babylon.2.1-alpha.debug.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  589. var d0 = Vector3.Dot(vector0, axis) - size;
  590. var d1 = Vector3.Dot(vector1, axis) - size;
  591. var s = d0 / (d0 - d1);
  592. return s;
  593. };
  594. Vector3.FromArray = function (array, offset) {
  595. if (!offset) {
  596. offset = 0;
  597. }
  598. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  599. };
  600. Vector3.FromArrayToRef = function (array, offset, result) {
  601. result.x = array[offset];
  602. result.y = array[offset + 1];
  603. result.z = array[offset + 2];
  604. };
  605. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  606. result.x = array[offset];
  607. result.y = array[offset + 1];
  608. result.z = array[offset + 2];
  609. };
  610. Vector3.FromFloatsToRef = function (x, y, z, result) {
  611. result.x = x;
  612. result.y = y;
  613. result.z = z;
  614. };
  615. Vector3.Zero = function () {
  616. return new Vector3(0, 0, 0);
  617. };
  618. Vector3.Up = function () {
  619. return new Vector3(0, 1.0, 0);
  620. };
  621. Vector3.TransformCoordinates = function (vector, transformation) {
  622. var result = Vector3.Zero();
  623. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  624. return result;
  625. };
  626. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  627. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  628. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  629. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  630. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  631. result.x = x / w;
  632. result.y = y / w;
  633. result.z = z / w;
  634. };
  635. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  636. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  637. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  638. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  639. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  640. result.x = rx / rw;
  641. result.y = ry / rw;
  642. result.z = rz / rw;
  643. };
  644. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  645. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  646. var m0 = SIMD.float32x4.load(transformation.m, 0);
  647. var m1 = SIMD.float32x4.load(transformation.m, 4);
  648. var m2 = SIMD.float32x4.load(transformation.m, 8);
  649. var m3 = SIMD.float32x4.load(transformation.m, 12);
  650. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  651. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  652. SIMD.float32x4.storeXYZ(result._data, 0, r);
  653. };
  654. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  655. var v0 = SIMD.float32x4.splat(x);
  656. var v1 = SIMD.float32x4.splat(y);
  657. var v2 = SIMD.float32x4.splat(z);
  658. var m0 = SIMD.float32x4.load(transformation.m, 0);
  659. var m1 = SIMD.float32x4.load(transformation.m, 4);
  660. var m2 = SIMD.float32x4.load(transformation.m, 8);
  661. var m3 = SIMD.float32x4.load(transformation.m, 12);
  662. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  663. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  664. SIMD.float32x4.storeXYZ(result._data, 0, r);
  665. };
  666. Vector3.TransformNormal = function (vector, transformation) {
  667. var result = Vector3.Zero();
  668. Vector3.TransformNormalToRef(vector, transformation, result);
  669. return result;
  670. };
  671. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  672. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  673. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  674. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  675. };
  676. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  677. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  678. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  679. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  680. };
  681. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  682. var squared = amount * amount;
  683. var cubed = amount * squared;
  684. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  685. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  686. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  687. return new Vector3(x, y, z);
  688. };
  689. Vector3.Clamp = function (value, min, max) {
  690. var x = value.x;
  691. x = (x > max.x) ? max.x : x;
  692. x = (x < min.x) ? min.x : x;
  693. var y = value.y;
  694. y = (y > max.y) ? max.y : y;
  695. y = (y < min.y) ? min.y : y;
  696. var z = value.z;
  697. z = (z > max.z) ? max.z : z;
  698. z = (z < min.z) ? min.z : z;
  699. return new Vector3(x, y, z);
  700. };
  701. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  702. var squared = amount * amount;
  703. var cubed = amount * squared;
  704. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  705. var part2 = (-2.0 * cubed) + (3.0 * squared);
  706. var part3 = (cubed - (2.0 * squared)) + amount;
  707. var part4 = cubed - squared;
  708. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  709. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  710. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Lerp = function (start, end, amount) {
  714. var x = start.x + ((end.x - start.x) * amount);
  715. var y = start.y + ((end.y - start.y) * amount);
  716. var z = start.z + ((end.z - start.z) * amount);
  717. return new Vector3(x, y, z);
  718. };
  719. Vector3.Dot = function (left, right) {
  720. return (left.x * right.x + left.y * right.y + left.z * right.z);
  721. };
  722. Vector3.Cross = function (left, right) {
  723. var result = Vector3.Zero();
  724. Vector3.CrossToRef(left, right, result);
  725. return result;
  726. };
  727. Vector3.CrossToRef = function (left, right, result) {
  728. result.x = left.y * right.z - left.z * right.y;
  729. result.y = left.z * right.x - left.x * right.z;
  730. result.z = left.x * right.y - left.y * right.x;
  731. };
  732. Vector3.Normalize = function (vector) {
  733. var result = Vector3.Zero();
  734. Vector3.NormalizeToRef(vector, result);
  735. return result;
  736. };
  737. Vector3.NormalizeToRef = function (vector, result) {
  738. result.copyFrom(vector);
  739. result.normalize();
  740. };
  741. Vector3.Project = function (vector, world, transform, viewport) {
  742. var cw = viewport.width;
  743. var ch = viewport.height;
  744. var cx = viewport.x;
  745. var cy = viewport.y;
  746. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  747. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  748. return Vector3.TransformCoordinates(vector, finalMatrix);
  749. };
  750. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  751. var matrix = world.multiply(transform);
  752. matrix.invert();
  753. source.x = source.x / viewportWidth * 2 - 1;
  754. source.y = -(source.y / viewportHeight * 2 - 1);
  755. var vector = Vector3.TransformCoordinates(source, matrix);
  756. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  757. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  758. vector = vector.scale(1.0 / num);
  759. }
  760. return vector;
  761. };
  762. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  763. var matrix = world.multiply(view).multiply(projection);
  764. matrix.invert();
  765. source.x = source.x / viewportWidth * 2 - 1;
  766. source.y = -(source.y / viewportHeight * 2 - 1);
  767. var vector = Vector3.TransformCoordinates(source, matrix);
  768. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  769. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  770. vector = vector.scale(1.0 / num);
  771. }
  772. return vector;
  773. };
  774. Vector3.Minimize = function (left, right) {
  775. var min = left.clone();
  776. min.MinimizeInPlace(right);
  777. return min;
  778. };
  779. Vector3.Maximize = function (left, right) {
  780. var max = left.clone();
  781. max.MaximizeInPlace(right);
  782. return max;
  783. };
  784. Vector3.Distance = function (value1, value2) {
  785. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  786. };
  787. Vector3.DistanceSquared = function (value1, value2) {
  788. var x = value1.x - value2.x;
  789. var y = value1.y - value2.y;
  790. var z = value1.z - value2.z;
  791. return (x * x) + (y * y) + (z * z);
  792. };
  793. Vector3.Center = function (value1, value2) {
  794. var center = value1.add(value2);
  795. center.scaleInPlace(0.5);
  796. return center;
  797. };
  798. return Vector3;
  799. })();
  800. BABYLON.Vector3 = Vector3;
  801. //Vector4 class created for EulerAngle class conversion to Quaternion
  802. var Vector4 = (function () {
  803. function Vector4(x, y, z, w) {
  804. this.x = x;
  805. this.y = y;
  806. this.z = z;
  807. this.w = w;
  808. }
  809. Vector4.prototype.toString = function () {
  810. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  811. };
  812. // Operators
  813. Vector4.prototype.asArray = function () {
  814. var result = [];
  815. this.toArray(result, 0);
  816. return result;
  817. };
  818. Vector4.prototype.toArray = function (array, index) {
  819. if (index === undefined) {
  820. index = 0;
  821. }
  822. array[index] = this.x;
  823. array[index + 1] = this.y;
  824. array[index + 2] = this.z;
  825. array[index + 3] = this.w;
  826. return this;
  827. };
  828. Vector4.prototype.addInPlace = function (otherVector) {
  829. this.x += otherVector.x;
  830. this.y += otherVector.y;
  831. this.z += otherVector.z;
  832. this.w += otherVector.w;
  833. return this;
  834. };
  835. Vector4.prototype.add = function (otherVector) {
  836. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  837. };
  838. Vector4.prototype.addToRef = function (otherVector, result) {
  839. result.x = this.x + otherVector.x;
  840. result.y = this.y + otherVector.y;
  841. result.z = this.z + otherVector.z;
  842. result.w = this.w + otherVector.w;
  843. return this;
  844. };
  845. Vector4.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. this.z -= otherVector.z;
  849. this.w -= otherVector.w;
  850. return this;
  851. };
  852. Vector4.prototype.subtract = function (otherVector) {
  853. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  854. };
  855. Vector4.prototype.subtractToRef = function (otherVector, result) {
  856. result.x = this.x - otherVector.x;
  857. result.y = this.y - otherVector.y;
  858. result.z = this.z - otherVector.z;
  859. result.w = this.w - otherVector.w;
  860. return this;
  861. };
  862. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  863. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  864. };
  865. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  866. result.x = this.x - x;
  867. result.y = this.y - y;
  868. result.z = this.z - z;
  869. result.w = this.w - w;
  870. return this;
  871. };
  872. Vector4.prototype.negate = function () {
  873. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  874. };
  875. Vector4.prototype.scaleInPlace = function (scale) {
  876. this.x *= scale;
  877. this.y *= scale;
  878. this.z *= scale;
  879. this.w *= scale;
  880. return this;
  881. };
  882. Vector4.prototype.scale = function (scale) {
  883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  884. };
  885. Vector4.prototype.scaleToRef = function (scale, result) {
  886. result.x = this.x * scale;
  887. result.y = this.y * scale;
  888. result.z = this.z * scale;
  889. result.w = this.w * scale;
  890. };
  891. Vector4.prototype.equals = function (otherVector) {
  892. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  893. };
  894. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  895. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  896. };
  897. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  898. return this.x === x && this.y === y && this.z === z && this.w === w;
  899. };
  900. Vector4.prototype.multiplyInPlace = function (otherVector) {
  901. this.x *= otherVector.x;
  902. this.y *= otherVector.y;
  903. this.z *= otherVector.z;
  904. this.w *= otherVector.w;
  905. return this;
  906. };
  907. Vector4.prototype.multiply = function (otherVector) {
  908. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  909. };
  910. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  911. result.x = this.x * otherVector.x;
  912. result.y = this.y * otherVector.y;
  913. result.z = this.z * otherVector.z;
  914. result.w = this.w * otherVector.w;
  915. return this;
  916. };
  917. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  918. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  919. };
  920. Vector4.prototype.divide = function (otherVector) {
  921. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  922. };
  923. Vector4.prototype.divideToRef = function (otherVector, result) {
  924. result.x = this.x / otherVector.x;
  925. result.y = this.y / otherVector.y;
  926. result.z = this.z / otherVector.z;
  927. result.w = this.w / otherVector.w;
  928. return this;
  929. };
  930. Vector4.prototype.MinimizeInPlace = function (other) {
  931. if (other.x < this.x)
  932. this.x = other.x;
  933. if (other.y < this.y)
  934. this.y = other.y;
  935. if (other.z < this.z)
  936. this.z = other.z;
  937. if (other.w < this.w)
  938. this.w = other.w;
  939. return this;
  940. };
  941. Vector4.prototype.MaximizeInPlace = function (other) {
  942. if (other.x > this.x)
  943. this.x = other.x;
  944. if (other.y > this.y)
  945. this.y = other.y;
  946. if (other.z > this.z)
  947. this.z = other.z;
  948. if (other.w > this.w)
  949. this.w = other.w;
  950. return this;
  951. };
  952. // Properties
  953. Vector4.prototype.length = function () {
  954. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  955. };
  956. Vector4.prototype.lengthSquared = function () {
  957. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  958. };
  959. // Methods
  960. Vector4.prototype.normalize = function () {
  961. var len = this.length();
  962. if (len === 0)
  963. return this;
  964. var num = 1.0 / len;
  965. this.x *= num;
  966. this.y *= num;
  967. this.z *= num;
  968. this.w *= num;
  969. return this;
  970. };
  971. Vector4.prototype.clone = function () {
  972. return new Vector4(this.x, this.y, this.z, this.w);
  973. };
  974. Vector4.prototype.copyFrom = function (source) {
  975. this.x = source.x;
  976. this.y = source.y;
  977. this.z = source.z;
  978. this.w = source.w;
  979. return this;
  980. };
  981. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  982. this.x = x;
  983. this.y = y;
  984. this.z = z;
  985. this.w = w;
  986. return this;
  987. };
  988. // Statics
  989. Vector4.FromArray = function (array, offset) {
  990. if (!offset) {
  991. offset = 0;
  992. }
  993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  994. };
  995. Vector4.FromArrayToRef = function (array, offset, result) {
  996. result.x = array[offset];
  997. result.y = array[offset + 1];
  998. result.z = array[offset + 2];
  999. result.w = array[offset + 3];
  1000. };
  1001. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1002. result.x = array[offset];
  1003. result.y = array[offset + 1];
  1004. result.z = array[offset + 2];
  1005. result.w = array[offset + 3];
  1006. };
  1007. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1008. result.x = x;
  1009. result.y = y;
  1010. result.z = z;
  1011. result.w = w;
  1012. };
  1013. Vector4.Zero = function () {
  1014. return new Vector4(0, 0, 0, 0);
  1015. };
  1016. Vector4.Normalize = function (vector) {
  1017. var result = Vector4.Zero();
  1018. Vector4.NormalizeToRef(vector, result);
  1019. return result;
  1020. };
  1021. Vector4.NormalizeToRef = function (vector, result) {
  1022. result.copyFrom(vector);
  1023. result.normalize();
  1024. };
  1025. Vector4.Minimize = function (left, right) {
  1026. var min = left.clone();
  1027. min.MinimizeInPlace(right);
  1028. return min;
  1029. };
  1030. Vector4.Maximize = function (left, right) {
  1031. var max = left.clone();
  1032. max.MaximizeInPlace(right);
  1033. return max;
  1034. };
  1035. Vector4.Distance = function (value1, value2) {
  1036. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1037. };
  1038. Vector4.DistanceSquared = function (value1, value2) {
  1039. var x = value1.x - value2.x;
  1040. var y = value1.y - value2.y;
  1041. var z = value1.z - value2.z;
  1042. var w = value1.w - value2.w;
  1043. return (x * x) + (y * y) + (z * z) + (w * w);
  1044. };
  1045. Vector4.Center = function (value1, value2) {
  1046. var center = value1.add(value2);
  1047. center.scaleInPlace(0.5);
  1048. return center;
  1049. };
  1050. return Vector4;
  1051. })();
  1052. BABYLON.Vector4 = Vector4;
  1053. var Quaternion = (function () {
  1054. function Quaternion(x, y, z, w) {
  1055. if (x === void 0) { x = 0; }
  1056. if (y === void 0) { y = 0; }
  1057. if (z === void 0) { z = 0; }
  1058. if (w === void 0) { w = 1; }
  1059. this.x = x;
  1060. this.y = y;
  1061. this.z = z;
  1062. this.w = w;
  1063. }
  1064. Quaternion.prototype.toString = function () {
  1065. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1066. };
  1067. Quaternion.prototype.asArray = function () {
  1068. return [this.x, this.y, this.z, this.w];
  1069. };
  1070. Quaternion.prototype.equals = function (otherQuaternion) {
  1071. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1072. };
  1073. Quaternion.prototype.clone = function () {
  1074. return new Quaternion(this.x, this.y, this.z, this.w);
  1075. };
  1076. Quaternion.prototype.copyFrom = function (other) {
  1077. this.x = other.x;
  1078. this.y = other.y;
  1079. this.z = other.z;
  1080. this.w = other.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1084. this.x = x;
  1085. this.y = y;
  1086. this.z = z;
  1087. this.w = w;
  1088. return this;
  1089. };
  1090. Quaternion.prototype.add = function (other) {
  1091. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1092. };
  1093. Quaternion.prototype.subtract = function (other) {
  1094. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1095. };
  1096. Quaternion.prototype.scale = function (value) {
  1097. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1098. };
  1099. Quaternion.prototype.multiply = function (q1) {
  1100. var result = new Quaternion(0, 0, 0, 1.0);
  1101. this.multiplyToRef(q1, result);
  1102. return result;
  1103. };
  1104. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1105. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1106. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1107. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1108. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1109. return this;
  1110. };
  1111. Quaternion.prototype.length = function () {
  1112. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1113. };
  1114. Quaternion.prototype.normalize = function () {
  1115. var length = 1.0 / this.length();
  1116. this.x *= length;
  1117. this.y *= length;
  1118. this.z *= length;
  1119. this.w *= length;
  1120. return this;
  1121. };
  1122. Quaternion.prototype.toEulerAngles = function () {
  1123. var result = Vector3.Zero();
  1124. this.toEulerAnglesToRef(result);
  1125. return result;
  1126. };
  1127. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1128. //result is an EulerAngles in the in the z-x-z convention
  1129. var qx = this.x;
  1130. var qy = this.y;
  1131. var qz = this.z;
  1132. var qw = this.w;
  1133. var qxy = qx * qy;
  1134. var qxz = qx * qz;
  1135. var qwy = qw * qy;
  1136. var qwz = qw * qz;
  1137. var qwx = qw * qx;
  1138. var qyz = qy * qz;
  1139. var sqx = qx * qx;
  1140. var sqy = qy * qy;
  1141. var determinant = sqx + sqy;
  1142. if (determinant !== 0.000 && determinant !== 1.000) {
  1143. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1144. result.y = Math.acos(1 - 2 * determinant);
  1145. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1146. }
  1147. else {
  1148. if (determinant === 0.0) {
  1149. result.x = 0.0;
  1150. result.y = 0.0;
  1151. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1152. }
  1153. else {
  1154. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1155. result.y = Math.PI;
  1156. result.z = 0.0;
  1157. }
  1158. }
  1159. return this;
  1160. };
  1161. Quaternion.prototype.toRotationMatrix = function (result) {
  1162. var xx = this.x * this.x;
  1163. var yy = this.y * this.y;
  1164. var zz = this.z * this.z;
  1165. var xy = this.x * this.y;
  1166. var zw = this.z * this.w;
  1167. var zx = this.z * this.x;
  1168. var yw = this.y * this.w;
  1169. var yz = this.y * this.z;
  1170. var xw = this.x * this.w;
  1171. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1172. result.m[1] = 2.0 * (xy + zw);
  1173. result.m[2] = 2.0 * (zx - yw);
  1174. result.m[3] = 0;
  1175. result.m[4] = 2.0 * (xy - zw);
  1176. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1177. result.m[6] = 2.0 * (yz + xw);
  1178. result.m[7] = 0;
  1179. result.m[8] = 2.0 * (zx + yw);
  1180. result.m[9] = 2.0 * (yz - xw);
  1181. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1182. result.m[11] = 0;
  1183. result.m[12] = 0;
  1184. result.m[13] = 0;
  1185. result.m[14] = 0;
  1186. result.m[15] = 1.0;
  1187. return this;
  1188. };
  1189. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1190. Quaternion.FromRotationMatrixToRef(matrix, this);
  1191. return this;
  1192. };
  1193. // Statics
  1194. Quaternion.FromRotationMatrix = function (matrix) {
  1195. var result = new Quaternion();
  1196. Quaternion.FromRotationMatrixToRef(matrix, result);
  1197. return result;
  1198. };
  1199. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1200. var data = matrix.m;
  1201. var m11 = data[0], m12 = data[4], m13 = data[8];
  1202. var m21 = data[1], m22 = data[5], m23 = data[9];
  1203. var m31 = data[2], m32 = data[6], m33 = data[10];
  1204. var trace = m11 + m22 + m33;
  1205. var s;
  1206. if (trace > 0) {
  1207. s = 0.5 / Math.sqrt(trace + 1.0);
  1208. result.w = 0.25 / s;
  1209. result.x = (m32 - m23) * s;
  1210. result.y = (m13 - m31) * s;
  1211. result.z = (m21 - m12) * s;
  1212. }
  1213. else if (m11 > m22 && m11 > m33) {
  1214. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1215. result.w = (m32 - m23) / s;
  1216. result.x = 0.25 * s;
  1217. result.y = (m12 + m21) / s;
  1218. result.z = (m13 + m31) / s;
  1219. }
  1220. else if (m22 > m33) {
  1221. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1222. result.w = (m13 - m31) / s;
  1223. result.x = (m12 + m21) / s;
  1224. result.y = 0.25 * s;
  1225. result.z = (m23 + m32) / s;
  1226. }
  1227. else {
  1228. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1229. result.w = (m21 - m12) / s;
  1230. result.x = (m13 + m31) / s;
  1231. result.y = (m23 + m32) / s;
  1232. result.z = 0.25 * s;
  1233. }
  1234. };
  1235. Quaternion.Inverse = function (q) {
  1236. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1237. };
  1238. Quaternion.Identity = function () {
  1239. return new Quaternion(0, 0, 0, 1);
  1240. };
  1241. Quaternion.RotationAxis = function (axis, angle) {
  1242. var result = new Quaternion();
  1243. var sin = Math.sin(angle / 2);
  1244. result.w = Math.cos(angle / 2);
  1245. result.x = axis.x * sin;
  1246. result.y = axis.y * sin;
  1247. result.z = axis.z * sin;
  1248. return result;
  1249. };
  1250. Quaternion.FromArray = function (array, offset) {
  1251. if (!offset) {
  1252. offset = 0;
  1253. }
  1254. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1255. };
  1256. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1257. var result = new Quaternion();
  1258. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1259. return result;
  1260. };
  1261. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1262. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1263. var halfRoll = roll * 0.5;
  1264. var halfPitch = pitch * 0.5;
  1265. var halfYaw = yaw * 0.5;
  1266. var sinRoll = Math.sin(halfRoll);
  1267. var cosRoll = Math.cos(halfRoll);
  1268. var sinPitch = Math.sin(halfPitch);
  1269. var cosPitch = Math.cos(halfPitch);
  1270. var sinYaw = Math.sin(halfYaw);
  1271. var cosYaw = Math.cos(halfYaw);
  1272. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1273. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1274. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1275. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1276. };
  1277. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1278. var result = new Quaternion();
  1279. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1280. return result;
  1281. };
  1282. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1283. // Produces a quaternion from Euler angles in the z-x-z orientation
  1284. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1285. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1286. var halfBeta = beta * 0.5;
  1287. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1288. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1289. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1290. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1291. };
  1292. Quaternion.Slerp = function (left, right, amount) {
  1293. var num2;
  1294. var num3;
  1295. var num = amount;
  1296. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1297. var flag = false;
  1298. if (num4 < 0) {
  1299. flag = true;
  1300. num4 = -num4;
  1301. }
  1302. if (num4 > 0.999999) {
  1303. num3 = 1 - num;
  1304. num2 = flag ? -num : num;
  1305. }
  1306. else {
  1307. var num5 = Math.acos(num4);
  1308. var num6 = (1.0 / Math.sin(num5));
  1309. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1310. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1311. }
  1312. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1313. };
  1314. return Quaternion;
  1315. })();
  1316. BABYLON.Quaternion = Quaternion;
  1317. var Matrix = (function () {
  1318. function Matrix() {
  1319. this.m = new Float32Array(16);
  1320. }
  1321. // Properties
  1322. Matrix.prototype.isIdentity = function () {
  1323. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1324. return false;
  1325. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1326. return false;
  1327. return true;
  1328. };
  1329. Matrix.prototype.determinant = function () {
  1330. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1331. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1332. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1333. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1334. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1335. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1336. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1337. };
  1338. // Methods
  1339. Matrix.prototype.toArray = function () {
  1340. return this.m;
  1341. };
  1342. Matrix.prototype.asArray = function () {
  1343. return this.toArray();
  1344. };
  1345. Matrix.prototype.invert = function () {
  1346. this.invertToRef(this);
  1347. return this;
  1348. };
  1349. Matrix.prototype.invertToRef = function (other) {
  1350. var l1 = this.m[0];
  1351. var l2 = this.m[1];
  1352. var l3 = this.m[2];
  1353. var l4 = this.m[3];
  1354. var l5 = this.m[4];
  1355. var l6 = this.m[5];
  1356. var l7 = this.m[6];
  1357. var l8 = this.m[7];
  1358. var l9 = this.m[8];
  1359. var l10 = this.m[9];
  1360. var l11 = this.m[10];
  1361. var l12 = this.m[11];
  1362. var l13 = this.m[12];
  1363. var l14 = this.m[13];
  1364. var l15 = this.m[14];
  1365. var l16 = this.m[15];
  1366. var l17 = (l11 * l16) - (l12 * l15);
  1367. var l18 = (l10 * l16) - (l12 * l14);
  1368. var l19 = (l10 * l15) - (l11 * l14);
  1369. var l20 = (l9 * l16) - (l12 * l13);
  1370. var l21 = (l9 * l15) - (l11 * l13);
  1371. var l22 = (l9 * l14) - (l10 * l13);
  1372. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1373. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1374. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1375. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1376. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1377. var l28 = (l7 * l16) - (l8 * l15);
  1378. var l29 = (l6 * l16) - (l8 * l14);
  1379. var l30 = (l6 * l15) - (l7 * l14);
  1380. var l31 = (l5 * l16) - (l8 * l13);
  1381. var l32 = (l5 * l15) - (l7 * l13);
  1382. var l33 = (l5 * l14) - (l6 * l13);
  1383. var l34 = (l7 * l12) - (l8 * l11);
  1384. var l35 = (l6 * l12) - (l8 * l10);
  1385. var l36 = (l6 * l11) - (l7 * l10);
  1386. var l37 = (l5 * l12) - (l8 * l9);
  1387. var l38 = (l5 * l11) - (l7 * l9);
  1388. var l39 = (l5 * l10) - (l6 * l9);
  1389. other.m[0] = l23 * l27;
  1390. other.m[4] = l24 * l27;
  1391. other.m[8] = l25 * l27;
  1392. other.m[12] = l26 * l27;
  1393. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1394. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1395. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1396. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1397. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1398. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1399. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1400. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1401. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1402. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1403. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1404. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1405. return this;
  1406. };
  1407. Matrix.prototype.invertToRefSIMD = function (other) {
  1408. var src = this.m;
  1409. var dest = other.m;
  1410. var row0, row1, row2, row3;
  1411. var tmp1;
  1412. var minor0, minor1, minor2, minor3;
  1413. var det;
  1414. // Load the 4 rows
  1415. var src0 = SIMD.float32x4.load(src, 0);
  1416. var src1 = SIMD.float32x4.load(src, 4);
  1417. var src2 = SIMD.float32x4.load(src, 8);
  1418. var src3 = SIMD.float32x4.load(src, 12);
  1419. // Transpose the source matrix. Sort of. Not a true transpose operation
  1420. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1421. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1422. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1423. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1424. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1425. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1426. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1427. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1428. // This is a true transposition, but it will lead to an incorrect result
  1429. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1430. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1431. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1432. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1433. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1434. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1435. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1436. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1437. // ----
  1438. tmp1 = SIMD.float32x4.mul(row2, row3);
  1439. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1440. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1441. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1442. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1443. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1444. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1445. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1446. // ----
  1447. tmp1 = SIMD.float32x4.mul(row1, row2);
  1448. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1449. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1450. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1451. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1452. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1453. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1454. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1455. // ----
  1456. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1457. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1458. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1459. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1460. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1461. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1462. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1463. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1464. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1465. // ----
  1466. tmp1 = SIMD.float32x4.mul(row0, row1);
  1467. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1468. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1469. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1470. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1471. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1472. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1473. // ----
  1474. tmp1 = SIMD.float32x4.mul(row0, row3);
  1475. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1476. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1477. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1478. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1479. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1480. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1481. // ----
  1482. tmp1 = SIMD.float32x4.mul(row0, row2);
  1483. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1484. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1485. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1486. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1487. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1488. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1489. // Compute determinant
  1490. det = SIMD.float32x4.mul(row0, minor0);
  1491. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1492. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1493. tmp1 = SIMD.float32x4.reciprocal(det);
  1494. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1495. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1496. // These shuffles aren't necessary if the faulty transposition is done
  1497. // up at the top of this function.
  1498. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1499. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1500. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1501. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1502. // Compute final values by multiplying with 1/det
  1503. minor0 = SIMD.float32x4.mul(det, minor0);
  1504. minor1 = SIMD.float32x4.mul(det, minor1);
  1505. minor2 = SIMD.float32x4.mul(det, minor2);
  1506. minor3 = SIMD.float32x4.mul(det, minor3);
  1507. SIMD.float32x4.store(dest, 0, minor0);
  1508. SIMD.float32x4.store(dest, 4, minor1);
  1509. SIMD.float32x4.store(dest, 8, minor2);
  1510. SIMD.float32x4.store(dest, 12, minor3);
  1511. return this;
  1512. };
  1513. Matrix.prototype.setTranslation = function (vector3) {
  1514. this.m[12] = vector3.x;
  1515. this.m[13] = vector3.y;
  1516. this.m[14] = vector3.z;
  1517. return this;
  1518. };
  1519. Matrix.prototype.multiply = function (other) {
  1520. var result = new Matrix();
  1521. this.multiplyToRef(other, result);
  1522. return result;
  1523. };
  1524. Matrix.prototype.copyFrom = function (other) {
  1525. for (var index = 0; index < 16; index++) {
  1526. this.m[index] = other.m[index];
  1527. }
  1528. return this;
  1529. };
  1530. Matrix.prototype.copyToArray = function (array, offset) {
  1531. if (offset === void 0) { offset = 0; }
  1532. for (var index = 0; index < 16; index++) {
  1533. array[offset + index] = this.m[index];
  1534. }
  1535. return this;
  1536. };
  1537. Matrix.prototype.multiplyToRef = function (other, result) {
  1538. this.multiplyToArray(other, result.m, 0);
  1539. return this;
  1540. };
  1541. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1542. var tm0 = this.m[0];
  1543. var tm1 = this.m[1];
  1544. var tm2 = this.m[2];
  1545. var tm3 = this.m[3];
  1546. var tm4 = this.m[4];
  1547. var tm5 = this.m[5];
  1548. var tm6 = this.m[6];
  1549. var tm7 = this.m[7];
  1550. var tm8 = this.m[8];
  1551. var tm9 = this.m[9];
  1552. var tm10 = this.m[10];
  1553. var tm11 = this.m[11];
  1554. var tm12 = this.m[12];
  1555. var tm13 = this.m[13];
  1556. var tm14 = this.m[14];
  1557. var tm15 = this.m[15];
  1558. var om0 = other.m[0];
  1559. var om1 = other.m[1];
  1560. var om2 = other.m[2];
  1561. var om3 = other.m[3];
  1562. var om4 = other.m[4];
  1563. var om5 = other.m[5];
  1564. var om6 = other.m[6];
  1565. var om7 = other.m[7];
  1566. var om8 = other.m[8];
  1567. var om9 = other.m[9];
  1568. var om10 = other.m[10];
  1569. var om11 = other.m[11];
  1570. var om12 = other.m[12];
  1571. var om13 = other.m[13];
  1572. var om14 = other.m[14];
  1573. var om15 = other.m[15];
  1574. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1575. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1576. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1577. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1578. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1579. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1580. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1581. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1582. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1583. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1584. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1585. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1586. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1587. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1588. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1589. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1590. return this;
  1591. };
  1592. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1593. if (offset === void 0) { offset = 0; }
  1594. var tm = this.m;
  1595. var om = other.m;
  1596. var om0 = SIMD.float32x4.load(om, 0);
  1597. var om1 = SIMD.float32x4.load(om, 4);
  1598. var om2 = SIMD.float32x4.load(om, 8);
  1599. var om3 = SIMD.float32x4.load(om, 12);
  1600. var tm0 = SIMD.float32x4.load(tm, 0);
  1601. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1602. var tm1 = SIMD.float32x4.load(tm, 4);
  1603. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1604. var tm2 = SIMD.float32x4.load(tm, 8);
  1605. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1606. var tm3 = SIMD.float32x4.load(tm, 12);
  1607. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1608. };
  1609. Matrix.prototype.equals = function (value) {
  1610. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1611. };
  1612. Matrix.prototype.clone = function () {
  1613. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1614. };
  1615. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1616. translation.x = this.m[12];
  1617. translation.y = this.m[13];
  1618. translation.z = this.m[14];
  1619. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1620. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1621. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1622. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1623. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1624. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1625. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1626. rotation.x = 0;
  1627. rotation.y = 0;
  1628. rotation.z = 0;
  1629. rotation.w = 1;
  1630. return false;
  1631. }
  1632. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1633. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1634. return true;
  1635. };
  1636. // Statics
  1637. Matrix.FromArray = function (array, offset) {
  1638. var result = new Matrix();
  1639. if (!offset) {
  1640. offset = 0;
  1641. }
  1642. Matrix.FromArrayToRef(array, offset, result);
  1643. return result;
  1644. };
  1645. Matrix.FromArrayToRef = function (array, offset, result) {
  1646. for (var index = 0; index < 16; index++) {
  1647. result.m[index] = array[index + offset];
  1648. }
  1649. };
  1650. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1651. result.m[0] = initialM11;
  1652. result.m[1] = initialM12;
  1653. result.m[2] = initialM13;
  1654. result.m[3] = initialM14;
  1655. result.m[4] = initialM21;
  1656. result.m[5] = initialM22;
  1657. result.m[6] = initialM23;
  1658. result.m[7] = initialM24;
  1659. result.m[8] = initialM31;
  1660. result.m[9] = initialM32;
  1661. result.m[10] = initialM33;
  1662. result.m[11] = initialM34;
  1663. result.m[12] = initialM41;
  1664. result.m[13] = initialM42;
  1665. result.m[14] = initialM43;
  1666. result.m[15] = initialM44;
  1667. };
  1668. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1669. var result = new Matrix();
  1670. result.m[0] = initialM11;
  1671. result.m[1] = initialM12;
  1672. result.m[2] = initialM13;
  1673. result.m[3] = initialM14;
  1674. result.m[4] = initialM21;
  1675. result.m[5] = initialM22;
  1676. result.m[6] = initialM23;
  1677. result.m[7] = initialM24;
  1678. result.m[8] = initialM31;
  1679. result.m[9] = initialM32;
  1680. result.m[10] = initialM33;
  1681. result.m[11] = initialM34;
  1682. result.m[12] = initialM41;
  1683. result.m[13] = initialM42;
  1684. result.m[14] = initialM43;
  1685. result.m[15] = initialM44;
  1686. return result;
  1687. };
  1688. Matrix.Compose = function (scale, rotation, translation) {
  1689. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1690. var rotationMatrix = Matrix.Identity();
  1691. rotation.toRotationMatrix(rotationMatrix);
  1692. result = result.multiply(rotationMatrix);
  1693. result.setTranslation(translation);
  1694. return result;
  1695. };
  1696. Matrix.Identity = function () {
  1697. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1698. };
  1699. Matrix.IdentityToRef = function (result) {
  1700. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1701. };
  1702. Matrix.Zero = function () {
  1703. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1704. };
  1705. Matrix.RotationX = function (angle) {
  1706. var result = new Matrix();
  1707. Matrix.RotationXToRef(angle, result);
  1708. return result;
  1709. };
  1710. Matrix.Invert = function (source) {
  1711. var result = new Matrix();
  1712. source.invertToRef(result);
  1713. return result;
  1714. };
  1715. Matrix.RotationXToRef = function (angle, result) {
  1716. var s = Math.sin(angle);
  1717. var c = Math.cos(angle);
  1718. result.m[0] = 1.0;
  1719. result.m[15] = 1.0;
  1720. result.m[5] = c;
  1721. result.m[10] = c;
  1722. result.m[9] = -s;
  1723. result.m[6] = s;
  1724. result.m[1] = 0;
  1725. result.m[2] = 0;
  1726. result.m[3] = 0;
  1727. result.m[4] = 0;
  1728. result.m[7] = 0;
  1729. result.m[8] = 0;
  1730. result.m[11] = 0;
  1731. result.m[12] = 0;
  1732. result.m[13] = 0;
  1733. result.m[14] = 0;
  1734. };
  1735. Matrix.RotationY = function (angle) {
  1736. var result = new Matrix();
  1737. Matrix.RotationYToRef(angle, result);
  1738. return result;
  1739. };
  1740. Matrix.RotationYToRef = function (angle, result) {
  1741. var s = Math.sin(angle);
  1742. var c = Math.cos(angle);
  1743. result.m[5] = 1.0;
  1744. result.m[15] = 1.0;
  1745. result.m[0] = c;
  1746. result.m[2] = -s;
  1747. result.m[8] = s;
  1748. result.m[10] = c;
  1749. result.m[1] = 0;
  1750. result.m[3] = 0;
  1751. result.m[4] = 0;
  1752. result.m[6] = 0;
  1753. result.m[7] = 0;
  1754. result.m[9] = 0;
  1755. result.m[11] = 0;
  1756. result.m[12] = 0;
  1757. result.m[13] = 0;
  1758. result.m[14] = 0;
  1759. };
  1760. Matrix.RotationZ = function (angle) {
  1761. var result = new Matrix();
  1762. Matrix.RotationZToRef(angle, result);
  1763. return result;
  1764. };
  1765. Matrix.RotationZToRef = function (angle, result) {
  1766. var s = Math.sin(angle);
  1767. var c = Math.cos(angle);
  1768. result.m[10] = 1.0;
  1769. result.m[15] = 1.0;
  1770. result.m[0] = c;
  1771. result.m[1] = s;
  1772. result.m[4] = -s;
  1773. result.m[5] = c;
  1774. result.m[2] = 0;
  1775. result.m[3] = 0;
  1776. result.m[6] = 0;
  1777. result.m[7] = 0;
  1778. result.m[8] = 0;
  1779. result.m[9] = 0;
  1780. result.m[11] = 0;
  1781. result.m[12] = 0;
  1782. result.m[13] = 0;
  1783. result.m[14] = 0;
  1784. };
  1785. Matrix.RotationAxis = function (axis, angle) {
  1786. var s = Math.sin(-angle);
  1787. var c = Math.cos(-angle);
  1788. var c1 = 1 - c;
  1789. axis.normalize();
  1790. var result = Matrix.Zero();
  1791. result.m[0] = (axis.x * axis.x) * c1 + c;
  1792. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1793. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1794. result.m[3] = 0.0;
  1795. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1796. result.m[5] = (axis.y * axis.y) * c1 + c;
  1797. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1798. result.m[7] = 0.0;
  1799. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1800. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1801. result.m[10] = (axis.z * axis.z) * c1 + c;
  1802. result.m[11] = 0.0;
  1803. result.m[15] = 1.0;
  1804. return result;
  1805. };
  1806. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1807. var result = new Matrix();
  1808. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1809. return result;
  1810. };
  1811. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1812. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1813. this._tempQuaternion.toRotationMatrix(result);
  1814. };
  1815. Matrix.Scaling = function (x, y, z) {
  1816. var result = Matrix.Zero();
  1817. Matrix.ScalingToRef(x, y, z, result);
  1818. return result;
  1819. };
  1820. Matrix.ScalingToRef = function (x, y, z, result) {
  1821. result.m[0] = x;
  1822. result.m[1] = 0;
  1823. result.m[2] = 0;
  1824. result.m[3] = 0;
  1825. result.m[4] = 0;
  1826. result.m[5] = y;
  1827. result.m[6] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[9] = 0;
  1831. result.m[10] = z;
  1832. result.m[11] = 0;
  1833. result.m[12] = 0;
  1834. result.m[13] = 0;
  1835. result.m[14] = 0;
  1836. result.m[15] = 1.0;
  1837. };
  1838. Matrix.Translation = function (x, y, z) {
  1839. var result = Matrix.Identity();
  1840. Matrix.TranslationToRef(x, y, z, result);
  1841. return result;
  1842. };
  1843. Matrix.TranslationToRef = function (x, y, z, result) {
  1844. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1845. };
  1846. Matrix.LookAtLH = function (eye, target, up) {
  1847. var result = Matrix.Zero();
  1848. Matrix.LookAtLHToRef(eye, target, up, result);
  1849. return result;
  1850. };
  1851. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1852. // Z axis
  1853. target.subtractToRef(eye, this._zAxis);
  1854. this._zAxis.normalize();
  1855. // X axis
  1856. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1857. this._xAxis.normalize();
  1858. // Y axis
  1859. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1860. this._yAxis.normalize();
  1861. // Eye angles
  1862. var ex = -Vector3.Dot(this._xAxis, eye);
  1863. var ey = -Vector3.Dot(this._yAxis, eye);
  1864. var ez = -Vector3.Dot(this._zAxis, eye);
  1865. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1866. };
  1867. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1868. var out = result.m;
  1869. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1870. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1871. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1872. // cc.kmVec3Subtract(f, pCenter, pEye);
  1873. var f = SIMD.float32x4.sub(center, eye);
  1874. // cc.kmVec3Normalize(f, f);
  1875. var tmp = SIMD.float32x4.mul(f, f);
  1876. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1877. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrt(tmp));
  1878. // cc.kmVec3Assign(up, pUp);
  1879. // cc.kmVec3Normalize(up, up);
  1880. tmp = SIMD.float32x4.mul(up, up);
  1881. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1882. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrt(tmp));
  1883. // cc.kmVec3Cross(s, f, up);
  1884. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  1885. // cc.kmVec3Normalize(s, s);
  1886. tmp = SIMD.float32x4.mul(s, s);
  1887. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1888. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1889. // cc.kmVec3Cross(u, s, f);
  1890. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  1891. // cc.kmVec3Normalize(s, s);
  1892. tmp = SIMD.float32x4.mul(s, s);
  1893. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1894. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1895. //cc.kmMat4Identity(pOut);
  1896. //pOut.mat[0] = s.x;
  1897. //pOut.mat[4] = s.y;
  1898. //pOut.mat[8] = s.z;
  1899. //pOut.mat[1] = u.x;
  1900. //pOut.mat[5] = u.y;
  1901. //pOut.mat[9] = u.z;
  1902. //pOut.mat[2] = -f.x;
  1903. //pOut.mat[6] = -f.y;
  1904. //pOut.mat[10] = -f.z;
  1905. var zero = SIMD.float32x4.splat(0.0);
  1906. s = SIMD.float32x4.neg(s);
  1907. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1908. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1909. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1910. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1911. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1912. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1913. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1914. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1915. // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z);
  1916. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1917. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1918. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1919. var b3 = SIMD.float32x4.neg(eye);
  1920. b3 = SIMD.float32x4.withW(b3, 1.0);
  1921. // cc.kmMat4Multiply(pOut, pOut, translate);
  1922. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  1923. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  1924. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  1925. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  1926. };
  1927. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1928. var matrix = Matrix.Zero();
  1929. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1930. return matrix;
  1931. };
  1932. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1933. var hw = 2.0 / width;
  1934. var hh = 2.0 / height;
  1935. var id = 1.0 / (zfar - znear);
  1936. var nid = znear / (znear - zfar);
  1937. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1938. };
  1939. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1940. var matrix = Matrix.Zero();
  1941. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1942. return matrix;
  1943. };
  1944. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1945. result.m[0] = 2.0 / (right - left);
  1946. result.m[1] = result.m[2] = result.m[3] = 0;
  1947. result.m[5] = 2.0 / (top - bottom);
  1948. result.m[4] = result.m[6] = result.m[7] = 0;
  1949. result.m[10] = -1.0 / (znear - zfar);
  1950. result.m[8] = result.m[9] = result.m[11] = 0;
  1951. result.m[12] = (left + right) / (left - right);
  1952. result.m[13] = (top + bottom) / (bottom - top);
  1953. result.m[14] = znear / (znear - zfar);
  1954. result.m[15] = 1.0;
  1955. };
  1956. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1957. var matrix = Matrix.Zero();
  1958. matrix.m[0] = (2.0 * znear) / width;
  1959. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1960. matrix.m[5] = (2.0 * znear) / height;
  1961. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1962. matrix.m[10] = -zfar / (znear - zfar);
  1963. matrix.m[8] = matrix.m[9] = 0.0;
  1964. matrix.m[11] = 1.0;
  1965. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1966. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1967. return matrix;
  1968. };
  1969. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1970. var matrix = Matrix.Zero();
  1971. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1972. return matrix;
  1973. };
  1974. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1975. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1976. var tan = 1.0 / (Math.tan(fov * 0.5));
  1977. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1978. if (v_fixed) {
  1979. result.m[0] = tan / aspect;
  1980. }
  1981. else {
  1982. result.m[0] = tan;
  1983. }
  1984. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1985. if (v_fixed) {
  1986. result.m[5] = tan;
  1987. }
  1988. else {
  1989. result.m[5] = tan * aspect;
  1990. }
  1991. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1992. result.m[8] = result.m[9] = 0.0;
  1993. result.m[10] = -zfar / (znear - zfar);
  1994. result.m[11] = 1.0;
  1995. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1996. result.m[14] = (znear * zfar) / (znear - zfar);
  1997. };
  1998. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1999. var cw = viewport.width;
  2000. var ch = viewport.height;
  2001. var cx = viewport.x;
  2002. var cy = viewport.y;
  2003. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2004. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2005. };
  2006. Matrix.Transpose = function (matrix) {
  2007. var result = new Matrix();
  2008. result.m[0] = matrix.m[0];
  2009. result.m[1] = matrix.m[4];
  2010. result.m[2] = matrix.m[8];
  2011. result.m[3] = matrix.m[12];
  2012. result.m[4] = matrix.m[1];
  2013. result.m[5] = matrix.m[5];
  2014. result.m[6] = matrix.m[9];
  2015. result.m[7] = matrix.m[13];
  2016. result.m[8] = matrix.m[2];
  2017. result.m[9] = matrix.m[6];
  2018. result.m[10] = matrix.m[10];
  2019. result.m[11] = matrix.m[14];
  2020. result.m[12] = matrix.m[3];
  2021. result.m[13] = matrix.m[7];
  2022. result.m[14] = matrix.m[11];
  2023. result.m[15] = matrix.m[15];
  2024. return result;
  2025. };
  2026. Matrix.Reflection = function (plane) {
  2027. var matrix = new Matrix();
  2028. Matrix.ReflectionToRef(plane, matrix);
  2029. return matrix;
  2030. };
  2031. Matrix.ReflectionToRef = function (plane, result) {
  2032. plane.normalize();
  2033. var x = plane.normal.x;
  2034. var y = plane.normal.y;
  2035. var z = plane.normal.z;
  2036. var temp = -2 * x;
  2037. var temp2 = -2 * y;
  2038. var temp3 = -2 * z;
  2039. result.m[0] = (temp * x) + 1;
  2040. result.m[1] = temp2 * x;
  2041. result.m[2] = temp3 * x;
  2042. result.m[3] = 0.0;
  2043. result.m[4] = temp * y;
  2044. result.m[5] = (temp2 * y) + 1;
  2045. result.m[6] = temp3 * y;
  2046. result.m[7] = 0.0;
  2047. result.m[8] = temp * z;
  2048. result.m[9] = temp2 * z;
  2049. result.m[10] = (temp3 * z) + 1;
  2050. result.m[11] = 0.0;
  2051. result.m[12] = temp * plane.d;
  2052. result.m[13] = temp2 * plane.d;
  2053. result.m[14] = temp3 * plane.d;
  2054. result.m[15] = 1.0;
  2055. };
  2056. Matrix._tempQuaternion = new Quaternion();
  2057. Matrix._xAxis = Vector3.Zero();
  2058. Matrix._yAxis = Vector3.Zero();
  2059. Matrix._zAxis = Vector3.Zero();
  2060. return Matrix;
  2061. })();
  2062. BABYLON.Matrix = Matrix;
  2063. var Plane = (function () {
  2064. function Plane(a, b, c, d) {
  2065. this.normal = new Vector3(a, b, c);
  2066. this.d = d;
  2067. }
  2068. Plane.prototype.asArray = function () {
  2069. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2070. };
  2071. // Methods
  2072. Plane.prototype.clone = function () {
  2073. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2074. };
  2075. Plane.prototype.normalize = function () {
  2076. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2077. var magnitude = 0;
  2078. if (norm !== 0) {
  2079. magnitude = 1.0 / norm;
  2080. }
  2081. this.normal.x *= magnitude;
  2082. this.normal.y *= magnitude;
  2083. this.normal.z *= magnitude;
  2084. this.d *= magnitude;
  2085. return this;
  2086. };
  2087. Plane.prototype.transform = function (transformation) {
  2088. var transposedMatrix = Matrix.Transpose(transformation);
  2089. var x = this.normal.x;
  2090. var y = this.normal.y;
  2091. var z = this.normal.z;
  2092. var d = this.d;
  2093. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2094. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2095. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2096. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2097. return new Plane(normalX, normalY, normalZ, finalD);
  2098. };
  2099. Plane.prototype.dotCoordinate = function (point) {
  2100. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2101. };
  2102. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2103. var x1 = point2.x - point1.x;
  2104. var y1 = point2.y - point1.y;
  2105. var z1 = point2.z - point1.z;
  2106. var x2 = point3.x - point1.x;
  2107. var y2 = point3.y - point1.y;
  2108. var z2 = point3.z - point1.z;
  2109. var yz = (y1 * z2) - (z1 * y2);
  2110. var xz = (z1 * x2) - (x1 * z2);
  2111. var xy = (x1 * y2) - (y1 * x2);
  2112. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2113. var invPyth;
  2114. if (pyth !== 0) {
  2115. invPyth = 1.0 / pyth;
  2116. }
  2117. else {
  2118. invPyth = 0;
  2119. }
  2120. this.normal.x = yz * invPyth;
  2121. this.normal.y = xz * invPyth;
  2122. this.normal.z = xy * invPyth;
  2123. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2124. return this;
  2125. };
  2126. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2127. var dot = Vector3.Dot(this.normal, direction);
  2128. return (dot <= epsilon);
  2129. };
  2130. Plane.prototype.signedDistanceTo = function (point) {
  2131. return Vector3.Dot(point, this.normal) + this.d;
  2132. };
  2133. // Statics
  2134. Plane.FromArray = function (array) {
  2135. return new Plane(array[0], array[1], array[2], array[3]);
  2136. };
  2137. Plane.FromPoints = function (point1, point2, point3) {
  2138. var result = new Plane(0, 0, 0, 0);
  2139. result.copyFromPoints(point1, point2, point3);
  2140. return result;
  2141. };
  2142. Plane.FromPositionAndNormal = function (origin, normal) {
  2143. var result = new Plane(0, 0, 0, 0);
  2144. normal.normalize();
  2145. result.normal = normal;
  2146. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2147. return result;
  2148. };
  2149. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2150. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2151. return Vector3.Dot(point, normal) + d;
  2152. };
  2153. return Plane;
  2154. })();
  2155. BABYLON.Plane = Plane;
  2156. var Viewport = (function () {
  2157. function Viewport(x, y, width, height) {
  2158. this.x = x;
  2159. this.y = y;
  2160. this.width = width;
  2161. this.height = height;
  2162. }
  2163. Viewport.prototype.toGlobal = function (engine) {
  2164. var width = engine.getRenderWidth();
  2165. var height = engine.getRenderHeight();
  2166. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2167. };
  2168. return Viewport;
  2169. })();
  2170. BABYLON.Viewport = Viewport;
  2171. var Frustum = (function () {
  2172. function Frustum() {
  2173. }
  2174. Frustum.GetPlanes = function (transform) {
  2175. var frustumPlanes = [];
  2176. for (var index = 0; index < 6; index++) {
  2177. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2178. }
  2179. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2180. return frustumPlanes;
  2181. };
  2182. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2183. // Near
  2184. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2185. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2186. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2187. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2188. frustumPlanes[0].normalize();
  2189. // Far
  2190. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2191. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2192. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2193. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2194. frustumPlanes[1].normalize();
  2195. // Left
  2196. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2197. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2198. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2199. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2200. frustumPlanes[2].normalize();
  2201. // Right
  2202. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2203. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2204. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2205. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2206. frustumPlanes[3].normalize();
  2207. // Top
  2208. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2209. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2210. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2211. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2212. frustumPlanes[4].normalize();
  2213. // Bottom
  2214. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2215. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2216. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2217. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2218. frustumPlanes[5].normalize();
  2219. };
  2220. return Frustum;
  2221. })();
  2222. BABYLON.Frustum = Frustum;
  2223. var Ray = (function () {
  2224. function Ray(origin, direction, length) {
  2225. if (length === void 0) { length = Number.MAX_VALUE; }
  2226. this.origin = origin;
  2227. this.direction = direction;
  2228. this.length = length;
  2229. }
  2230. // Methods
  2231. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2232. var d = 0.0;
  2233. var maxValue = Number.MAX_VALUE;
  2234. if (Math.abs(this.direction.x) < 0.0000001) {
  2235. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2236. return false;
  2237. }
  2238. }
  2239. else {
  2240. var inv = 1.0 / this.direction.x;
  2241. var min = (minimum.x - this.origin.x) * inv;
  2242. var max = (maximum.x - this.origin.x) * inv;
  2243. if (max === -Infinity) {
  2244. max = Infinity;
  2245. }
  2246. if (min > max) {
  2247. var temp = min;
  2248. min = max;
  2249. max = temp;
  2250. }
  2251. d = Math.max(min, d);
  2252. maxValue = Math.min(max, maxValue);
  2253. if (d > maxValue) {
  2254. return false;
  2255. }
  2256. }
  2257. if (Math.abs(this.direction.y) < 0.0000001) {
  2258. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2259. return false;
  2260. }
  2261. }
  2262. else {
  2263. inv = 1.0 / this.direction.y;
  2264. min = (minimum.y - this.origin.y) * inv;
  2265. max = (maximum.y - this.origin.y) * inv;
  2266. if (max === -Infinity) {
  2267. max = Infinity;
  2268. }
  2269. if (min > max) {
  2270. temp = min;
  2271. min = max;
  2272. max = temp;
  2273. }
  2274. d = Math.max(min, d);
  2275. maxValue = Math.min(max, maxValue);
  2276. if (d > maxValue) {
  2277. return false;
  2278. }
  2279. }
  2280. if (Math.abs(this.direction.z) < 0.0000001) {
  2281. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2282. return false;
  2283. }
  2284. }
  2285. else {
  2286. inv = 1.0 / this.direction.z;
  2287. min = (minimum.z - this.origin.z) * inv;
  2288. max = (maximum.z - this.origin.z) * inv;
  2289. if (max === -Infinity) {
  2290. max = Infinity;
  2291. }
  2292. if (min > max) {
  2293. temp = min;
  2294. min = max;
  2295. max = temp;
  2296. }
  2297. d = Math.max(min, d);
  2298. maxValue = Math.min(max, maxValue);
  2299. if (d > maxValue) {
  2300. return false;
  2301. }
  2302. }
  2303. return true;
  2304. };
  2305. Ray.prototype.intersectsBox = function (box) {
  2306. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2307. };
  2308. Ray.prototype.intersectsSphere = function (sphere) {
  2309. var x = sphere.center.x - this.origin.x;
  2310. var y = sphere.center.y - this.origin.y;
  2311. var z = sphere.center.z - this.origin.z;
  2312. var pyth = (x * x) + (y * y) + (z * z);
  2313. var rr = sphere.radius * sphere.radius;
  2314. if (pyth <= rr) {
  2315. return true;
  2316. }
  2317. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2318. if (dot < 0.0) {
  2319. return false;
  2320. }
  2321. var temp = pyth - (dot * dot);
  2322. return temp <= rr;
  2323. };
  2324. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2325. if (!this._edge1) {
  2326. this._edge1 = Vector3.Zero();
  2327. this._edge2 = Vector3.Zero();
  2328. this._pvec = Vector3.Zero();
  2329. this._tvec = Vector3.Zero();
  2330. this._qvec = Vector3.Zero();
  2331. }
  2332. vertex1.subtractToRef(vertex0, this._edge1);
  2333. vertex2.subtractToRef(vertex0, this._edge2);
  2334. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2335. var det = Vector3.Dot(this._edge1, this._pvec);
  2336. if (det === 0) {
  2337. return null;
  2338. }
  2339. var invdet = 1 / det;
  2340. this.origin.subtractToRef(vertex0, this._tvec);
  2341. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2342. if (bu < 0 || bu > 1.0) {
  2343. return null;
  2344. }
  2345. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2346. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2347. if (bv < 0 || bu + bv > 1.0) {
  2348. return null;
  2349. }
  2350. //check if the distance is longer than the predefined length.
  2351. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2352. if (distance > this.length) {
  2353. return null;
  2354. }
  2355. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2356. };
  2357. // Statics
  2358. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2359. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2360. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2361. var direction = end.subtract(start);
  2362. direction.normalize();
  2363. return new Ray(start, direction);
  2364. };
  2365. /**
  2366. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2367. * transformed to the given world matrix.
  2368. * @param origin The origin point
  2369. * @param end The end point
  2370. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2371. */
  2372. Ray.CreateNewFromTo = function (origin, end, world) {
  2373. if (world === void 0) { world = Matrix.Identity(); }
  2374. var direction = end.subtract(origin);
  2375. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2376. direction.normalize();
  2377. return Ray.Transform(new Ray(origin, direction, length), world);
  2378. };
  2379. Ray.Transform = function (ray, matrix) {
  2380. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2381. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2382. return new Ray(newOrigin, newDirection, ray.length);
  2383. };
  2384. return Ray;
  2385. })();
  2386. BABYLON.Ray = Ray;
  2387. (function (Space) {
  2388. Space[Space["LOCAL"] = 0] = "LOCAL";
  2389. Space[Space["WORLD"] = 1] = "WORLD";
  2390. })(BABYLON.Space || (BABYLON.Space = {}));
  2391. var Space = BABYLON.Space;
  2392. var Axis = (function () {
  2393. function Axis() {
  2394. }
  2395. Axis.X = new Vector3(1, 0, 0);
  2396. Axis.Y = new Vector3(0, 1, 0);
  2397. Axis.Z = new Vector3(0, 0, 1);
  2398. return Axis;
  2399. })();
  2400. BABYLON.Axis = Axis;
  2401. ;
  2402. var BezierCurve = (function () {
  2403. function BezierCurve() {
  2404. }
  2405. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2406. // Extract X (which is equal to time here)
  2407. var f0 = 1 - 3 * x2 + 3 * x1;
  2408. var f1 = 3 * x2 - 6 * x1;
  2409. var f2 = 3 * x1;
  2410. var refinedT = t;
  2411. for (var i = 0; i < 5; i++) {
  2412. var refinedT2 = refinedT * refinedT;
  2413. var refinedT3 = refinedT2 * refinedT;
  2414. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2415. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2416. refinedT -= (x - t) * slope;
  2417. refinedT = Math.min(1, Math.max(0, refinedT));
  2418. }
  2419. // Resolve cubic bezier for the given x
  2420. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2421. };
  2422. return BezierCurve;
  2423. })();
  2424. BABYLON.BezierCurve = BezierCurve;
  2425. (function (Orientation) {
  2426. Orientation[Orientation["CW"] = 0] = "CW";
  2427. Orientation[Orientation["CCW"] = 1] = "CCW";
  2428. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2429. var Orientation = BABYLON.Orientation;
  2430. var Angle = (function () {
  2431. function Angle(radians) {
  2432. var _this = this;
  2433. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2434. this.radians = function () { return _this._radians; };
  2435. this._radians = radians;
  2436. if (this._radians < 0)
  2437. this._radians += (2 * Math.PI);
  2438. }
  2439. Angle.BetweenTwoPoints = function (a, b) {
  2440. var delta = b.subtract(a);
  2441. var theta = Math.atan2(delta.y, delta.x);
  2442. return new Angle(theta);
  2443. };
  2444. Angle.FromRadians = function (radians) {
  2445. return new Angle(radians);
  2446. };
  2447. Angle.FromDegrees = function (degrees) {
  2448. return new Angle(degrees * Math.PI / 180);
  2449. };
  2450. return Angle;
  2451. })();
  2452. BABYLON.Angle = Angle;
  2453. var Arc2 = (function () {
  2454. function Arc2(startPoint, midPoint, endPoint) {
  2455. this.startPoint = startPoint;
  2456. this.midPoint = midPoint;
  2457. this.endPoint = endPoint;
  2458. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2459. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2460. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2461. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2462. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2463. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2464. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2465. var a1 = this.startAngle.degrees();
  2466. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2467. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2468. // angles correction
  2469. if (a2 - a1 > +180.0)
  2470. a2 -= 360.0;
  2471. if (a2 - a1 < -180.0)
  2472. a2 += 360.0;
  2473. if (a3 - a2 > +180.0)
  2474. a3 -= 360.0;
  2475. if (a3 - a2 < -180.0)
  2476. a3 += 360.0;
  2477. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2478. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2479. }
  2480. return Arc2;
  2481. })();
  2482. BABYLON.Arc2 = Arc2;
  2483. var PathCursor = (function () {
  2484. function PathCursor(path) {
  2485. this.path = path;
  2486. this._onchange = new Array();
  2487. this.value = 0;
  2488. this.animations = new Array();
  2489. }
  2490. PathCursor.prototype.getPoint = function () {
  2491. var point = this.path.getPointAtLengthPosition(this.value);
  2492. return new Vector3(point.x, 0, point.y);
  2493. };
  2494. PathCursor.prototype.moveAhead = function (step) {
  2495. if (step === void 0) { step = 0.002; }
  2496. this.move(step);
  2497. return this;
  2498. };
  2499. PathCursor.prototype.moveBack = function (step) {
  2500. if (step === void 0) { step = 0.002; }
  2501. this.move(-step);
  2502. return this;
  2503. };
  2504. PathCursor.prototype.move = function (step) {
  2505. if (Math.abs(step) > 1) {
  2506. throw "step size should be less than 1.";
  2507. }
  2508. this.value += step;
  2509. this.ensureLimits();
  2510. this.raiseOnChange();
  2511. return this;
  2512. };
  2513. PathCursor.prototype.ensureLimits = function () {
  2514. while (this.value > 1) {
  2515. this.value -= 1;
  2516. }
  2517. while (this.value < 0) {
  2518. this.value += 1;
  2519. }
  2520. return this;
  2521. };
  2522. // used by animation engine
  2523. PathCursor.prototype.markAsDirty = function (propertyName) {
  2524. this.ensureLimits();
  2525. this.raiseOnChange();
  2526. return this;
  2527. };
  2528. PathCursor.prototype.raiseOnChange = function () {
  2529. var _this = this;
  2530. this._onchange.forEach(function (f) { return f(_this); });
  2531. return this;
  2532. };
  2533. PathCursor.prototype.onchange = function (f) {
  2534. this._onchange.push(f);
  2535. return this;
  2536. };
  2537. return PathCursor;
  2538. })();
  2539. BABYLON.PathCursor = PathCursor;
  2540. var Path2 = (function () {
  2541. function Path2(x, y) {
  2542. this._points = new Array();
  2543. this._length = 0;
  2544. this.closed = false;
  2545. this._points.push(new Vector2(x, y));
  2546. }
  2547. Path2.prototype.addLineTo = function (x, y) {
  2548. if (closed) {
  2549. BABYLON.Tools.Error("cannot add lines to closed paths");
  2550. return this;
  2551. }
  2552. var newPoint = new Vector2(x, y);
  2553. var previousPoint = this._points[this._points.length - 1];
  2554. this._points.push(newPoint);
  2555. this._length += newPoint.subtract(previousPoint).length();
  2556. return this;
  2557. };
  2558. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2559. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2560. if (closed) {
  2561. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2562. return this;
  2563. }
  2564. var startPoint = this._points[this._points.length - 1];
  2565. var midPoint = new Vector2(midX, midY);
  2566. var endPoint = new Vector2(endX, endY);
  2567. var arc = new Arc2(startPoint, midPoint, endPoint);
  2568. var increment = arc.angle.radians() / numberOfSegments;
  2569. if (arc.orientation === 0 /* CW */)
  2570. increment *= -1;
  2571. var currentAngle = arc.startAngle.radians() + increment;
  2572. for (var i = 0; i < numberOfSegments; i++) {
  2573. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2574. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2575. this.addLineTo(x, y);
  2576. currentAngle += increment;
  2577. }
  2578. return this;
  2579. };
  2580. Path2.prototype.close = function () {
  2581. this.closed = true;
  2582. return this;
  2583. };
  2584. Path2.prototype.length = function () {
  2585. var result = this._length;
  2586. if (!this.closed) {
  2587. var lastPoint = this._points[this._points.length - 1];
  2588. var firstPoint = this._points[0];
  2589. result += (firstPoint.subtract(lastPoint).length());
  2590. }
  2591. return result;
  2592. };
  2593. Path2.prototype.getPoints = function () {
  2594. return this._points;
  2595. };
  2596. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2597. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2598. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2599. return Vector2.Zero();
  2600. }
  2601. var lengthPosition = normalizedLengthPosition * this.length();
  2602. var previousOffset = 0;
  2603. for (var i = 0; i < this._points.length; i++) {
  2604. var j = (i + 1) % this._points.length;
  2605. var a = this._points[i];
  2606. var b = this._points[j];
  2607. var bToA = b.subtract(a);
  2608. var nextOffset = (bToA.length() + previousOffset);
  2609. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2610. var dir = bToA.normalize();
  2611. var localOffset = lengthPosition - previousOffset;
  2612. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2613. }
  2614. previousOffset = nextOffset;
  2615. }
  2616. BABYLON.Tools.Error("internal error");
  2617. return Vector2.Zero();
  2618. };
  2619. Path2.StartingAt = function (x, y) {
  2620. return new Path2(x, y);
  2621. };
  2622. return Path2;
  2623. })();
  2624. BABYLON.Path2 = Path2;
  2625. var Path3D = (function () {
  2626. function Path3D(path) {
  2627. this.path = path;
  2628. this._curve = new Array();
  2629. this._distances = new Array();
  2630. this._tangents = new Array();
  2631. this._normals = new Array();
  2632. this._binormals = new Array();
  2633. this._curve = path.slice(); // copy array
  2634. this._compute();
  2635. }
  2636. Path3D.prototype.getCurve = function () {
  2637. return this._curve;
  2638. };
  2639. Path3D.prototype.getTangents = function () {
  2640. return this._tangents;
  2641. };
  2642. Path3D.prototype.getNormals = function () {
  2643. return this._normals;
  2644. };
  2645. Path3D.prototype.getBinormals = function () {
  2646. return this._binormals;
  2647. };
  2648. Path3D.prototype.getDistances = function () {
  2649. return this._distances;
  2650. };
  2651. Path3D.prototype.update = function (path) {
  2652. for (var i = 0; i < path.length; i++) {
  2653. this._curve[i] = path[i];
  2654. }
  2655. this._compute();
  2656. return this;
  2657. };
  2658. // private function compute() : computes tangents, normals and binormals
  2659. Path3D.prototype._compute = function () {
  2660. var l = this._curve.length;
  2661. // first and last tangents
  2662. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2663. this._tangents[0].normalize();
  2664. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2665. this._tangents[l - 1].normalize();
  2666. // normals and binormals at first point : arbitrary vector with _normalVector()
  2667. var tg0 = this._tangents[0];
  2668. var pp0 = this._normalVector(this._curve[0], tg0);
  2669. this._normals[0] = pp0;
  2670. this._normals[0].normalize();
  2671. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2672. this._normals[0].normalize();
  2673. this._distances[0] = 0;
  2674. // normals and binormals : next points
  2675. var prev; // previous vector (segment)
  2676. var cur; // current vector (segment)
  2677. var curTang; // current tangent
  2678. var prevNorm; // previous normal
  2679. var prevBinor; // previous binormal
  2680. for (var i = 1; i < l; i++) {
  2681. // tangents
  2682. prev = this._curve[i].subtract(this._curve[i - 1]);
  2683. if (i < l - 1) {
  2684. cur = this._curve[i + 1].subtract(this._curve[i]);
  2685. this._tangents[i] = prev.add(cur);
  2686. this._tangents[i].normalize();
  2687. }
  2688. this._distances[i] = this._distances[i - 1] + prev.length();
  2689. // normals and binormals
  2690. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2691. curTang = this._tangents[i];
  2692. prevNorm = this._normals[i - 1];
  2693. prevBinor = this._binormals[i - 1];
  2694. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2695. this._normals[i].normalize();
  2696. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2697. this._binormals[i].normalize();
  2698. }
  2699. };
  2700. // private function normalVector(v0, vt) :
  2701. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2702. Path3D.prototype._normalVector = function (v0, vt) {
  2703. var point;
  2704. if (vt.x !== 1) {
  2705. point = new Vector3(1, 0, 0);
  2706. }
  2707. else if (vt.y !== 1) {
  2708. point = new Vector3(0, 1, 0);
  2709. }
  2710. else if (vt.z !== 1) {
  2711. point = new Vector3(0, 0, 1);
  2712. }
  2713. var normal0 = Vector3.Cross(vt, point);
  2714. normal0.normalize();
  2715. return normal0;
  2716. };
  2717. return Path3D;
  2718. })();
  2719. BABYLON.Path3D = Path3D;
  2720. var Curve3 = (function () {
  2721. function Curve3(points) {
  2722. this._points = points;
  2723. }
  2724. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2725. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2726. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2727. var bez = new Array();
  2728. var step = 1 / nbPoints;
  2729. var equation = function (t, val0, val1, val2) {
  2730. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2731. return res;
  2732. };
  2733. for (var i = 0; i <= 1; i += step) {
  2734. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2735. }
  2736. return new Curve3(bez);
  2737. };
  2738. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2739. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2740. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2741. var bez = new Array();
  2742. var step = 1 / nbPoints;
  2743. var equation = function (t, val0, val1, val2, val3) {
  2744. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2745. return res;
  2746. };
  2747. for (var i = 0; i <= 1; i += step) {
  2748. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2749. }
  2750. return new Curve3(bez);
  2751. };
  2752. Curve3.prototype.getPoints = function () {
  2753. return this._points;
  2754. };
  2755. Curve3.prototype.continue = function (curve) {
  2756. var lastPoint = this._points[this._points.length - 1];
  2757. var continuedPoints = this._points.slice();
  2758. var curvePoints = curve.getPoints();
  2759. for (var i = 1; i < curvePoints.length; i++) {
  2760. continuedPoints.push(curvePoints[i].add(lastPoint));
  2761. }
  2762. return new Curve3(continuedPoints);
  2763. };
  2764. return Curve3;
  2765. })();
  2766. BABYLON.Curve3 = Curve3;
  2767. // Vertex formats
  2768. var PositionNormalVertex = (function () {
  2769. function PositionNormalVertex(position, normal) {
  2770. if (position === void 0) { position = Vector3.Zero(); }
  2771. if (normal === void 0) { normal = Vector3.Up(); }
  2772. this.position = position;
  2773. this.normal = normal;
  2774. }
  2775. PositionNormalVertex.prototype.clone = function () {
  2776. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2777. };
  2778. return PositionNormalVertex;
  2779. })();
  2780. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2781. var PositionNormalTextureVertex = (function () {
  2782. function PositionNormalTextureVertex(position, normal, uv) {
  2783. if (position === void 0) { position = Vector3.Zero(); }
  2784. if (normal === void 0) { normal = Vector3.Up(); }
  2785. if (uv === void 0) { uv = Vector2.Zero(); }
  2786. this.position = position;
  2787. this.normal = normal;
  2788. this.uv = uv;
  2789. }
  2790. PositionNormalTextureVertex.prototype.clone = function () {
  2791. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2792. };
  2793. return PositionNormalTextureVertex;
  2794. })();
  2795. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2796. // SIMD
  2797. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2798. var previousInvertToRef = Matrix.prototype.invertToRef;
  2799. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2800. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2801. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2802. var SIMDHelper = (function () {
  2803. function SIMDHelper() {
  2804. }
  2805. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2806. get: function () {
  2807. return SIMDHelper._isEnabled;
  2808. },
  2809. enumerable: true,
  2810. configurable: true
  2811. });
  2812. SIMDHelper.DisableSIMD = function () {
  2813. // Replace functions
  2814. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2815. Matrix.prototype.invertToRef = previousInvertToRef;
  2816. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2817. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2818. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2819. SIMDHelper._isEnabled = false;
  2820. };
  2821. SIMDHelper.EnableSIMD = function () {
  2822. if (window.SIMD === undefined) {
  2823. return;
  2824. }
  2825. // Replace functions
  2826. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2827. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2828. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2829. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2830. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2831. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2832. get: function () {
  2833. return this._data[0];
  2834. },
  2835. set: function (value) {
  2836. if (!this._data) {
  2837. this._data = new Float32Array(3);
  2838. }
  2839. this._data[0] = value;
  2840. }
  2841. });
  2842. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2843. get: function () {
  2844. return this._data[1];
  2845. },
  2846. set: function (value) {
  2847. this._data[1] = value;
  2848. }
  2849. });
  2850. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2851. get: function () {
  2852. return this._data[2];
  2853. },
  2854. set: function (value) {
  2855. this._data[2] = value;
  2856. }
  2857. });
  2858. SIMDHelper._isEnabled = true;
  2859. };
  2860. SIMDHelper._isEnabled = false;
  2861. return SIMDHelper;
  2862. })();
  2863. BABYLON.SIMDHelper = SIMDHelper;
  2864. if (window.SIMD !== undefined) {
  2865. SIMDHelper.EnableSIMD();
  2866. }
  2867. })(BABYLON || (BABYLON = {}));
  2868. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2869. (function (BABYLON) {
  2870. // Screenshots
  2871. var screenshotCanvas;
  2872. var cloneValue = function (source, destinationObject) {
  2873. if (!source)
  2874. return null;
  2875. if (source instanceof BABYLON.Mesh) {
  2876. return null;
  2877. }
  2878. if (source instanceof BABYLON.SubMesh) {
  2879. return source.clone(destinationObject);
  2880. }
  2881. else if (source.clone) {
  2882. return source.clone();
  2883. }
  2884. return null;
  2885. };
  2886. var Tools = (function () {
  2887. function Tools() {
  2888. }
  2889. Tools.GetFilename = function (path) {
  2890. var index = path.lastIndexOf("/");
  2891. if (index < 0)
  2892. return path;
  2893. return path.substring(index + 1);
  2894. };
  2895. Tools.GetDOMTextContent = function (element) {
  2896. var result = "";
  2897. var child = element.firstChild;
  2898. while (child) {
  2899. if (child.nodeType === 3) {
  2900. result += child.textContent;
  2901. }
  2902. child = child.nextSibling;
  2903. }
  2904. return result;
  2905. };
  2906. Tools.ToDegrees = function (angle) {
  2907. return angle * 180 / Math.PI;
  2908. };
  2909. Tools.ToRadians = function (angle) {
  2910. return angle * Math.PI / 180;
  2911. };
  2912. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2913. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2914. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2915. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2916. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2917. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2918. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2919. }
  2920. return {
  2921. minimum: minimum,
  2922. maximum: maximum
  2923. };
  2924. };
  2925. Tools.ExtractMinAndMax = function (positions, start, count) {
  2926. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2927. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2928. for (var index = start; index < start + count; index++) {
  2929. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2930. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2931. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2932. }
  2933. return {
  2934. minimum: minimum,
  2935. maximum: maximum
  2936. };
  2937. };
  2938. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2939. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2940. return undefined;
  2941. return Array.isArray(obj) ? obj : [obj];
  2942. };
  2943. // Misc.
  2944. Tools.GetPointerPrefix = function () {
  2945. var eventPrefix = "pointer";
  2946. // Check if hand.js is referenced or if the browser natively supports pointer events
  2947. if (!navigator.pointerEnabled) {
  2948. eventPrefix = "mouse";
  2949. }
  2950. return eventPrefix;
  2951. };
  2952. Tools.QueueNewFrame = function (func) {
  2953. if (window.requestAnimationFrame)
  2954. window.requestAnimationFrame(func);
  2955. else if (window.msRequestAnimationFrame)
  2956. window.msRequestAnimationFrame(func);
  2957. else if (window.webkitRequestAnimationFrame)
  2958. window.webkitRequestAnimationFrame(func);
  2959. else if (window.mozRequestAnimationFrame)
  2960. window.mozRequestAnimationFrame(func);
  2961. else if (window.oRequestAnimationFrame)
  2962. window.oRequestAnimationFrame(func);
  2963. else {
  2964. window.setTimeout(func, 16);
  2965. }
  2966. };
  2967. Tools.RequestFullscreen = function (element) {
  2968. if (element.requestFullscreen)
  2969. element.requestFullscreen();
  2970. else if (element.msRequestFullscreen)
  2971. element.msRequestFullscreen();
  2972. else if (element.webkitRequestFullscreen)
  2973. element.webkitRequestFullscreen();
  2974. else if (element.mozRequestFullScreen)
  2975. element.mozRequestFullScreen();
  2976. };
  2977. Tools.ExitFullscreen = function () {
  2978. if (document.exitFullscreen) {
  2979. document.exitFullscreen();
  2980. }
  2981. else if (document.mozCancelFullScreen) {
  2982. document.mozCancelFullScreen();
  2983. }
  2984. else if (document.webkitCancelFullScreen) {
  2985. document.webkitCancelFullScreen();
  2986. }
  2987. else if (document.msCancelFullScreen) {
  2988. document.msCancelFullScreen();
  2989. }
  2990. };
  2991. // External files
  2992. Tools.CleanUrl = function (url) {
  2993. url = url.replace(/#/mg, "%23");
  2994. return url;
  2995. };
  2996. Tools.LoadImage = function (url, onload, onerror, database) {
  2997. url = Tools.CleanUrl(url);
  2998. var img = new Image();
  2999. if (url.substr(0, 5) !== "data:")
  3000. img.crossOrigin = 'anonymous';
  3001. img.onload = function () {
  3002. onload(img);
  3003. };
  3004. img.onerror = function (err) {
  3005. onerror(img, err);
  3006. };
  3007. var noIndexedDB = function () {
  3008. img.src = url;
  3009. };
  3010. var loadFromIndexedDB = function () {
  3011. database.loadImageFromDB(url, img);
  3012. };
  3013. //ANY database to do!
  3014. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  3015. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3016. }
  3017. else {
  3018. if (url.indexOf("file:") === -1) {
  3019. noIndexedDB();
  3020. }
  3021. else {
  3022. try {
  3023. var textureName = url.substring(5);
  3024. var blobURL;
  3025. try {
  3026. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  3027. }
  3028. catch (ex) {
  3029. // Chrome doesn't support oneTimeOnly parameter
  3030. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  3031. }
  3032. img.src = blobURL;
  3033. }
  3034. catch (e) {
  3035. Tools.Log("Error while trying to load texture: " + textureName);
  3036. img.src = null;
  3037. }
  3038. }
  3039. }
  3040. return img;
  3041. };
  3042. //ANY
  3043. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  3044. url = Tools.CleanUrl(url);
  3045. var noIndexedDB = function () {
  3046. var request = new XMLHttpRequest();
  3047. var loadUrl = Tools.BaseUrl + url;
  3048. request.open('GET', loadUrl, true);
  3049. if (useArrayBuffer) {
  3050. request.responseType = "arraybuffer";
  3051. }
  3052. request.onprogress = progressCallBack;
  3053. request.onreadystatechange = function () {
  3054. if (request.readyState === 4) {
  3055. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  3056. callback(!useArrayBuffer ? request.responseText : request.response);
  3057. }
  3058. else {
  3059. if (onError) {
  3060. onError();
  3061. }
  3062. else {
  3063. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  3064. }
  3065. }
  3066. }
  3067. };
  3068. request.send(null);
  3069. };
  3070. var loadFromIndexedDB = function () {
  3071. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  3072. };
  3073. if (url.indexOf("file:") !== -1) {
  3074. var fileName = url.substring(5);
  3075. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  3076. }
  3077. else {
  3078. // Caching all files
  3079. if (database && database.enableSceneOffline) {
  3080. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3081. }
  3082. else {
  3083. noIndexedDB();
  3084. }
  3085. }
  3086. };
  3087. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3088. var reader = new FileReader();
  3089. reader.onload = function (e) {
  3090. //target doesn't have result from ts 1.3
  3091. callback(e.target['result']);
  3092. };
  3093. reader.onprogress = progressCallback;
  3094. reader.readAsDataURL(fileToLoad);
  3095. };
  3096. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3097. var reader = new FileReader();
  3098. reader.onerror = function (e) {
  3099. Tools.Log("Error while reading file: " + fileToLoad.name);
  3100. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3101. };
  3102. reader.onload = function (e) {
  3103. //target doesn't have result from ts 1.3
  3104. callback(e.target['result']);
  3105. };
  3106. reader.onprogress = progressCallBack;
  3107. if (!useArrayBuffer) {
  3108. // Asynchronous read
  3109. reader.readAsText(fileToLoad);
  3110. }
  3111. else {
  3112. reader.readAsArrayBuffer(fileToLoad);
  3113. }
  3114. };
  3115. // Misc.
  3116. Tools.Clamp = function (value, min, max) {
  3117. if (min === void 0) { min = 0; }
  3118. if (max === void 0) { max = 1; }
  3119. return Math.min(max, Math.max(min, value));
  3120. };
  3121. // Returns -1 when value is a negative number and
  3122. // +1 when value is a positive number.
  3123. Tools.Sign = function (value) {
  3124. value = +value; // convert to a number
  3125. if (value === 0 || isNaN(value))
  3126. return value;
  3127. return value > 0 ? 1 : -1;
  3128. };
  3129. Tools.Format = function (value, decimals) {
  3130. if (decimals === void 0) { decimals = 2; }
  3131. return value.toFixed(decimals);
  3132. };
  3133. Tools.CheckExtends = function (v, min, max) {
  3134. if (v.x < min.x)
  3135. min.x = v.x;
  3136. if (v.y < min.y)
  3137. min.y = v.y;
  3138. if (v.z < min.z)
  3139. min.z = v.z;
  3140. if (v.x > max.x)
  3141. max.x = v.x;
  3142. if (v.y > max.y)
  3143. max.y = v.y;
  3144. if (v.z > max.z)
  3145. max.z = v.z;
  3146. };
  3147. Tools.WithinEpsilon = function (a, b, epsilon) {
  3148. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3149. var num = a - b;
  3150. return -epsilon <= num && num <= epsilon;
  3151. };
  3152. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3153. for (var prop in source) {
  3154. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3155. continue;
  3156. }
  3157. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3158. continue;
  3159. }
  3160. var sourceValue = source[prop];
  3161. var typeOfSourceValue = typeof sourceValue;
  3162. if (typeOfSourceValue === "function") {
  3163. continue;
  3164. }
  3165. if (typeOfSourceValue === "object") {
  3166. if (sourceValue instanceof Array) {
  3167. destination[prop] = [];
  3168. if (sourceValue.length > 0) {
  3169. if (typeof sourceValue[0] == "object") {
  3170. for (var index = 0; index < sourceValue.length; index++) {
  3171. var clonedValue = cloneValue(sourceValue[index], destination);
  3172. if (destination[prop].indexOf(clonedValue) === -1) {
  3173. destination[prop].push(clonedValue);
  3174. }
  3175. }
  3176. }
  3177. else {
  3178. destination[prop] = sourceValue.slice(0);
  3179. }
  3180. }
  3181. }
  3182. else {
  3183. destination[prop] = cloneValue(sourceValue, destination);
  3184. }
  3185. }
  3186. else {
  3187. destination[prop] = sourceValue;
  3188. }
  3189. }
  3190. };
  3191. Tools.IsEmpty = function (obj) {
  3192. for (var i in obj) {
  3193. return false;
  3194. }
  3195. return true;
  3196. };
  3197. Tools.RegisterTopRootEvents = function (events) {
  3198. for (var index = 0; index < events.length; index++) {
  3199. var event = events[index];
  3200. window.addEventListener(event.name, event.handler, false);
  3201. try {
  3202. if (window.parent) {
  3203. window.parent.addEventListener(event.name, event.handler, false);
  3204. }
  3205. }
  3206. catch (e) {
  3207. }
  3208. }
  3209. };
  3210. Tools.UnregisterTopRootEvents = function (events) {
  3211. for (var index = 0; index < events.length; index++) {
  3212. var event = events[index];
  3213. window.removeEventListener(event.name, event.handler);
  3214. try {
  3215. if (window.parent) {
  3216. window.parent.removeEventListener(event.name, event.handler);
  3217. }
  3218. }
  3219. catch (e) {
  3220. }
  3221. }
  3222. };
  3223. Tools.DumpFramebuffer = function (width, height, engine) {
  3224. // Read the contents of the framebuffer
  3225. var numberOfChannelsByLine = width * 4;
  3226. var halfHeight = height / 2;
  3227. //Reading datas from WebGL
  3228. var data = engine.readPixels(0, 0, width, height);
  3229. for (var i = 0; i < halfHeight; i++) {
  3230. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3231. var currentCell = j + i * numberOfChannelsByLine;
  3232. var targetLine = height - i - 1;
  3233. var targetCell = j + targetLine * numberOfChannelsByLine;
  3234. var temp = data[currentCell];
  3235. data[currentCell] = data[targetCell];
  3236. data[targetCell] = temp;
  3237. }
  3238. }
  3239. // Create a 2D canvas to store the result
  3240. if (!screenshotCanvas) {
  3241. screenshotCanvas = document.createElement('canvas');
  3242. }
  3243. screenshotCanvas.width = width;
  3244. screenshotCanvas.height = height;
  3245. var context = screenshotCanvas.getContext('2d');
  3246. // Copy the pixels to a 2D canvas
  3247. var imageData = context.createImageData(width, height);
  3248. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3249. var castData = imageData.data;
  3250. castData.set(data);
  3251. context.putImageData(imageData, 0, 0);
  3252. var base64Image = screenshotCanvas.toDataURL();
  3253. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3254. if (("download" in document.createElement("a"))) {
  3255. var a = window.document.createElement("a");
  3256. a.href = base64Image;
  3257. var date = new Date();
  3258. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3259. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3260. window.document.body.appendChild(a);
  3261. a.addEventListener("click", function () {
  3262. a.parentElement.removeChild(a);
  3263. });
  3264. a.click();
  3265. }
  3266. else {
  3267. var newWindow = window.open("");
  3268. var img = newWindow.document.createElement("img");
  3269. img.src = base64Image;
  3270. newWindow.document.body.appendChild(img);
  3271. }
  3272. };
  3273. Tools.CreateScreenshot = function (engine, camera, size) {
  3274. var width;
  3275. var height;
  3276. var scene = camera.getScene();
  3277. var previousCamera = null;
  3278. if (scene.activeCamera !== camera) {
  3279. previousCamera = scene.activeCamera;
  3280. scene.activeCamera = camera;
  3281. }
  3282. //If a precision value is specified
  3283. if (size.precision) {
  3284. width = Math.round(engine.getRenderWidth() * size.precision);
  3285. height = Math.round(width / engine.getAspectRatio(camera));
  3286. size = { width: width, height: height };
  3287. }
  3288. else if (size.width && size.height) {
  3289. width = size.width;
  3290. height = size.height;
  3291. }
  3292. else if (size.width && !size.height) {
  3293. width = size.width;
  3294. height = Math.round(width / engine.getAspectRatio(camera));
  3295. size = { width: width, height: height };
  3296. }
  3297. else if (size.height && !size.width) {
  3298. height = size.height;
  3299. width = Math.round(height * engine.getAspectRatio(camera));
  3300. size = { width: width, height: height };
  3301. }
  3302. else if (!isNaN(size)) {
  3303. height = size;
  3304. width = size;
  3305. }
  3306. else {
  3307. Tools.Error("Invalid 'size' parameter !");
  3308. return;
  3309. }
  3310. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3311. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3312. texture.renderList = scene.meshes;
  3313. texture.onAfterRender = function () {
  3314. Tools.DumpFramebuffer(width, height, engine);
  3315. };
  3316. scene.incrementRenderId();
  3317. texture.render(true);
  3318. texture.dispose();
  3319. if (previousCamera) {
  3320. scene.activeCamera = previousCamera;
  3321. }
  3322. };
  3323. // XHR response validator for local file scenario
  3324. Tools.ValidateXHRData = function (xhr, dataType) {
  3325. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3326. if (dataType === void 0) { dataType = 7; }
  3327. try {
  3328. if (dataType & 1) {
  3329. if (xhr.responseText && xhr.responseText.length > 0) {
  3330. return true;
  3331. }
  3332. else if (dataType === 1) {
  3333. return false;
  3334. }
  3335. }
  3336. if (dataType & 2) {
  3337. // Check header width and height since there is no "TGA" magic number
  3338. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3339. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3340. return true;
  3341. }
  3342. else if (dataType === 2) {
  3343. return false;
  3344. }
  3345. }
  3346. if (dataType & 4) {
  3347. // Check for the "DDS" magic number
  3348. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3349. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3350. return true;
  3351. }
  3352. else {
  3353. return false;
  3354. }
  3355. }
  3356. }
  3357. catch (e) {
  3358. }
  3359. return false;
  3360. };
  3361. Object.defineProperty(Tools, "NoneLogLevel", {
  3362. get: function () {
  3363. return Tools._NoneLogLevel;
  3364. },
  3365. enumerable: true,
  3366. configurable: true
  3367. });
  3368. Object.defineProperty(Tools, "MessageLogLevel", {
  3369. get: function () {
  3370. return Tools._MessageLogLevel;
  3371. },
  3372. enumerable: true,
  3373. configurable: true
  3374. });
  3375. Object.defineProperty(Tools, "WarningLogLevel", {
  3376. get: function () {
  3377. return Tools._WarningLogLevel;
  3378. },
  3379. enumerable: true,
  3380. configurable: true
  3381. });
  3382. Object.defineProperty(Tools, "ErrorLogLevel", {
  3383. get: function () {
  3384. return Tools._ErrorLogLevel;
  3385. },
  3386. enumerable: true,
  3387. configurable: true
  3388. });
  3389. Object.defineProperty(Tools, "AllLogLevel", {
  3390. get: function () {
  3391. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3392. },
  3393. enumerable: true,
  3394. configurable: true
  3395. });
  3396. Tools._AddLogEntry = function (entry) {
  3397. Tools._LogCache = entry + Tools._LogCache;
  3398. if (Tools.OnNewCacheEntry) {
  3399. Tools.OnNewCacheEntry(entry);
  3400. }
  3401. };
  3402. Tools._FormatMessage = function (message) {
  3403. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3404. var date = new Date();
  3405. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3406. };
  3407. Tools._LogDisabled = function (message) {
  3408. // nothing to do
  3409. };
  3410. Tools._LogEnabled = function (message) {
  3411. var formattedMessage = Tools._FormatMessage(message);
  3412. console.log("BJS - " + formattedMessage);
  3413. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3414. Tools._AddLogEntry(entry);
  3415. };
  3416. Tools._WarnDisabled = function (message) {
  3417. // nothing to do
  3418. };
  3419. Tools._WarnEnabled = function (message) {
  3420. var formattedMessage = Tools._FormatMessage(message);
  3421. console.warn("BJS - " + formattedMessage);
  3422. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3423. Tools._AddLogEntry(entry);
  3424. };
  3425. Tools._ErrorDisabled = function (message) {
  3426. // nothing to do
  3427. };
  3428. Tools._ErrorEnabled = function (message) {
  3429. var formattedMessage = Tools._FormatMessage(message);
  3430. console.error("BJS - " + formattedMessage);
  3431. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3432. Tools._AddLogEntry(entry);
  3433. };
  3434. Object.defineProperty(Tools, "LogCache", {
  3435. get: function () {
  3436. return Tools._LogCache;
  3437. },
  3438. enumerable: true,
  3439. configurable: true
  3440. });
  3441. Object.defineProperty(Tools, "LogLevels", {
  3442. set: function (level) {
  3443. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3444. Tools.Log = Tools._LogEnabled;
  3445. }
  3446. else {
  3447. Tools.Log = Tools._LogDisabled;
  3448. }
  3449. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3450. Tools.Warn = Tools._WarnEnabled;
  3451. }
  3452. else {
  3453. Tools.Warn = Tools._WarnDisabled;
  3454. }
  3455. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3456. Tools.Error = Tools._ErrorEnabled;
  3457. }
  3458. else {
  3459. Tools.Error = Tools._ErrorDisabled;
  3460. }
  3461. },
  3462. enumerable: true,
  3463. configurable: true
  3464. });
  3465. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3466. get: function () {
  3467. return Tools._PerformanceNoneLogLevel;
  3468. },
  3469. enumerable: true,
  3470. configurable: true
  3471. });
  3472. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3473. get: function () {
  3474. return Tools._PerformanceUserMarkLogLevel;
  3475. },
  3476. enumerable: true,
  3477. configurable: true
  3478. });
  3479. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3480. get: function () {
  3481. return Tools._PerformanceConsoleLogLevel;
  3482. },
  3483. enumerable: true,
  3484. configurable: true
  3485. });
  3486. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3487. set: function (level) {
  3488. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3489. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3490. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3491. return;
  3492. }
  3493. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3494. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3495. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3496. return;
  3497. }
  3498. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3499. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3500. },
  3501. enumerable: true,
  3502. configurable: true
  3503. });
  3504. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3505. };
  3506. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3507. };
  3508. Tools._StartUserMark = function (counterName, condition) {
  3509. if (condition === void 0) { condition = true; }
  3510. if (!condition || !Tools._performance.mark) {
  3511. return;
  3512. }
  3513. Tools._performance.mark(counterName + "-Begin");
  3514. };
  3515. Tools._EndUserMark = function (counterName, condition) {
  3516. if (condition === void 0) { condition = true; }
  3517. if (!condition || !Tools._performance.mark) {
  3518. return;
  3519. }
  3520. Tools._performance.mark(counterName + "-End");
  3521. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3522. };
  3523. Tools._StartPerformanceConsole = function (counterName, condition) {
  3524. if (condition === void 0) { condition = true; }
  3525. if (!condition) {
  3526. return;
  3527. }
  3528. Tools._StartUserMark(counterName, condition);
  3529. if (console.time) {
  3530. console.time(counterName);
  3531. }
  3532. };
  3533. Tools._EndPerformanceConsole = function (counterName, condition) {
  3534. if (condition === void 0) { condition = true; }
  3535. if (!condition) {
  3536. return;
  3537. }
  3538. Tools._EndUserMark(counterName, condition);
  3539. if (console.time) {
  3540. console.timeEnd(counterName);
  3541. }
  3542. };
  3543. Object.defineProperty(Tools, "Now", {
  3544. get: function () {
  3545. if (window.performance && window.performance.now) {
  3546. return window.performance.now();
  3547. }
  3548. return new Date().getTime();
  3549. },
  3550. enumerable: true,
  3551. configurable: true
  3552. });
  3553. // Deprecated
  3554. Tools.GetFps = function () {
  3555. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3556. return 0;
  3557. };
  3558. Tools.BaseUrl = "";
  3559. Tools.GetExponantOfTwo = function (value, max) {
  3560. var count = 1;
  3561. do {
  3562. count *= 2;
  3563. } while (count < value);
  3564. if (count > max)
  3565. count = max;
  3566. return count;
  3567. };
  3568. // Logs
  3569. Tools._NoneLogLevel = 0;
  3570. Tools._MessageLogLevel = 1;
  3571. Tools._WarningLogLevel = 2;
  3572. Tools._ErrorLogLevel = 4;
  3573. Tools._LogCache = "";
  3574. Tools.Log = Tools._LogEnabled;
  3575. Tools.Warn = Tools._WarnEnabled;
  3576. Tools.Error = Tools._ErrorEnabled;
  3577. // Performances
  3578. Tools._PerformanceNoneLogLevel = 0;
  3579. Tools._PerformanceUserMarkLogLevel = 1;
  3580. Tools._PerformanceConsoleLogLevel = 2;
  3581. Tools._performance = window.performance;
  3582. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3583. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3584. return Tools;
  3585. })();
  3586. BABYLON.Tools = Tools;
  3587. /**
  3588. * An implementation of a loop for asynchronous functions.
  3589. */
  3590. var AsyncLoop = (function () {
  3591. /**
  3592. * Constroctor.
  3593. * @param iterations the number of iterations.
  3594. * @param _fn the function to run each iteration
  3595. * @param _successCallback the callback that will be called upon succesful execution
  3596. * @param offset starting offset.
  3597. */
  3598. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3599. if (offset === void 0) { offset = 0; }
  3600. this.iterations = iterations;
  3601. this._fn = _fn;
  3602. this._successCallback = _successCallback;
  3603. this.index = offset - 1;
  3604. this._done = false;
  3605. }
  3606. /**
  3607. * Execute the next iteration. Must be called after the last iteration was finished.
  3608. */
  3609. AsyncLoop.prototype.executeNext = function () {
  3610. if (!this._done) {
  3611. if (this.index + 1 < this.iterations) {
  3612. ++this.index;
  3613. this._fn(this);
  3614. }
  3615. else {
  3616. this.breakLoop();
  3617. }
  3618. }
  3619. };
  3620. /**
  3621. * Break the loop and run the success callback.
  3622. */
  3623. AsyncLoop.prototype.breakLoop = function () {
  3624. this._done = true;
  3625. this._successCallback();
  3626. };
  3627. /**
  3628. * Helper function
  3629. */
  3630. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3631. if (offset === void 0) { offset = 0; }
  3632. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3633. loop.executeNext();
  3634. return loop;
  3635. };
  3636. /**
  3637. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3638. * @param iterations total number of iterations
  3639. * @param syncedIterations number of synchronous iterations in each async iteration.
  3640. * @param fn the function to call each iteration.
  3641. * @param callback a success call back that will be called when iterating stops.
  3642. * @param breakFunction a break condition (optional)
  3643. * @param timeout timeout settings for the setTimeout function. default - 0.
  3644. * @constructor
  3645. */
  3646. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3647. if (timeout === void 0) { timeout = 0; }
  3648. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3649. if (breakFunction && breakFunction())
  3650. loop.breakLoop();
  3651. else {
  3652. setTimeout(function () {
  3653. for (var i = 0; i < syncedIterations; ++i) {
  3654. var iteration = (loop.index * syncedIterations) + i;
  3655. if (iteration >= iterations)
  3656. break;
  3657. fn(iteration);
  3658. if (breakFunction && breakFunction()) {
  3659. loop.breakLoop();
  3660. break;
  3661. }
  3662. }
  3663. loop.executeNext();
  3664. }, timeout);
  3665. }
  3666. }, callback);
  3667. };
  3668. return AsyncLoop;
  3669. })();
  3670. BABYLON.AsyncLoop = AsyncLoop;
  3671. })(BABYLON || (BABYLON = {}));
  3672. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3673. (function (BABYLON) {
  3674. var _DepthCullingState = (function () {
  3675. function _DepthCullingState() {
  3676. this._isDepthTestDirty = false;
  3677. this._isDepthMaskDirty = false;
  3678. this._isDepthFuncDirty = false;
  3679. this._isCullFaceDirty = false;
  3680. this._isCullDirty = false;
  3681. this._isZOffsetDirty = false;
  3682. }
  3683. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3684. get: function () {
  3685. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  3686. },
  3687. enumerable: true,
  3688. configurable: true
  3689. });
  3690. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  3691. get: function () {
  3692. return this._zOffset;
  3693. },
  3694. set: function (value) {
  3695. if (this._zOffset === value) {
  3696. return;
  3697. }
  3698. this._zOffset = value;
  3699. this._isZOffsetDirty = true;
  3700. },
  3701. enumerable: true,
  3702. configurable: true
  3703. });
  3704. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3705. get: function () {
  3706. return this._cullFace;
  3707. },
  3708. set: function (value) {
  3709. if (this._cullFace === value) {
  3710. return;
  3711. }
  3712. this._cullFace = value;
  3713. this._isCullFaceDirty = true;
  3714. },
  3715. enumerable: true,
  3716. configurable: true
  3717. });
  3718. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3719. get: function () {
  3720. return this._cull;
  3721. },
  3722. set: function (value) {
  3723. if (this._cull === value) {
  3724. return;
  3725. }
  3726. this._cull = value;
  3727. this._isCullDirty = true;
  3728. },
  3729. enumerable: true,
  3730. configurable: true
  3731. });
  3732. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3733. get: function () {
  3734. return this._depthFunc;
  3735. },
  3736. set: function (value) {
  3737. if (this._depthFunc === value) {
  3738. return;
  3739. }
  3740. this._depthFunc = value;
  3741. this._isDepthFuncDirty = true;
  3742. },
  3743. enumerable: true,
  3744. configurable: true
  3745. });
  3746. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3747. get: function () {
  3748. return this._depthMask;
  3749. },
  3750. set: function (value) {
  3751. if (this._depthMask === value) {
  3752. return;
  3753. }
  3754. this._depthMask = value;
  3755. this._isDepthMaskDirty = true;
  3756. },
  3757. enumerable: true,
  3758. configurable: true
  3759. });
  3760. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3761. get: function () {
  3762. return this._depthTest;
  3763. },
  3764. set: function (value) {
  3765. if (this._depthTest === value) {
  3766. return;
  3767. }
  3768. this._depthTest = value;
  3769. this._isDepthTestDirty = true;
  3770. },
  3771. enumerable: true,
  3772. configurable: true
  3773. });
  3774. _DepthCullingState.prototype.reset = function () {
  3775. this._depthMask = true;
  3776. this._depthTest = true;
  3777. this._depthFunc = null;
  3778. this._cull = null;
  3779. this._cullFace = null;
  3780. this._zOffset = 0;
  3781. this._isDepthTestDirty = true;
  3782. this._isDepthMaskDirty = true;
  3783. this._isDepthFuncDirty = false;
  3784. this._isCullFaceDirty = false;
  3785. this._isCullDirty = false;
  3786. this._isZOffsetDirty = false;
  3787. };
  3788. _DepthCullingState.prototype.apply = function (gl) {
  3789. if (!this.isDirty) {
  3790. return;
  3791. }
  3792. // Cull
  3793. if (this._isCullDirty) {
  3794. if (this.cull) {
  3795. gl.enable(gl.CULL_FACE);
  3796. }
  3797. else {
  3798. gl.disable(gl.CULL_FACE);
  3799. }
  3800. this._isCullDirty = false;
  3801. }
  3802. // Cull face
  3803. if (this._isCullFaceDirty) {
  3804. gl.cullFace(this.cullFace);
  3805. this._isCullFaceDirty = false;
  3806. }
  3807. // Depth mask
  3808. if (this._isDepthMaskDirty) {
  3809. gl.depthMask(this.depthMask);
  3810. this._isDepthMaskDirty = false;
  3811. }
  3812. // Depth test
  3813. if (this._isDepthTestDirty) {
  3814. if (this.depthTest) {
  3815. gl.enable(gl.DEPTH_TEST);
  3816. }
  3817. else {
  3818. gl.disable(gl.DEPTH_TEST);
  3819. }
  3820. this._isDepthTestDirty = false;
  3821. }
  3822. // Depth func
  3823. if (this._isDepthFuncDirty) {
  3824. gl.depthFunc(this.depthFunc);
  3825. this._isDepthFuncDirty = false;
  3826. }
  3827. // zOffset
  3828. if (this._isZOffsetDirty) {
  3829. if (this.zOffset) {
  3830. gl.enable(gl.POLYGON_OFFSET_FILL);
  3831. gl.polygonOffset(this.zOffset, 0);
  3832. }
  3833. else {
  3834. gl.disable(gl.POLYGON_OFFSET_FILL);
  3835. }
  3836. this._isZOffsetDirty = false;
  3837. }
  3838. };
  3839. return _DepthCullingState;
  3840. })();
  3841. BABYLON._DepthCullingState = _DepthCullingState;
  3842. var _AlphaState = (function () {
  3843. function _AlphaState() {
  3844. this._isAlphaBlendDirty = false;
  3845. this._isBlendFunctionParametersDirty = false;
  3846. this._alphaBlend = false;
  3847. this._blendFunctionParameters = new Array(4);
  3848. }
  3849. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3850. get: function () {
  3851. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3852. },
  3853. enumerable: true,
  3854. configurable: true
  3855. });
  3856. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3857. get: function () {
  3858. return this._alphaBlend;
  3859. },
  3860. set: function (value) {
  3861. if (this._alphaBlend === value) {
  3862. return;
  3863. }
  3864. this._alphaBlend = value;
  3865. this._isAlphaBlendDirty = true;
  3866. },
  3867. enumerable: true,
  3868. configurable: true
  3869. });
  3870. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3871. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3872. return;
  3873. }
  3874. this._blendFunctionParameters[0] = value0;
  3875. this._blendFunctionParameters[1] = value1;
  3876. this._blendFunctionParameters[2] = value2;
  3877. this._blendFunctionParameters[3] = value3;
  3878. this._isBlendFunctionParametersDirty = true;
  3879. };
  3880. _AlphaState.prototype.reset = function () {
  3881. this._alphaBlend = false;
  3882. this._blendFunctionParameters[0] = null;
  3883. this._blendFunctionParameters[1] = null;
  3884. this._blendFunctionParameters[2] = null;
  3885. this._blendFunctionParameters[3] = null;
  3886. this._isAlphaBlendDirty = true;
  3887. this._isBlendFunctionParametersDirty = false;
  3888. };
  3889. _AlphaState.prototype.apply = function (gl) {
  3890. if (!this.isDirty) {
  3891. return;
  3892. }
  3893. // Alpha blend
  3894. if (this._isAlphaBlendDirty) {
  3895. if (this._alphaBlend) {
  3896. gl.enable(gl.BLEND);
  3897. }
  3898. else {
  3899. gl.disable(gl.BLEND);
  3900. }
  3901. this._isAlphaBlendDirty = false;
  3902. }
  3903. // Alpha function
  3904. if (this._isBlendFunctionParametersDirty) {
  3905. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3906. this._isBlendFunctionParametersDirty = false;
  3907. }
  3908. };
  3909. return _AlphaState;
  3910. })();
  3911. BABYLON._AlphaState = _AlphaState;
  3912. var compileShader = function (gl, source, type, defines) {
  3913. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3914. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3915. gl.compileShader(shader);
  3916. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3917. throw new Error(gl.getShaderInfoLog(shader));
  3918. }
  3919. return shader;
  3920. };
  3921. var getWebGLTextureType = function (gl, type) {
  3922. var textureType = gl.UNSIGNED_BYTE;
  3923. if (type === Engine.TEXTURETYPE_FLOAT)
  3924. textureType = gl.FLOAT;
  3925. return textureType;
  3926. };
  3927. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3928. var magFilter = gl.NEAREST;
  3929. var minFilter = gl.NEAREST;
  3930. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3931. magFilter = gl.LINEAR;
  3932. if (generateMipMaps) {
  3933. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3934. }
  3935. else {
  3936. minFilter = gl.LINEAR;
  3937. }
  3938. }
  3939. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3940. magFilter = gl.LINEAR;
  3941. if (generateMipMaps) {
  3942. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3943. }
  3944. else {
  3945. minFilter = gl.LINEAR;
  3946. }
  3947. }
  3948. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3949. magFilter = gl.NEAREST;
  3950. if (generateMipMaps) {
  3951. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3952. }
  3953. else {
  3954. minFilter = gl.NEAREST;
  3955. }
  3956. }
  3957. return {
  3958. min: minFilter,
  3959. mag: magFilter
  3960. };
  3961. };
  3962. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3963. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3964. var engine = scene.getEngine();
  3965. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3966. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3967. gl.bindTexture(gl.TEXTURE_2D, texture);
  3968. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3969. processFunction(potWidth, potHeight);
  3970. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3971. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3972. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3973. if (!noMipmap && !isCompressed) {
  3974. gl.generateMipmap(gl.TEXTURE_2D);
  3975. }
  3976. gl.bindTexture(gl.TEXTURE_2D, null);
  3977. engine._activeTexturesCache = [];
  3978. texture._baseWidth = width;
  3979. texture._baseHeight = height;
  3980. texture._width = potWidth;
  3981. texture._height = potHeight;
  3982. texture.isReady = true;
  3983. texture.samplingMode = samplingMode;
  3984. scene._removePendingData(texture);
  3985. };
  3986. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3987. var onload = function () {
  3988. loadedImages[index] = img;
  3989. loadedImages._internalCount++;
  3990. scene._removePendingData(img);
  3991. if (loadedImages._internalCount === 6) {
  3992. onfinish(loadedImages);
  3993. }
  3994. };
  3995. var onerror = function () {
  3996. scene._removePendingData(img);
  3997. };
  3998. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3999. scene._addPendingData(img);
  4000. };
  4001. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  4002. var loadedImages = [];
  4003. loadedImages._internalCount = 0;
  4004. for (var index = 0; index < 6; index++) {
  4005. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  4006. }
  4007. };
  4008. var EngineCapabilities = (function () {
  4009. function EngineCapabilities() {
  4010. }
  4011. return EngineCapabilities;
  4012. })();
  4013. BABYLON.EngineCapabilities = EngineCapabilities;
  4014. /**
  4015. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  4016. */
  4017. var Engine = (function () {
  4018. /**
  4019. * @constructor
  4020. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  4021. * @param {boolean} [antialias] - enable antialias
  4022. * @param options - further options to be sent to the getContext function
  4023. */
  4024. function Engine(canvas, antialias, options) {
  4025. var _this = this;
  4026. // Public members
  4027. this.isFullscreen = false;
  4028. this.isPointerLock = false;
  4029. this.cullBackFaces = true;
  4030. this.renderEvenInBackground = true;
  4031. this.scenes = new Array();
  4032. this._windowIsBackground = false;
  4033. this._loadingDivBackgroundColor = "black";
  4034. this._drawCalls = 0;
  4035. this._renderingQueueLaunched = false;
  4036. this._activeRenderLoops = [];
  4037. // FPS
  4038. this.fpsRange = 60;
  4039. this.previousFramesDuration = [];
  4040. this.fps = 60;
  4041. this.deltaTime = 0;
  4042. // States
  4043. this._depthCullingState = new _DepthCullingState();
  4044. this._alphaState = new _AlphaState();
  4045. this._alphaMode = Engine.ALPHA_DISABLE;
  4046. // Cache
  4047. this._loadedTexturesCache = new Array();
  4048. this._activeTexturesCache = new Array();
  4049. this._compiledEffects = {};
  4050. this._uintIndicesCurrentlySet = false;
  4051. this._renderingCanvas = canvas;
  4052. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4053. options = options || {};
  4054. options.antialias = antialias;
  4055. try {
  4056. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  4057. }
  4058. catch (e) {
  4059. throw new Error("WebGL not supported");
  4060. }
  4061. if (!this._gl) {
  4062. throw new Error("WebGL not supported");
  4063. }
  4064. this._onBlur = function () {
  4065. _this._windowIsBackground = true;
  4066. };
  4067. this._onFocus = function () {
  4068. _this._windowIsBackground = false;
  4069. };
  4070. window.addEventListener("blur", this._onBlur);
  4071. window.addEventListener("focus", this._onFocus);
  4072. // Viewport
  4073. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  4074. this.resize();
  4075. // Caps
  4076. this._caps = new EngineCapabilities();
  4077. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  4078. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  4079. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  4080. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  4081. // Infos
  4082. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  4083. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  4084. if (rendererInfo != null) {
  4085. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  4086. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  4087. }
  4088. if (!this._glVendor) {
  4089. this._glVendor = "Unknown vendor";
  4090. }
  4091. if (!this._glRenderer) {
  4092. this._glRenderer = "Unknown renderer";
  4093. }
  4094. // Extensions
  4095. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  4096. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  4097. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  4098. 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');
  4099. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  4100. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  4101. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  4102. // Depth buffer
  4103. this.setDepthBuffer(true);
  4104. this.setDepthFunctionToLessOrEqual();
  4105. this.setDepthWrite(true);
  4106. // Fullscreen
  4107. this._onFullscreenChange = function () {
  4108. if (document.fullscreen !== undefined) {
  4109. _this.isFullscreen = document.fullscreen;
  4110. }
  4111. else if (document.mozFullScreen !== undefined) {
  4112. _this.isFullscreen = document.mozFullScreen;
  4113. }
  4114. else if (document.webkitIsFullScreen !== undefined) {
  4115. _this.isFullscreen = document.webkitIsFullScreen;
  4116. }
  4117. else if (document.msIsFullScreen !== undefined) {
  4118. _this.isFullscreen = document.msIsFullScreen;
  4119. }
  4120. // Pointer lock
  4121. if (_this.isFullscreen && _this._pointerLockRequested) {
  4122. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4123. if (canvas.requestPointerLock) {
  4124. canvas.requestPointerLock();
  4125. }
  4126. }
  4127. };
  4128. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4129. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4130. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4131. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4132. // Pointer lock
  4133. this._onPointerLockChange = function () {
  4134. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4135. };
  4136. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4137. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4138. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4139. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4140. if (!Engine.audioEngine) {
  4141. Engine.audioEngine = new BABYLON.AudioEngine();
  4142. }
  4143. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4144. }
  4145. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4146. get: function () {
  4147. return Engine._ALPHA_DISABLE;
  4148. },
  4149. enumerable: true,
  4150. configurable: true
  4151. });
  4152. Object.defineProperty(Engine, "ALPHA_ADD", {
  4153. get: function () {
  4154. return Engine._ALPHA_ADD;
  4155. },
  4156. enumerable: true,
  4157. configurable: true
  4158. });
  4159. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4160. get: function () {
  4161. return Engine._ALPHA_COMBINE;
  4162. },
  4163. enumerable: true,
  4164. configurable: true
  4165. });
  4166. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4167. get: function () {
  4168. return Engine._DELAYLOADSTATE_NONE;
  4169. },
  4170. enumerable: true,
  4171. configurable: true
  4172. });
  4173. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4174. get: function () {
  4175. return Engine._DELAYLOADSTATE_LOADED;
  4176. },
  4177. enumerable: true,
  4178. configurable: true
  4179. });
  4180. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4181. get: function () {
  4182. return Engine._DELAYLOADSTATE_LOADING;
  4183. },
  4184. enumerable: true,
  4185. configurable: true
  4186. });
  4187. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4188. get: function () {
  4189. return Engine._DELAYLOADSTATE_NOTLOADED;
  4190. },
  4191. enumerable: true,
  4192. configurable: true
  4193. });
  4194. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4195. get: function () {
  4196. return Engine._TEXTUREFORMAT_ALPHA;
  4197. },
  4198. enumerable: true,
  4199. configurable: true
  4200. });
  4201. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4202. get: function () {
  4203. return Engine._TEXTUREFORMAT_LUMINANCE;
  4204. },
  4205. enumerable: true,
  4206. configurable: true
  4207. });
  4208. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4209. get: function () {
  4210. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4211. },
  4212. enumerable: true,
  4213. configurable: true
  4214. });
  4215. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4216. get: function () {
  4217. return Engine._TEXTUREFORMAT_RGB;
  4218. },
  4219. enumerable: true,
  4220. configurable: true
  4221. });
  4222. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4223. get: function () {
  4224. return Engine._TEXTUREFORMAT_RGBA;
  4225. },
  4226. enumerable: true,
  4227. configurable: true
  4228. });
  4229. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4230. get: function () {
  4231. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4232. },
  4233. enumerable: true,
  4234. configurable: true
  4235. });
  4236. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4237. get: function () {
  4238. return Engine._TEXTURETYPE_FLOAT;
  4239. },
  4240. enumerable: true,
  4241. configurable: true
  4242. });
  4243. Object.defineProperty(Engine, "Version", {
  4244. get: function () {
  4245. return "2.1.0 alpha";
  4246. },
  4247. enumerable: true,
  4248. configurable: true
  4249. });
  4250. Engine.prototype._prepareWorkingCanvas = function () {
  4251. if (this._workingCanvas) {
  4252. return;
  4253. }
  4254. this._workingCanvas = document.createElement("canvas");
  4255. this._workingContext = this._workingCanvas.getContext("2d");
  4256. };
  4257. Engine.prototype.getGlInfo = function () {
  4258. return {
  4259. vendor: this._glVendor,
  4260. renderer: this._glRenderer,
  4261. version: this._glVersion
  4262. };
  4263. };
  4264. Engine.prototype.getAspectRatio = function (camera) {
  4265. var viewport = camera.viewport;
  4266. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4267. };
  4268. Engine.prototype.getRenderWidth = function () {
  4269. if (this._currentRenderTarget) {
  4270. return this._currentRenderTarget._width;
  4271. }
  4272. return this._renderingCanvas.width;
  4273. };
  4274. Engine.prototype.getRenderHeight = function () {
  4275. if (this._currentRenderTarget) {
  4276. return this._currentRenderTarget._height;
  4277. }
  4278. return this._renderingCanvas.height;
  4279. };
  4280. Engine.prototype.getRenderingCanvas = function () {
  4281. return this._renderingCanvas;
  4282. };
  4283. Engine.prototype.getRenderingCanvasClientRect = function () {
  4284. return this._renderingCanvas.getBoundingClientRect();
  4285. };
  4286. Engine.prototype.setHardwareScalingLevel = function (level) {
  4287. this._hardwareScalingLevel = level;
  4288. this.resize();
  4289. };
  4290. Engine.prototype.getHardwareScalingLevel = function () {
  4291. return this._hardwareScalingLevel;
  4292. };
  4293. Engine.prototype.getLoadedTexturesCache = function () {
  4294. return this._loadedTexturesCache;
  4295. };
  4296. Engine.prototype.getCaps = function () {
  4297. return this._caps;
  4298. };
  4299. Object.defineProperty(Engine.prototype, "drawCalls", {
  4300. get: function () {
  4301. return this._drawCalls;
  4302. },
  4303. enumerable: true,
  4304. configurable: true
  4305. });
  4306. // Methods
  4307. Engine.prototype.resetDrawCalls = function () {
  4308. this._drawCalls = 0;
  4309. };
  4310. Engine.prototype.setDepthFunctionToGreater = function () {
  4311. this._depthCullingState.depthFunc = this._gl.GREATER;
  4312. };
  4313. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4314. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4315. };
  4316. Engine.prototype.setDepthFunctionToLess = function () {
  4317. this._depthCullingState.depthFunc = this._gl.LESS;
  4318. };
  4319. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4320. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4321. };
  4322. /**
  4323. * stop executing a render loop function and remove it from the execution array
  4324. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4325. */
  4326. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4327. if (!renderFunction) {
  4328. this._activeRenderLoops = [];
  4329. return;
  4330. }
  4331. var index = this._activeRenderLoops.indexOf(renderFunction);
  4332. if (index >= 0) {
  4333. this._activeRenderLoops.splice(index, 1);
  4334. }
  4335. };
  4336. Engine.prototype._renderLoop = function () {
  4337. var _this = this;
  4338. var shouldRender = true;
  4339. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4340. shouldRender = false;
  4341. }
  4342. if (shouldRender) {
  4343. // Start new frame
  4344. this.beginFrame();
  4345. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4346. var renderFunction = this._activeRenderLoops[index];
  4347. renderFunction();
  4348. }
  4349. // Present
  4350. this.endFrame();
  4351. }
  4352. if (this._activeRenderLoops.length > 0) {
  4353. // Register new frame
  4354. BABYLON.Tools.QueueNewFrame(function () {
  4355. _this._renderLoop();
  4356. });
  4357. }
  4358. else {
  4359. this._renderingQueueLaunched = false;
  4360. }
  4361. };
  4362. /**
  4363. * Register and execute a render loop. The engine can have more than one render function.
  4364. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4365. * @example
  4366. * engine.runRenderLoop(function () {
  4367. * scene.render()
  4368. * })
  4369. */
  4370. Engine.prototype.runRenderLoop = function (renderFunction) {
  4371. var _this = this;
  4372. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4373. return;
  4374. }
  4375. this._activeRenderLoops.push(renderFunction);
  4376. if (!this._renderingQueueLaunched) {
  4377. this._renderingQueueLaunched = true;
  4378. BABYLON.Tools.QueueNewFrame(function () {
  4379. _this._renderLoop();
  4380. });
  4381. }
  4382. };
  4383. /**
  4384. * Toggle full screen mode.
  4385. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4386. */
  4387. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4388. if (this.isFullscreen) {
  4389. BABYLON.Tools.ExitFullscreen();
  4390. }
  4391. else {
  4392. this._pointerLockRequested = requestPointerLock;
  4393. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4394. }
  4395. };
  4396. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4397. this.applyStates();
  4398. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4399. if (this._depthCullingState.depthMask) {
  4400. this._gl.clearDepth(1.0);
  4401. }
  4402. var mode = 0;
  4403. if (backBuffer)
  4404. mode |= this._gl.COLOR_BUFFER_BIT;
  4405. if (depthStencil && this._depthCullingState.depthMask)
  4406. mode |= this._gl.DEPTH_BUFFER_BIT;
  4407. this._gl.clear(mode);
  4408. };
  4409. /**
  4410. * Set the WebGL's viewport
  4411. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4412. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4413. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4414. */
  4415. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4416. var width = requiredWidth || this._renderingCanvas.width;
  4417. var height = requiredHeight || this._renderingCanvas.height;
  4418. var x = viewport.x || 0;
  4419. var y = viewport.y || 0;
  4420. this._cachedViewport = viewport;
  4421. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4422. };
  4423. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4424. this._cachedViewport = null;
  4425. this._gl.viewport(x, y, width, height);
  4426. };
  4427. Engine.prototype.beginFrame = function () {
  4428. this._measureFps();
  4429. };
  4430. Engine.prototype.endFrame = function () {
  4431. //this.flushFramebuffer();
  4432. };
  4433. /**
  4434. * resize the view according to the canvas' size.
  4435. * @example
  4436. * window.addEventListener("resize", function () {
  4437. * engine.resize();
  4438. * });
  4439. */
  4440. Engine.prototype.resize = function () {
  4441. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4442. };
  4443. /**
  4444. * force a specific size of the canvas
  4445. * @param {number} width - the new canvas' width
  4446. * @param {number} height - the new canvas' height
  4447. */
  4448. Engine.prototype.setSize = function (width, height) {
  4449. this._renderingCanvas.width = width;
  4450. this._renderingCanvas.height = height;
  4451. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4452. };
  4453. Engine.prototype.bindFramebuffer = function (texture) {
  4454. this._currentRenderTarget = texture;
  4455. var gl = this._gl;
  4456. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4457. this._gl.viewport(0, 0, texture._width, texture._height);
  4458. this.wipeCaches();
  4459. };
  4460. Engine.prototype.unBindFramebuffer = function (texture) {
  4461. this._currentRenderTarget = null;
  4462. if (texture.generateMipMaps) {
  4463. var gl = this._gl;
  4464. gl.bindTexture(gl.TEXTURE_2D, texture);
  4465. gl.generateMipmap(gl.TEXTURE_2D);
  4466. gl.bindTexture(gl.TEXTURE_2D, null);
  4467. }
  4468. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4469. };
  4470. Engine.prototype.flushFramebuffer = function () {
  4471. this._gl.flush();
  4472. };
  4473. Engine.prototype.restoreDefaultFramebuffer = function () {
  4474. this._currentRenderTarget = null;
  4475. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4476. this.setViewport(this._cachedViewport);
  4477. this.wipeCaches();
  4478. };
  4479. // VBOs
  4480. Engine.prototype._resetVertexBufferBinding = function () {
  4481. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4482. this._cachedVertexBuffers = null;
  4483. };
  4484. Engine.prototype.createVertexBuffer = function (vertices) {
  4485. var vbo = this._gl.createBuffer();
  4486. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4487. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4488. this._resetVertexBufferBinding();
  4489. vbo.references = 1;
  4490. return vbo;
  4491. };
  4492. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4493. var vbo = this._gl.createBuffer();
  4494. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4495. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4496. this._resetVertexBufferBinding();
  4497. vbo.references = 1;
  4498. return vbo;
  4499. };
  4500. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4501. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4502. if (offset === undefined) {
  4503. offset = 0;
  4504. }
  4505. if (vertices instanceof Float32Array) {
  4506. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4507. }
  4508. else {
  4509. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4510. }
  4511. this._resetVertexBufferBinding();
  4512. };
  4513. Engine.prototype._resetIndexBufferBinding = function () {
  4514. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4515. this._cachedIndexBuffer = null;
  4516. };
  4517. Engine.prototype.createIndexBuffer = function (indices) {
  4518. var vbo = this._gl.createBuffer();
  4519. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4520. // Check for 32 bits indices
  4521. var arrayBuffer;
  4522. var need32Bits = false;
  4523. if (this._caps.uintIndices) {
  4524. for (var index = 0; index < indices.length; index++) {
  4525. if (indices[index] > 65535) {
  4526. need32Bits = true;
  4527. break;
  4528. }
  4529. }
  4530. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4531. }
  4532. else {
  4533. arrayBuffer = new Uint16Array(indices);
  4534. }
  4535. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4536. this._resetIndexBufferBinding();
  4537. vbo.references = 1;
  4538. vbo.is32Bits = need32Bits;
  4539. return vbo;
  4540. };
  4541. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4542. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4543. this._cachedVertexBuffers = vertexBuffer;
  4544. this._cachedEffectForVertexBuffers = effect;
  4545. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4546. var offset = 0;
  4547. for (var index = 0; index < vertexDeclaration.length; index++) {
  4548. var order = effect.getAttributeLocation(index);
  4549. if (order >= 0) {
  4550. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4551. }
  4552. offset += vertexDeclaration[index] * 4;
  4553. }
  4554. }
  4555. if (this._cachedIndexBuffer !== indexBuffer) {
  4556. this._cachedIndexBuffer = indexBuffer;
  4557. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4558. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4559. }
  4560. };
  4561. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4562. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4563. this._cachedVertexBuffers = vertexBuffers;
  4564. this._cachedEffectForVertexBuffers = effect;
  4565. var attributes = effect.getAttributesNames();
  4566. for (var index = 0; index < attributes.length; index++) {
  4567. var order = effect.getAttributeLocation(index);
  4568. if (order >= 0) {
  4569. var vertexBuffer = vertexBuffers[attributes[index]];
  4570. if (!vertexBuffer) {
  4571. continue;
  4572. }
  4573. var stride = vertexBuffer.getStrideSize();
  4574. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4575. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4576. }
  4577. }
  4578. }
  4579. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4580. this._cachedIndexBuffer = indexBuffer;
  4581. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4582. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4583. }
  4584. };
  4585. Engine.prototype._releaseBuffer = function (buffer) {
  4586. buffer.references--;
  4587. if (buffer.references === 0) {
  4588. this._gl.deleteBuffer(buffer);
  4589. return true;
  4590. }
  4591. return false;
  4592. };
  4593. Engine.prototype.createInstancesBuffer = function (capacity) {
  4594. var buffer = this._gl.createBuffer();
  4595. buffer.capacity = capacity;
  4596. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4597. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4598. return buffer;
  4599. };
  4600. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4601. this._gl.deleteBuffer(buffer);
  4602. };
  4603. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4604. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4605. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4606. for (var index = 0; index < 4; index++) {
  4607. var offsetLocation = offsetLocations[index];
  4608. this._gl.enableVertexAttribArray(offsetLocation);
  4609. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4610. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4611. }
  4612. };
  4613. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4614. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4615. for (var index = 0; index < 4; index++) {
  4616. var offsetLocation = offsetLocations[index];
  4617. this._gl.disableVertexAttribArray(offsetLocation);
  4618. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4619. }
  4620. };
  4621. Engine.prototype.applyStates = function () {
  4622. this._depthCullingState.apply(this._gl);
  4623. this._alphaState.apply(this._gl);
  4624. };
  4625. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4626. // Apply states
  4627. this.applyStates();
  4628. this._drawCalls++;
  4629. // Render
  4630. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4631. if (instancesCount) {
  4632. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4633. return;
  4634. }
  4635. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4636. };
  4637. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4638. // Apply states
  4639. this.applyStates();
  4640. this._drawCalls++;
  4641. if (instancesCount) {
  4642. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4643. return;
  4644. }
  4645. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4646. };
  4647. // Shaders
  4648. Engine.prototype._releaseEffect = function (effect) {
  4649. if (this._compiledEffects[effect._key]) {
  4650. delete this._compiledEffects[effect._key];
  4651. if (effect.getProgram()) {
  4652. this._gl.deleteProgram(effect.getProgram());
  4653. }
  4654. }
  4655. };
  4656. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4657. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4658. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4659. var name = vertex + "+" + fragment + "@" + defines;
  4660. if (this._compiledEffects[name]) {
  4661. return this._compiledEffects[name];
  4662. }
  4663. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4664. effect._key = name;
  4665. this._compiledEffects[name] = effect;
  4666. return effect;
  4667. };
  4668. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4669. if (uniformsNames === void 0) { uniformsNames = []; }
  4670. if (samplers === void 0) { samplers = []; }
  4671. if (defines === void 0) { defines = ""; }
  4672. return this.createEffect({
  4673. vertex: "particles",
  4674. fragmentElement: fragmentName
  4675. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4676. };
  4677. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4678. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4679. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4680. var shaderProgram = this._gl.createProgram();
  4681. this._gl.attachShader(shaderProgram, vertexShader);
  4682. this._gl.attachShader(shaderProgram, fragmentShader);
  4683. this._gl.linkProgram(shaderProgram);
  4684. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4685. if (!linked) {
  4686. var error = this._gl.getProgramInfoLog(shaderProgram);
  4687. if (error) {
  4688. throw new Error(error);
  4689. }
  4690. }
  4691. this._gl.deleteShader(vertexShader);
  4692. this._gl.deleteShader(fragmentShader);
  4693. return shaderProgram;
  4694. };
  4695. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4696. var results = [];
  4697. for (var index = 0; index < uniformsNames.length; index++) {
  4698. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4699. }
  4700. return results;
  4701. };
  4702. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4703. var results = [];
  4704. for (var index = 0; index < attributesNames.length; index++) {
  4705. try {
  4706. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4707. }
  4708. catch (e) {
  4709. results.push(-1);
  4710. }
  4711. }
  4712. return results;
  4713. };
  4714. Engine.prototype.enableEffect = function (effect) {
  4715. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4716. if (effect && effect.onBind) {
  4717. effect.onBind(effect);
  4718. }
  4719. return;
  4720. }
  4721. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4722. // Use program
  4723. this._gl.useProgram(effect.getProgram());
  4724. for (var i in this._vertexAttribArrays) {
  4725. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4726. continue;
  4727. }
  4728. this._vertexAttribArrays[i] = false;
  4729. this._gl.disableVertexAttribArray(i);
  4730. }
  4731. var attributesCount = effect.getAttributesCount();
  4732. for (var index = 0; index < attributesCount; index++) {
  4733. // Attributes
  4734. var order = effect.getAttributeLocation(index);
  4735. if (order >= 0) {
  4736. this._vertexAttribArrays[order] = true;
  4737. this._gl.enableVertexAttribArray(order);
  4738. }
  4739. }
  4740. this._currentEffect = effect;
  4741. if (effect.onBind) {
  4742. effect.onBind(effect);
  4743. }
  4744. };
  4745. Engine.prototype.setArray = function (uniform, array) {
  4746. if (!uniform)
  4747. return;
  4748. this._gl.uniform1fv(uniform, array);
  4749. };
  4750. Engine.prototype.setArray2 = function (uniform, array) {
  4751. if (!uniform || array.length % 2 !== 0)
  4752. return;
  4753. this._gl.uniform2fv(uniform, array);
  4754. };
  4755. Engine.prototype.setArray3 = function (uniform, array) {
  4756. if (!uniform || array.length % 3 !== 0)
  4757. return;
  4758. this._gl.uniform3fv(uniform, array);
  4759. };
  4760. Engine.prototype.setArray4 = function (uniform, array) {
  4761. if (!uniform || array.length % 4 !== 0)
  4762. return;
  4763. this._gl.uniform4fv(uniform, array);
  4764. };
  4765. Engine.prototype.setMatrices = function (uniform, matrices) {
  4766. if (!uniform)
  4767. return;
  4768. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4769. };
  4770. Engine.prototype.setMatrix = function (uniform, matrix) {
  4771. if (!uniform)
  4772. return;
  4773. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4774. };
  4775. Engine.prototype.setFloat = function (uniform, value) {
  4776. if (!uniform)
  4777. return;
  4778. this._gl.uniform1f(uniform, value);
  4779. };
  4780. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4781. if (!uniform)
  4782. return;
  4783. this._gl.uniform2f(uniform, x, y);
  4784. };
  4785. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4786. if (!uniform)
  4787. return;
  4788. this._gl.uniform3f(uniform, x, y, z);
  4789. };
  4790. Engine.prototype.setBool = function (uniform, bool) {
  4791. if (!uniform)
  4792. return;
  4793. this._gl.uniform1i(uniform, bool);
  4794. };
  4795. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4796. if (!uniform)
  4797. return;
  4798. this._gl.uniform4f(uniform, x, y, z, w);
  4799. };
  4800. Engine.prototype.setColor3 = function (uniform, color3) {
  4801. if (!uniform)
  4802. return;
  4803. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4804. };
  4805. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4806. if (!uniform)
  4807. return;
  4808. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4809. };
  4810. // States
  4811. Engine.prototype.setState = function (culling, zOffset, force) {
  4812. if (zOffset === void 0) { zOffset = 0; }
  4813. // Culling
  4814. if (this._depthCullingState.cull !== culling || force) {
  4815. if (culling) {
  4816. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4817. this._depthCullingState.cull = true;
  4818. }
  4819. else {
  4820. this._depthCullingState.cull = false;
  4821. }
  4822. }
  4823. // Z offset
  4824. this._depthCullingState.zOffset = zOffset;
  4825. };
  4826. Engine.prototype.setDepthBuffer = function (enable) {
  4827. this._depthCullingState.depthTest = enable;
  4828. };
  4829. Engine.prototype.getDepthWrite = function () {
  4830. return this._depthCullingState.depthMask;
  4831. };
  4832. Engine.prototype.setDepthWrite = function (enable) {
  4833. this._depthCullingState.depthMask = enable;
  4834. };
  4835. Engine.prototype.setColorWrite = function (enable) {
  4836. this._gl.colorMask(enable, enable, enable, enable);
  4837. };
  4838. Engine.prototype.setAlphaMode = function (mode) {
  4839. switch (mode) {
  4840. case Engine.ALPHA_DISABLE:
  4841. this.setDepthWrite(true);
  4842. this._alphaState.alphaBlend = false;
  4843. break;
  4844. case Engine.ALPHA_COMBINE:
  4845. this.setDepthWrite(false);
  4846. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4847. this._alphaState.alphaBlend = true;
  4848. break;
  4849. case Engine.ALPHA_ADD:
  4850. this.setDepthWrite(false);
  4851. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4852. this._alphaState.alphaBlend = true;
  4853. break;
  4854. }
  4855. this._alphaMode = mode;
  4856. };
  4857. Engine.prototype.getAlphaMode = function () {
  4858. return this._alphaMode;
  4859. };
  4860. Engine.prototype.setAlphaTesting = function (enable) {
  4861. this._alphaTest = enable;
  4862. };
  4863. Engine.prototype.getAlphaTesting = function () {
  4864. return this._alphaTest;
  4865. };
  4866. // Textures
  4867. Engine.prototype.wipeCaches = function () {
  4868. this._activeTexturesCache = [];
  4869. this._currentEffect = null;
  4870. this._depthCullingState.reset();
  4871. this._alphaState.reset();
  4872. this._cachedVertexBuffers = null;
  4873. this._cachedIndexBuffer = null;
  4874. this._cachedEffectForVertexBuffers = null;
  4875. };
  4876. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4877. var gl = this._gl;
  4878. gl.bindTexture(gl.TEXTURE_2D, texture);
  4879. var magFilter = gl.NEAREST;
  4880. var minFilter = gl.NEAREST;
  4881. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4882. magFilter = gl.LINEAR;
  4883. minFilter = gl.LINEAR;
  4884. }
  4885. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4886. magFilter = gl.LINEAR;
  4887. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4888. }
  4889. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4890. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4891. gl.bindTexture(gl.TEXTURE_2D, null);
  4892. texture.samplingMode = samplingMode;
  4893. };
  4894. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4895. var _this = this;
  4896. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4897. if (onLoad === void 0) { onLoad = null; }
  4898. if (onError === void 0) { onError = null; }
  4899. if (buffer === void 0) { buffer = null; }
  4900. var texture = this._gl.createTexture();
  4901. var extension;
  4902. var fromData = false;
  4903. if (url.substr(0, 5) === "data:") {
  4904. fromData = true;
  4905. }
  4906. if (!fromData)
  4907. extension = url.substr(url.length - 4, 4).toLowerCase();
  4908. else {
  4909. var oldUrl = url;
  4910. fromData = oldUrl.split(':');
  4911. url = oldUrl;
  4912. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4913. }
  4914. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4915. var isTGA = (extension === ".tga");
  4916. scene._addPendingData(texture);
  4917. texture.url = url;
  4918. texture.noMipmap = noMipmap;
  4919. texture.references = 1;
  4920. this._loadedTexturesCache.push(texture);
  4921. var onerror = function () {
  4922. scene._removePendingData(texture);
  4923. if (onError) {
  4924. onError();
  4925. }
  4926. };
  4927. if (isTGA) {
  4928. var callback = function (arrayBuffer) {
  4929. var data = new Uint8Array(arrayBuffer);
  4930. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4931. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4932. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4933. if (onLoad) {
  4934. onLoad();
  4935. }
  4936. }, samplingMode);
  4937. };
  4938. if (!(fromData instanceof Array))
  4939. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4940. callback(arrayBuffer);
  4941. }, onerror, scene.database, true);
  4942. else
  4943. callback(buffer);
  4944. }
  4945. else if (isDDS) {
  4946. callback = function (data) {
  4947. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4948. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4949. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4950. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4951. if (onLoad) {
  4952. onLoad();
  4953. }
  4954. }, samplingMode);
  4955. };
  4956. if (!(fromData instanceof Array))
  4957. BABYLON.Tools.LoadFile(url, function (data) {
  4958. callback(data);
  4959. }, onerror, scene.database, true);
  4960. else
  4961. callback(buffer);
  4962. }
  4963. else {
  4964. var onload = function (img) {
  4965. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4966. var isPot = (img.width === potWidth && img.height === potHeight);
  4967. if (!isPot) {
  4968. _this._prepareWorkingCanvas();
  4969. _this._workingCanvas.width = potWidth;
  4970. _this._workingCanvas.height = potHeight;
  4971. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4972. _this._workingContext.imageSmoothingEnabled = false;
  4973. _this._workingContext.mozImageSmoothingEnabled = false;
  4974. _this._workingContext.oImageSmoothingEnabled = false;
  4975. _this._workingContext.webkitImageSmoothingEnabled = false;
  4976. _this._workingContext.msImageSmoothingEnabled = false;
  4977. }
  4978. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4979. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4980. _this._workingContext.imageSmoothingEnabled = true;
  4981. _this._workingContext.mozImageSmoothingEnabled = true;
  4982. _this._workingContext.oImageSmoothingEnabled = true;
  4983. _this._workingContext.webkitImageSmoothingEnabled = true;
  4984. _this._workingContext.msImageSmoothingEnabled = true;
  4985. }
  4986. }
  4987. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4988. if (onLoad) {
  4989. onLoad();
  4990. }
  4991. }, samplingMode);
  4992. };
  4993. if (!(fromData instanceof Array))
  4994. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4995. else
  4996. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4997. }
  4998. return texture;
  4999. };
  5000. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  5001. var texture = this._gl.createTexture();
  5002. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5003. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5004. // Format
  5005. var internalFormat = this._gl.RGBA;
  5006. switch (format) {
  5007. case Engine.TEXTUREFORMAT_ALPHA:
  5008. internalFormat = this._gl.ALPHA;
  5009. break;
  5010. case Engine.TEXTUREFORMAT_LUMINANCE:
  5011. internalFormat = this._gl.LUMINANCE;
  5012. break;
  5013. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  5014. internalFormat = this._gl.LUMINANCE_ALPHA;
  5015. break;
  5016. case Engine.TEXTUREFORMAT_RGB:
  5017. internalFormat = this._gl.RGB;
  5018. break;
  5019. case Engine.TEXTUREFORMAT_RGBA:
  5020. internalFormat = this._gl.RGBA;
  5021. break;
  5022. }
  5023. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  5024. if (generateMipMaps) {
  5025. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5026. }
  5027. // Filters
  5028. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  5029. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5030. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5031. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5032. this._activeTexturesCache = [];
  5033. texture._baseWidth = width;
  5034. texture._baseHeight = height;
  5035. texture._width = width;
  5036. texture._height = height;
  5037. texture.isReady = true;
  5038. texture.references = 1;
  5039. texture.samplingMode = samplingMode;
  5040. this._loadedTexturesCache.push(texture);
  5041. return texture;
  5042. };
  5043. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  5044. var texture = this._gl.createTexture();
  5045. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  5046. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  5047. this._activeTexturesCache = [];
  5048. texture._baseWidth = width;
  5049. texture._baseHeight = height;
  5050. texture._width = width;
  5051. texture._height = height;
  5052. texture.isReady = false;
  5053. texture.generateMipMaps = generateMipMaps;
  5054. texture.references = 1;
  5055. texture.samplingMode = samplingMode;
  5056. this.updateTextureSamplingMode(samplingMode, texture);
  5057. this._loadedTexturesCache.push(texture);
  5058. return texture;
  5059. };
  5060. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  5061. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  5062. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5063. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5064. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5065. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5066. };
  5067. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  5068. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5069. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  5070. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  5071. if (texture.generateMipMaps) {
  5072. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5073. }
  5074. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5075. this._activeTexturesCache = [];
  5076. texture.isReady = true;
  5077. };
  5078. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  5079. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5080. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  5081. // Scale the video if it is a NPOT using the current working canvas
  5082. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  5083. if (!texture._workingCanvas) {
  5084. texture._workingCanvas = document.createElement("canvas");
  5085. texture._workingContext = texture._workingCanvas.getContext("2d");
  5086. texture._workingCanvas.width = texture._width;
  5087. texture._workingCanvas.height = texture._height;
  5088. }
  5089. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  5090. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  5091. }
  5092. else {
  5093. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  5094. }
  5095. if (texture.generateMipMaps) {
  5096. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5097. }
  5098. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5099. this._activeTexturesCache = [];
  5100. texture.isReady = true;
  5101. };
  5102. Engine.prototype.createRenderTargetTexture = function (size, options) {
  5103. // old version had a "generateMipMaps" arg instead of options.
  5104. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  5105. // in the same way, generateDepthBuffer is defaulted to true
  5106. var generateMipMaps = false;
  5107. var generateDepthBuffer = true;
  5108. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5109. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  5110. if (options !== undefined) {
  5111. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  5112. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  5113. type = options.type === undefined ? type : options.type;
  5114. if (options.samplingMode !== undefined) {
  5115. samplingMode = options.samplingMode;
  5116. }
  5117. if (type === Engine.TEXTURETYPE_FLOAT) {
  5118. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5119. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5120. }
  5121. }
  5122. var gl = this._gl;
  5123. var texture = gl.createTexture();
  5124. gl.bindTexture(gl.TEXTURE_2D, texture);
  5125. var width = size.width || size;
  5126. var height = size.height || size;
  5127. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5128. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5129. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5130. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5131. }
  5132. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5133. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5136. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5137. var depthBuffer;
  5138. // Create the depth buffer
  5139. if (generateDepthBuffer) {
  5140. depthBuffer = gl.createRenderbuffer();
  5141. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5142. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5143. }
  5144. // Create the framebuffer
  5145. var framebuffer = gl.createFramebuffer();
  5146. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5147. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5148. if (generateDepthBuffer) {
  5149. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5150. }
  5151. // Unbind
  5152. gl.bindTexture(gl.TEXTURE_2D, null);
  5153. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5154. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5155. texture._framebuffer = framebuffer;
  5156. if (generateDepthBuffer) {
  5157. texture._depthBuffer = depthBuffer;
  5158. }
  5159. texture._width = width;
  5160. texture._height = height;
  5161. texture.isReady = true;
  5162. texture.generateMipMaps = generateMipMaps;
  5163. texture.references = 1;
  5164. texture.samplingMode = samplingMode;
  5165. this._activeTexturesCache = [];
  5166. this._loadedTexturesCache.push(texture);
  5167. return texture;
  5168. };
  5169. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5170. var _this = this;
  5171. var gl = this._gl;
  5172. var texture = gl.createTexture();
  5173. texture.isCube = true;
  5174. texture.url = rootUrl;
  5175. texture.references = 1;
  5176. this._loadedTexturesCache.push(texture);
  5177. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5178. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5179. if (isDDS) {
  5180. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5181. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5182. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5183. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5184. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5185. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5186. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5187. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5188. }
  5189. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5190. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5193. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5194. _this._activeTexturesCache = [];
  5195. texture._width = info.width;
  5196. texture._height = info.height;
  5197. texture.isReady = true;
  5198. }, null, null, true);
  5199. }
  5200. else {
  5201. cascadeLoad(rootUrl, scene, function (imgs) {
  5202. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5203. var height = width;
  5204. _this._prepareWorkingCanvas();
  5205. _this._workingCanvas.width = width;
  5206. _this._workingCanvas.height = height;
  5207. var faces = [
  5208. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5209. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5210. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5211. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5212. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5213. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5214. ];
  5215. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5216. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5217. for (var index = 0; index < faces.length; index++) {
  5218. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5219. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5220. }
  5221. if (!noMipmap) {
  5222. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5223. }
  5224. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5228. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5229. _this._activeTexturesCache = [];
  5230. texture._width = width;
  5231. texture._height = height;
  5232. texture.isReady = true;
  5233. }, extensions);
  5234. }
  5235. return texture;
  5236. };
  5237. Engine.prototype._releaseTexture = function (texture) {
  5238. var gl = this._gl;
  5239. if (texture._framebuffer) {
  5240. gl.deleteFramebuffer(texture._framebuffer);
  5241. }
  5242. if (texture._depthBuffer) {
  5243. gl.deleteRenderbuffer(texture._depthBuffer);
  5244. }
  5245. gl.deleteTexture(texture);
  5246. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5247. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5248. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5249. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5250. this._activeTexturesCache[channel] = null;
  5251. }
  5252. var index = this._loadedTexturesCache.indexOf(texture);
  5253. if (index !== -1) {
  5254. this._loadedTexturesCache.splice(index, 1);
  5255. }
  5256. };
  5257. Engine.prototype.bindSamplers = function (effect) {
  5258. this._gl.useProgram(effect.getProgram());
  5259. var samplers = effect.getSamplers();
  5260. for (var index = 0; index < samplers.length; index++) {
  5261. var uniform = effect.getUniform(samplers[index]);
  5262. this._gl.uniform1i(uniform, index);
  5263. }
  5264. this._currentEffect = null;
  5265. };
  5266. Engine.prototype._bindTexture = function (channel, texture) {
  5267. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5268. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5269. this._activeTexturesCache[channel] = null;
  5270. };
  5271. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5272. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5273. };
  5274. Engine.prototype.setTexture = function (channel, texture) {
  5275. if (channel < 0) {
  5276. return;
  5277. }
  5278. // Not ready?
  5279. if (!texture || !texture.isReady()) {
  5280. if (this._activeTexturesCache[channel] != null) {
  5281. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5282. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5283. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5284. this._activeTexturesCache[channel] = null;
  5285. }
  5286. return;
  5287. }
  5288. // Video
  5289. if (texture instanceof BABYLON.VideoTexture) {
  5290. if (texture.update()) {
  5291. this._activeTexturesCache[channel] = null;
  5292. }
  5293. }
  5294. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5295. texture.delayLoad();
  5296. return;
  5297. }
  5298. if (this._activeTexturesCache[channel] === texture) {
  5299. return;
  5300. }
  5301. this._activeTexturesCache[channel] = texture;
  5302. var internalTexture = texture.getInternalTexture();
  5303. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5304. if (internalTexture.isCube) {
  5305. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5306. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5307. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5308. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5309. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5310. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5311. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5312. }
  5313. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5314. }
  5315. else {
  5316. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5317. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5318. internalTexture._cachedWrapU = texture.wrapU;
  5319. switch (texture.wrapU) {
  5320. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5321. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5322. break;
  5323. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5324. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5325. break;
  5326. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5327. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5328. break;
  5329. }
  5330. }
  5331. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5332. internalTexture._cachedWrapV = texture.wrapV;
  5333. switch (texture.wrapV) {
  5334. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5335. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5336. break;
  5337. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5338. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5339. break;
  5340. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5341. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5342. break;
  5343. }
  5344. }
  5345. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5346. }
  5347. };
  5348. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5349. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5350. var value = texture.anisotropicFilteringLevel;
  5351. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5352. value = 1;
  5353. }
  5354. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5355. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5356. texture._cachedAnisotropicFilteringLevel = value;
  5357. }
  5358. };
  5359. Engine.prototype.readPixels = function (x, y, width, height) {
  5360. var data = new Uint8Array(height * width * 4);
  5361. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5362. return data;
  5363. };
  5364. // Dispose
  5365. Engine.prototype.dispose = function () {
  5366. this.hideLoadingUI();
  5367. this.stopRenderLoop();
  5368. while (this.scenes.length) {
  5369. this.scenes[0].dispose();
  5370. }
  5371. // Release audio engine
  5372. Engine.audioEngine.dispose();
  5373. for (var name in this._compiledEffects) {
  5374. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5375. }
  5376. for (var i in this._vertexAttribArrays) {
  5377. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5378. continue;
  5379. }
  5380. this._gl.disableVertexAttribArray(i);
  5381. }
  5382. // Events
  5383. window.removeEventListener("blur", this._onBlur);
  5384. window.removeEventListener("focus", this._onFocus);
  5385. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5386. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5387. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5388. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5389. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5390. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5391. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5392. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5393. };
  5394. // Loading screen
  5395. Engine.prototype.displayLoadingUI = function () {
  5396. var _this = this;
  5397. this._loadingDiv = document.createElement("div");
  5398. this._loadingDiv.style.opacity = "0";
  5399. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5400. // Loading text
  5401. this._loadingTextDiv = document.createElement("div");
  5402. this._loadingTextDiv.style.position = "absolute";
  5403. this._loadingTextDiv.style.left = "0";
  5404. this._loadingTextDiv.style.top = "50%";
  5405. this._loadingTextDiv.style.marginTop = "80px";
  5406. this._loadingTextDiv.style.width = "100%";
  5407. this._loadingTextDiv.style.height = "20px";
  5408. this._loadingTextDiv.style.fontFamily = "Arial";
  5409. this._loadingTextDiv.style.fontSize = "14px";
  5410. this._loadingTextDiv.style.color = "white";
  5411. this._loadingTextDiv.style.textAlign = "center";
  5412. this._loadingTextDiv.innerHTML = "Loading";
  5413. this._loadingDiv.appendChild(this._loadingTextDiv);
  5414. // Loading img
  5415. var imgBack = new Image();
  5416. 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==";
  5417. imgBack.style.position = "absolute";
  5418. imgBack.style.left = "50%";
  5419. imgBack.style.top = "50%";
  5420. imgBack.style.marginLeft = "-50px";
  5421. imgBack.style.marginTop = "-50px";
  5422. imgBack.style.transition = "transform 1.0s ease";
  5423. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5424. var deg = 360;
  5425. var onTransitionEnd = function () {
  5426. deg += 360;
  5427. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5428. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5429. };
  5430. imgBack.addEventListener("transitionend", onTransitionEnd);
  5431. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5432. this._loadingDiv.appendChild(imgBack);
  5433. // front image
  5434. var imgFront = new Image();
  5435. 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=";
  5436. imgFront.style.position = "absolute";
  5437. imgFront.style.left = "50%";
  5438. imgFront.style.top = "50%";
  5439. imgFront.style.marginLeft = "-50px";
  5440. imgFront.style.marginTop = "-50px";
  5441. this._loadingDiv.appendChild(imgFront);
  5442. // Resize
  5443. this._resizeLoadingUI = function () {
  5444. var canvasRect = _this.getRenderingCanvasClientRect();
  5445. _this._loadingDiv.style.position = "absolute";
  5446. _this._loadingDiv.style.left = canvasRect.left + "px";
  5447. _this._loadingDiv.style.top = canvasRect.top + "px";
  5448. _this._loadingDiv.style.width = canvasRect.width + "px";
  5449. _this._loadingDiv.style.height = canvasRect.height + "px";
  5450. };
  5451. this._resizeLoadingUI();
  5452. window.addEventListener("resize", this._resizeLoadingUI);
  5453. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5454. document.body.appendChild(this._loadingDiv);
  5455. setTimeout(function () {
  5456. _this._loadingDiv.style.opacity = "1";
  5457. imgBack.style.transform = "rotateZ(360deg)";
  5458. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5459. }, 0);
  5460. };
  5461. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5462. set: function (text) {
  5463. if (!this._loadingDiv) {
  5464. return;
  5465. }
  5466. this._loadingTextDiv.innerHTML = text;
  5467. },
  5468. enumerable: true,
  5469. configurable: true
  5470. });
  5471. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5472. get: function () {
  5473. return this._loadingDivBackgroundColor;
  5474. },
  5475. set: function (color) {
  5476. this._loadingDivBackgroundColor = color;
  5477. if (!this._loadingDiv) {
  5478. return;
  5479. }
  5480. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5481. },
  5482. enumerable: true,
  5483. configurable: true
  5484. });
  5485. Engine.prototype.hideLoadingUI = function () {
  5486. var _this = this;
  5487. if (!this._loadingDiv) {
  5488. return;
  5489. }
  5490. var onTransitionEnd = function () {
  5491. if (!_this._loadingDiv) {
  5492. return;
  5493. }
  5494. document.body.removeChild(_this._loadingDiv);
  5495. window.removeEventListener("resize", _this._resizeLoadingUI);
  5496. _this._loadingDiv = null;
  5497. };
  5498. this._loadingDiv.style.opacity = "0";
  5499. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5500. };
  5501. // FPS
  5502. Engine.prototype.getFps = function () {
  5503. return this.fps;
  5504. };
  5505. Engine.prototype.getDeltaTime = function () {
  5506. return this.deltaTime;
  5507. };
  5508. Engine.prototype._measureFps = function () {
  5509. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5510. var length = this.previousFramesDuration.length;
  5511. if (length >= 2) {
  5512. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5513. }
  5514. if (length >= this.fpsRange) {
  5515. if (length > this.fpsRange) {
  5516. this.previousFramesDuration.splice(0, 1);
  5517. length = this.previousFramesDuration.length;
  5518. }
  5519. var sum = 0;
  5520. for (var id = 0; id < length - 1; id++) {
  5521. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5522. }
  5523. this.fps = 1000.0 / (sum / (length - 1));
  5524. }
  5525. };
  5526. // Statics
  5527. Engine.isSupported = function () {
  5528. try {
  5529. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5530. if (navigator.isCocoonJS) {
  5531. return true;
  5532. }
  5533. var tempcanvas = document.createElement("canvas");
  5534. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5535. return gl != null && !!window.WebGLRenderingContext;
  5536. }
  5537. catch (e) {
  5538. return false;
  5539. }
  5540. };
  5541. // Const statics
  5542. Engine._ALPHA_DISABLE = 0;
  5543. Engine._ALPHA_ADD = 1;
  5544. Engine._ALPHA_COMBINE = 2;
  5545. Engine._DELAYLOADSTATE_NONE = 0;
  5546. Engine._DELAYLOADSTATE_LOADED = 1;
  5547. Engine._DELAYLOADSTATE_LOADING = 2;
  5548. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5549. Engine._TEXTUREFORMAT_ALPHA = 0;
  5550. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5551. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5552. Engine._TEXTUREFORMAT_RGB = 4;
  5553. Engine._TEXTUREFORMAT_RGBA = 4;
  5554. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5555. Engine._TEXTURETYPE_FLOAT = 1;
  5556. // Updatable statics so stick with vars here
  5557. Engine.Epsilon = 0.001;
  5558. Engine.CollisionsEpsilon = 0.001;
  5559. Engine.ShadersRepository = "Babylon/Shaders/";
  5560. return Engine;
  5561. })();
  5562. BABYLON.Engine = Engine;
  5563. })(BABYLON || (BABYLON = {}));
  5564. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5565. (function (BABYLON) {
  5566. /**
  5567. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5568. */
  5569. var Node = (function () {
  5570. /**
  5571. * @constructor
  5572. * @param {string} name - the name and id to be given to this node
  5573. * @param {BABYLON.Scene} the scene this node will be added to
  5574. */
  5575. function Node(name, scene) {
  5576. this.state = "";
  5577. this.animations = new Array();
  5578. this._childrenFlag = -1;
  5579. this._isEnabled = true;
  5580. this._isReady = true;
  5581. this._currentRenderId = -1;
  5582. this._parentRenderId = -1;
  5583. this.name = name;
  5584. this.id = name;
  5585. this._scene = scene;
  5586. this._initCache();
  5587. }
  5588. Node.prototype.getScene = function () {
  5589. return this._scene;
  5590. };
  5591. Node.prototype.getEngine = function () {
  5592. return this._scene.getEngine();
  5593. };
  5594. // override it in derived class
  5595. Node.prototype.getWorldMatrix = function () {
  5596. return BABYLON.Matrix.Identity();
  5597. };
  5598. // override it in derived class if you add new variables to the cache
  5599. // and call the parent class method
  5600. Node.prototype._initCache = function () {
  5601. this._cache = {};
  5602. this._cache.parent = undefined;
  5603. };
  5604. Node.prototype.updateCache = function (force) {
  5605. if (!force && this.isSynchronized())
  5606. return;
  5607. this._cache.parent = this.parent;
  5608. this._updateCache();
  5609. };
  5610. // override it in derived class if you add new variables to the cache
  5611. // and call the parent class method if !ignoreParentClass
  5612. Node.prototype._updateCache = function (ignoreParentClass) {
  5613. };
  5614. // override it in derived class if you add new variables to the cache
  5615. Node.prototype._isSynchronized = function () {
  5616. return true;
  5617. };
  5618. Node.prototype.isSynchronizedWithParent = function () {
  5619. if (!this.parent) {
  5620. return true;
  5621. }
  5622. if (this._parentRenderId !== this.parent._currentRenderId) {
  5623. return false;
  5624. }
  5625. this._parentRenderId = this.parent._currentRenderId;
  5626. return this.parent._currentRenderId <= this._currentRenderId && this.parent.isSynchronized();
  5627. };
  5628. Node.prototype.isSynchronized = function (updateCache) {
  5629. var check = this.hasNewParent();
  5630. check = check || !this.isSynchronizedWithParent();
  5631. check = check || !this._isSynchronized();
  5632. if (updateCache)
  5633. this.updateCache(true);
  5634. return !check;
  5635. };
  5636. Node.prototype.hasNewParent = function (update) {
  5637. if (this._cache.parent === this.parent)
  5638. return false;
  5639. if (update)
  5640. this._cache.parent = this.parent;
  5641. return true;
  5642. };
  5643. /**
  5644. * Is this node ready to be used/rendered
  5645. * @return {boolean} is it ready
  5646. */
  5647. Node.prototype.isReady = function () {
  5648. return this._isReady;
  5649. };
  5650. /**
  5651. * Is this node enabled.
  5652. * If the node has a parent and is enabled, the parent will be inspected as well.
  5653. * @return {boolean} whether this node (and its parent) is enabled.
  5654. * @see setEnabled
  5655. */
  5656. Node.prototype.isEnabled = function () {
  5657. if (!this._isEnabled) {
  5658. return false;
  5659. }
  5660. if (this.parent) {
  5661. return this.parent.isEnabled();
  5662. }
  5663. return true;
  5664. };
  5665. /**
  5666. * Set the enabled state of this node.
  5667. * @param {boolean} value - the new enabled state
  5668. * @see isEnabled
  5669. */
  5670. Node.prototype.setEnabled = function (value) {
  5671. this._isEnabled = value;
  5672. };
  5673. /**
  5674. * Is this node a descendant of the given node.
  5675. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5676. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5677. * @see parent
  5678. */
  5679. Node.prototype.isDescendantOf = function (ancestor) {
  5680. if (this.parent) {
  5681. if (this.parent === ancestor) {
  5682. return true;
  5683. }
  5684. return this.parent.isDescendantOf(ancestor);
  5685. }
  5686. return false;
  5687. };
  5688. Node.prototype._getDescendants = function (list, results) {
  5689. for (var index = 0; index < list.length; index++) {
  5690. var item = list[index];
  5691. if (item.isDescendantOf(this)) {
  5692. results.push(item);
  5693. }
  5694. }
  5695. };
  5696. /**
  5697. * Will return all nodes that have this node as parent.
  5698. * @return {BABYLON.Node[]} all children nodes of all types.
  5699. */
  5700. Node.prototype.getDescendants = function () {
  5701. var results = [];
  5702. this._getDescendants(this._scene.meshes, results);
  5703. this._getDescendants(this._scene.lights, results);
  5704. this._getDescendants(this._scene.cameras, results);
  5705. return results;
  5706. };
  5707. Node.prototype._setReady = function (state) {
  5708. if (state == this._isReady) {
  5709. return;
  5710. }
  5711. if (!state) {
  5712. this._isReady = false;
  5713. return;
  5714. }
  5715. this._isReady = true;
  5716. if (this.onReady) {
  5717. this.onReady(this);
  5718. }
  5719. };
  5720. return Node;
  5721. })();
  5722. BABYLON.Node = Node;
  5723. })(BABYLON || (BABYLON = {}));
  5724. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5725. (function (BABYLON) {
  5726. var BoundingSphere = (function () {
  5727. function BoundingSphere(minimum, maximum) {
  5728. this.minimum = minimum;
  5729. this.maximum = maximum;
  5730. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5731. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5732. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5733. this.radius = distance * 0.5;
  5734. this.centerWorld = BABYLON.Vector3.Zero();
  5735. this._update(BABYLON.Matrix.Identity());
  5736. }
  5737. // Methods
  5738. BoundingSphere.prototype._update = function (world) {
  5739. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5740. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5741. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5742. };
  5743. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5744. for (var i = 0; i < 6; i++) {
  5745. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5746. return false;
  5747. }
  5748. return true;
  5749. };
  5750. BoundingSphere.prototype.intersectsPoint = function (point) {
  5751. var x = this.centerWorld.x - point.x;
  5752. var y = this.centerWorld.y - point.y;
  5753. var z = this.centerWorld.z - point.z;
  5754. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5755. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5756. return false;
  5757. return true;
  5758. };
  5759. // Statics
  5760. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5761. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5762. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5763. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5764. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5765. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5766. return false;
  5767. return true;
  5768. };
  5769. return BoundingSphere;
  5770. })();
  5771. BABYLON.BoundingSphere = BoundingSphere;
  5772. })(BABYLON || (BABYLON = {}));
  5773. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5774. (function (BABYLON) {
  5775. var BoundingBox = (function () {
  5776. function BoundingBox(minimum, maximum) {
  5777. this.minimum = minimum;
  5778. this.maximum = maximum;
  5779. this.vectors = new Array();
  5780. this.vectorsWorld = new Array();
  5781. // Bounding vectors
  5782. this.vectors.push(this.minimum.clone());
  5783. this.vectors.push(this.maximum.clone());
  5784. this.vectors.push(this.minimum.clone());
  5785. this.vectors[2].x = this.maximum.x;
  5786. this.vectors.push(this.minimum.clone());
  5787. this.vectors[3].y = this.maximum.y;
  5788. this.vectors.push(this.minimum.clone());
  5789. this.vectors[4].z = this.maximum.z;
  5790. this.vectors.push(this.maximum.clone());
  5791. this.vectors[5].z = this.minimum.z;
  5792. this.vectors.push(this.maximum.clone());
  5793. this.vectors[6].x = this.minimum.x;
  5794. this.vectors.push(this.maximum.clone());
  5795. this.vectors[7].y = this.minimum.y;
  5796. // OBB
  5797. this.center = this.maximum.add(this.minimum).scale(0.5);
  5798. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5799. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5800. for (var index = 0; index < this.vectors.length; index++) {
  5801. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5802. }
  5803. this.minimumWorld = BABYLON.Vector3.Zero();
  5804. this.maximumWorld = BABYLON.Vector3.Zero();
  5805. this._update(BABYLON.Matrix.Identity());
  5806. }
  5807. // Methods
  5808. BoundingBox.prototype.getWorldMatrix = function () {
  5809. return this._worldMatrix;
  5810. };
  5811. BoundingBox.prototype._update = function (world) {
  5812. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5813. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5814. for (var index = 0; index < this.vectors.length; index++) {
  5815. var v = this.vectorsWorld[index];
  5816. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5817. if (v.x < this.minimumWorld.x)
  5818. this.minimumWorld.x = v.x;
  5819. if (v.y < this.minimumWorld.y)
  5820. this.minimumWorld.y = v.y;
  5821. if (v.z < this.minimumWorld.z)
  5822. this.minimumWorld.z = v.z;
  5823. if (v.x > this.maximumWorld.x)
  5824. this.maximumWorld.x = v.x;
  5825. if (v.y > this.maximumWorld.y)
  5826. this.maximumWorld.y = v.y;
  5827. if (v.z > this.maximumWorld.z)
  5828. this.maximumWorld.z = v.z;
  5829. }
  5830. // OBB
  5831. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5832. this.center.scaleInPlace(0.5);
  5833. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5834. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5835. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5836. this._worldMatrix = world;
  5837. };
  5838. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5839. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5840. };
  5841. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5842. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5843. };
  5844. BoundingBox.prototype.intersectsPoint = function (point) {
  5845. var delta = BABYLON.Engine.Epsilon;
  5846. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5847. return false;
  5848. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5849. return false;
  5850. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5851. return false;
  5852. return true;
  5853. };
  5854. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5855. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5856. };
  5857. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5858. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5859. return false;
  5860. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5861. return false;
  5862. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5863. return false;
  5864. return true;
  5865. };
  5866. // Statics
  5867. BoundingBox.Intersects = function (box0, box1) {
  5868. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5869. return false;
  5870. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5871. return false;
  5872. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5873. return false;
  5874. return true;
  5875. };
  5876. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5877. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5878. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5879. return (num <= (sphereRadius * sphereRadius));
  5880. };
  5881. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5882. for (var p = 0; p < 6; p++) {
  5883. for (var i = 0; i < 8; i++) {
  5884. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5885. return false;
  5886. }
  5887. }
  5888. }
  5889. return true;
  5890. };
  5891. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5892. for (var p = 0; p < 6; p++) {
  5893. var inCount = 8;
  5894. for (var i = 0; i < 8; i++) {
  5895. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5896. --inCount;
  5897. }
  5898. else {
  5899. break;
  5900. }
  5901. }
  5902. if (inCount === 0)
  5903. return false;
  5904. }
  5905. return true;
  5906. };
  5907. return BoundingBox;
  5908. })();
  5909. BABYLON.BoundingBox = BoundingBox;
  5910. })(BABYLON || (BABYLON = {}));
  5911. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5912. (function (BABYLON) {
  5913. var computeBoxExtents = function (axis, box) {
  5914. var p = BABYLON.Vector3.Dot(box.center, axis);
  5915. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5916. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5917. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5918. var r = r0 + r1 + r2;
  5919. return {
  5920. min: p - r,
  5921. max: p + r
  5922. };
  5923. };
  5924. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5925. var axisOverlap = function (axis, box0, box1) {
  5926. var result0 = computeBoxExtents(axis, box0);
  5927. var result1 = computeBoxExtents(axis, box1);
  5928. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5929. };
  5930. var BoundingInfo = (function () {
  5931. function BoundingInfo(minimum, maximum) {
  5932. this.minimum = minimum;
  5933. this.maximum = maximum;
  5934. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5935. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5936. }
  5937. // Methods
  5938. BoundingInfo.prototype._update = function (world) {
  5939. this.boundingBox._update(world);
  5940. this.boundingSphere._update(world);
  5941. };
  5942. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5943. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5944. return false;
  5945. return this.boundingBox.isInFrustum(frustumPlanes);
  5946. };
  5947. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5948. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5949. };
  5950. BoundingInfo.prototype._checkCollision = function (collider) {
  5951. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5952. };
  5953. BoundingInfo.prototype.intersectsPoint = function (point) {
  5954. if (!this.boundingSphere.centerWorld) {
  5955. return false;
  5956. }
  5957. if (!this.boundingSphere.intersectsPoint(point)) {
  5958. return false;
  5959. }
  5960. if (!this.boundingBox.intersectsPoint(point)) {
  5961. return false;
  5962. }
  5963. return true;
  5964. };
  5965. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5966. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5967. return false;
  5968. }
  5969. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5970. return false;
  5971. }
  5972. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5973. return false;
  5974. }
  5975. if (!precise) {
  5976. return true;
  5977. }
  5978. var box0 = this.boundingBox;
  5979. var box1 = boundingInfo.boundingBox;
  5980. if (!axisOverlap(box0.directions[0], box0, box1))
  5981. return false;
  5982. if (!axisOverlap(box0.directions[1], box0, box1))
  5983. return false;
  5984. if (!axisOverlap(box0.directions[2], box0, box1))
  5985. return false;
  5986. if (!axisOverlap(box1.directions[0], box0, box1))
  5987. return false;
  5988. if (!axisOverlap(box1.directions[1], box0, box1))
  5989. return false;
  5990. if (!axisOverlap(box1.directions[2], box0, box1))
  5991. return false;
  5992. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5993. return false;
  5994. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5995. return false;
  5996. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5997. return false;
  5998. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5999. return false;
  6000. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  6001. return false;
  6002. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  6003. return false;
  6004. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  6005. return false;
  6006. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  6007. return false;
  6008. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  6009. return false;
  6010. return true;
  6011. };
  6012. return BoundingInfo;
  6013. })();
  6014. BABYLON.BoundingInfo = BoundingInfo;
  6015. })(BABYLON || (BABYLON = {}));
  6016. //# sourceMappingURL=babylon.boundingInfo.js.map
  6017. var BABYLON;
  6018. (function (BABYLON) {
  6019. var Light = (function (_super) {
  6020. __extends(Light, _super);
  6021. function Light(name, scene) {
  6022. _super.call(this, name, scene);
  6023. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  6024. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  6025. this.intensity = 1.0;
  6026. this.range = Number.MAX_VALUE;
  6027. this.includeOnlyWithLayerMask = 0;
  6028. this.includedOnlyMeshes = new Array();
  6029. this.excludedMeshes = new Array();
  6030. this.excludeWithLayerMask = 0;
  6031. this._excludedMeshesIds = new Array();
  6032. this._includedOnlyMeshesIds = new Array();
  6033. scene.addLight(this);
  6034. }
  6035. Light.prototype.getShadowGenerator = function () {
  6036. return this._shadowGenerator;
  6037. };
  6038. Light.prototype.getAbsolutePosition = function () {
  6039. return BABYLON.Vector3.Zero();
  6040. };
  6041. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  6042. };
  6043. Light.prototype._getWorldMatrix = function () {
  6044. return BABYLON.Matrix.Identity();
  6045. };
  6046. Light.prototype.canAffectMesh = function (mesh) {
  6047. if (!mesh) {
  6048. return true;
  6049. }
  6050. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  6051. return false;
  6052. }
  6053. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  6054. return false;
  6055. }
  6056. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  6057. return false;
  6058. }
  6059. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  6060. return false;
  6061. }
  6062. return true;
  6063. };
  6064. Light.prototype.getWorldMatrix = function () {
  6065. this._currentRenderId = this.getScene().getRenderId();
  6066. var worldMatrix = this._getWorldMatrix();
  6067. if (this.parent && this.parent.getWorldMatrix) {
  6068. if (!this._parentedWorldMatrix) {
  6069. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  6070. }
  6071. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  6072. return this._parentedWorldMatrix;
  6073. }
  6074. return worldMatrix;
  6075. };
  6076. Light.prototype.dispose = function () {
  6077. if (this._shadowGenerator) {
  6078. this._shadowGenerator.dispose();
  6079. this._shadowGenerator = null;
  6080. }
  6081. // Remove from scene
  6082. this.getScene().removeLight(this);
  6083. };
  6084. return Light;
  6085. })(BABYLON.Node);
  6086. BABYLON.Light = Light;
  6087. })(BABYLON || (BABYLON = {}));
  6088. //# sourceMappingURL=babylon.light.js.map
  6089. var BABYLON;
  6090. (function (BABYLON) {
  6091. var PointLight = (function (_super) {
  6092. __extends(PointLight, _super);
  6093. function PointLight(name, position, scene) {
  6094. _super.call(this, name, scene);
  6095. this.position = position;
  6096. }
  6097. PointLight.prototype.getAbsolutePosition = function () {
  6098. return this._transformedPosition ? this._transformedPosition : this.position;
  6099. };
  6100. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  6101. if (this.parent && this.parent.getWorldMatrix) {
  6102. if (!this._transformedPosition) {
  6103. this._transformedPosition = BABYLON.Vector3.Zero();
  6104. }
  6105. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  6106. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  6107. return;
  6108. }
  6109. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  6110. };
  6111. PointLight.prototype.getShadowGenerator = function () {
  6112. return null;
  6113. };
  6114. PointLight.prototype._getWorldMatrix = function () {
  6115. if (!this._worldMatrix) {
  6116. this._worldMatrix = BABYLON.Matrix.Identity();
  6117. }
  6118. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6119. return this._worldMatrix;
  6120. };
  6121. return PointLight;
  6122. })(BABYLON.Light);
  6123. BABYLON.PointLight = PointLight;
  6124. })(BABYLON || (BABYLON = {}));
  6125. //# sourceMappingURL=babylon.pointLight.js.map
  6126. var BABYLON;
  6127. (function (BABYLON) {
  6128. var SpotLight = (function (_super) {
  6129. __extends(SpotLight, _super);
  6130. function SpotLight(name, position, direction, angle, exponent, scene) {
  6131. _super.call(this, name, scene);
  6132. this.position = position;
  6133. this.direction = direction;
  6134. this.angle = angle;
  6135. this.exponent = exponent;
  6136. }
  6137. SpotLight.prototype.getAbsolutePosition = function () {
  6138. return this.transformedPosition ? this.transformedPosition : this.position;
  6139. };
  6140. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6141. var activeCamera = this.getScene().activeCamera;
  6142. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6143. };
  6144. SpotLight.prototype.supportsVSM = function () {
  6145. return true;
  6146. };
  6147. SpotLight.prototype.needRefreshPerFrame = function () {
  6148. return false;
  6149. };
  6150. SpotLight.prototype.setDirectionToTarget = function (target) {
  6151. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6152. return this.direction;
  6153. };
  6154. SpotLight.prototype.computeTransformedPosition = function () {
  6155. if (this.parent && this.parent.getWorldMatrix) {
  6156. if (!this.transformedPosition) {
  6157. this.transformedPosition = BABYLON.Vector3.Zero();
  6158. }
  6159. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6160. return true;
  6161. }
  6162. return false;
  6163. };
  6164. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6165. var normalizeDirection;
  6166. if (this.parent && this.parent.getWorldMatrix) {
  6167. if (!this._transformedDirection) {
  6168. this._transformedDirection = BABYLON.Vector3.Zero();
  6169. }
  6170. this.computeTransformedPosition();
  6171. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6172. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6173. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6174. }
  6175. else {
  6176. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6177. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6178. }
  6179. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6180. };
  6181. SpotLight.prototype._getWorldMatrix = function () {
  6182. if (!this._worldMatrix) {
  6183. this._worldMatrix = BABYLON.Matrix.Identity();
  6184. }
  6185. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6186. return this._worldMatrix;
  6187. };
  6188. return SpotLight;
  6189. })(BABYLON.Light);
  6190. BABYLON.SpotLight = SpotLight;
  6191. })(BABYLON || (BABYLON = {}));
  6192. //# sourceMappingURL=babylon.spotLight.js.map
  6193. var BABYLON;
  6194. (function (BABYLON) {
  6195. var DirectionalLight = (function (_super) {
  6196. __extends(DirectionalLight, _super);
  6197. function DirectionalLight(name, direction, scene) {
  6198. _super.call(this, name, scene);
  6199. this.direction = direction;
  6200. this.shadowOrthoScale = 0.5;
  6201. this.position = direction.scale(-1);
  6202. }
  6203. DirectionalLight.prototype.getAbsolutePosition = function () {
  6204. return this.transformedPosition ? this.transformedPosition : this.position;
  6205. };
  6206. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6207. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6208. return this.direction;
  6209. };
  6210. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6211. var orthoLeft = Number.MAX_VALUE;
  6212. var orthoRight = Number.MIN_VALUE;
  6213. var orthoTop = Number.MIN_VALUE;
  6214. var orthoBottom = Number.MAX_VALUE;
  6215. var tempVector3 = BABYLON.Vector3.Zero();
  6216. var activeCamera = this.getScene().activeCamera;
  6217. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6218. var mesh = renderList[meshIndex];
  6219. if (!mesh) {
  6220. continue;
  6221. }
  6222. var boundingInfo = mesh.getBoundingInfo();
  6223. if (!boundingInfo) {
  6224. continue;
  6225. }
  6226. var boundingBox = boundingInfo.boundingBox;
  6227. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6228. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6229. if (tempVector3.x < orthoLeft)
  6230. orthoLeft = tempVector3.x;
  6231. if (tempVector3.y < orthoBottom)
  6232. orthoBottom = tempVector3.y;
  6233. if (tempVector3.x > orthoRight)
  6234. orthoRight = tempVector3.x;
  6235. if (tempVector3.y > orthoTop)
  6236. orthoTop = tempVector3.y;
  6237. }
  6238. }
  6239. var xOffset = orthoRight - orthoLeft;
  6240. var yOffset = orthoTop - orthoBottom;
  6241. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6242. };
  6243. DirectionalLight.prototype.supportsVSM = function () {
  6244. return true;
  6245. };
  6246. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6247. return true;
  6248. };
  6249. DirectionalLight.prototype.computeTransformedPosition = function () {
  6250. if (this.parent && this.parent.getWorldMatrix) {
  6251. if (!this.transformedPosition) {
  6252. this.transformedPosition = BABYLON.Vector3.Zero();
  6253. }
  6254. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6255. return true;
  6256. }
  6257. return false;
  6258. };
  6259. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6260. if (this.parent && this.parent.getWorldMatrix) {
  6261. if (!this._transformedDirection) {
  6262. this._transformedDirection = BABYLON.Vector3.Zero();
  6263. }
  6264. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6265. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6266. return;
  6267. }
  6268. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6269. };
  6270. DirectionalLight.prototype._getWorldMatrix = function () {
  6271. if (!this._worldMatrix) {
  6272. this._worldMatrix = BABYLON.Matrix.Identity();
  6273. }
  6274. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6275. return this._worldMatrix;
  6276. };
  6277. return DirectionalLight;
  6278. })(BABYLON.Light);
  6279. BABYLON.DirectionalLight = DirectionalLight;
  6280. })(BABYLON || (BABYLON = {}));
  6281. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6282. (function (BABYLON) {
  6283. var ShadowGenerator = (function () {
  6284. function ShadowGenerator(mapSize, light) {
  6285. var _this = this;
  6286. // Members
  6287. this._filter = ShadowGenerator.FILTER_NONE;
  6288. this.blurScale = 2;
  6289. this._blurBoxOffset = 0;
  6290. this._bias = 0.00005;
  6291. this._darkness = 0;
  6292. this._transparencyShadow = false;
  6293. this._viewMatrix = BABYLON.Matrix.Zero();
  6294. this._projectionMatrix = BABYLON.Matrix.Zero();
  6295. this._transformMatrix = BABYLON.Matrix.Zero();
  6296. this._worldViewProjection = BABYLON.Matrix.Zero();
  6297. this._light = light;
  6298. this._scene = light.getScene();
  6299. this._mapSize = mapSize;
  6300. light._shadowGenerator = this;
  6301. // Render target
  6302. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6303. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6304. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6305. this._shadowMap.anisotropicFilteringLevel = 1;
  6306. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6307. this._shadowMap.renderParticles = false;
  6308. this._shadowMap.onAfterUnbind = function () {
  6309. if (!_this.useBlurVarianceShadowMap) {
  6310. return;
  6311. }
  6312. if (!_this._shadowMap2) {
  6313. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6314. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6315. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6316. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6317. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6318. _this._downSamplePostprocess.onApply = function (effect) {
  6319. effect.setTexture("textureSampler", _this._shadowMap);
  6320. };
  6321. _this.blurBoxOffset = 1;
  6322. }
  6323. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6324. };
  6325. // Custom render function
  6326. var renderSubMesh = function (subMesh) {
  6327. var mesh = subMesh.getRenderingMesh();
  6328. var scene = _this._scene;
  6329. var engine = scene.getEngine();
  6330. // Culling
  6331. engine.setState(subMesh.getMaterial().backFaceCulling);
  6332. // Managing instances
  6333. var batch = mesh._getInstancesRenderList(subMesh._id);
  6334. if (batch.mustReturn) {
  6335. return;
  6336. }
  6337. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6338. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6339. engine.enableEffect(_this._effect);
  6340. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6341. var material = subMesh.getMaterial();
  6342. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6343. // Alpha test
  6344. if (material && material.needAlphaTesting()) {
  6345. var alphaTexture = material.getAlphaTestTexture();
  6346. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6347. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6348. }
  6349. // Bones
  6350. if (mesh.useBones) {
  6351. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6352. }
  6353. // Draw
  6354. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6355. }
  6356. else {
  6357. // Need to reset refresh rate of the shadowMap
  6358. _this._shadowMap.resetRefreshCounter();
  6359. }
  6360. };
  6361. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6362. var index;
  6363. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6364. renderSubMesh(opaqueSubMeshes.data[index]);
  6365. }
  6366. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6367. renderSubMesh(alphaTestSubMeshes.data[index]);
  6368. }
  6369. if (_this._transparencyShadow) {
  6370. for (index = 0; index < transparentSubMeshes.length; index++) {
  6371. renderSubMesh(transparentSubMeshes.data[index]);
  6372. }
  6373. }
  6374. };
  6375. this._shadowMap.onClear = function (engine) {
  6376. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6377. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6378. }
  6379. else {
  6380. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6381. }
  6382. };
  6383. }
  6384. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6385. // Static
  6386. get: function () {
  6387. return ShadowGenerator._FILTER_NONE;
  6388. },
  6389. enumerable: true,
  6390. configurable: true
  6391. });
  6392. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6393. get: function () {
  6394. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6395. },
  6396. enumerable: true,
  6397. configurable: true
  6398. });
  6399. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6400. get: function () {
  6401. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6402. },
  6403. enumerable: true,
  6404. configurable: true
  6405. });
  6406. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6407. get: function () {
  6408. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6409. },
  6410. enumerable: true,
  6411. configurable: true
  6412. });
  6413. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6414. get: function () {
  6415. return this._bias;
  6416. },
  6417. set: function (bias) {
  6418. this._bias = bias;
  6419. },
  6420. enumerable: true,
  6421. configurable: true
  6422. });
  6423. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6424. get: function () {
  6425. return this._blurBoxOffset;
  6426. },
  6427. set: function (value) {
  6428. var _this = this;
  6429. if (this._blurBoxOffset === value) {
  6430. return;
  6431. }
  6432. this._blurBoxOffset = value;
  6433. if (this._boxBlurPostprocess) {
  6434. this._boxBlurPostprocess.dispose();
  6435. }
  6436. 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);
  6437. this._boxBlurPostprocess.onApply = function (effect) {
  6438. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6439. };
  6440. },
  6441. enumerable: true,
  6442. configurable: true
  6443. });
  6444. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6445. get: function () {
  6446. return this._filter;
  6447. },
  6448. set: function (value) {
  6449. if (this._filter === value) {
  6450. return;
  6451. }
  6452. this._filter = value;
  6453. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6454. this._shadowMap.anisotropicFilteringLevel = 16;
  6455. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6456. }
  6457. else {
  6458. this._shadowMap.anisotropicFilteringLevel = 1;
  6459. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6460. }
  6461. },
  6462. enumerable: true,
  6463. configurable: true
  6464. });
  6465. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6466. get: function () {
  6467. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6468. },
  6469. set: function (value) {
  6470. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6471. },
  6472. enumerable: true,
  6473. configurable: true
  6474. });
  6475. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6476. get: function () {
  6477. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6478. },
  6479. set: function (value) {
  6480. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6481. },
  6482. enumerable: true,
  6483. configurable: true
  6484. });
  6485. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6486. get: function () {
  6487. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6488. },
  6489. set: function (value) {
  6490. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6491. },
  6492. enumerable: true,
  6493. configurable: true
  6494. });
  6495. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6496. var defines = [];
  6497. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6498. defines.push("#define VSM");
  6499. }
  6500. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6501. var mesh = subMesh.getMesh();
  6502. var material = subMesh.getMaterial();
  6503. // Alpha test
  6504. if (material && material.needAlphaTesting()) {
  6505. defines.push("#define ALPHATEST");
  6506. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6507. attribs.push(BABYLON.VertexBuffer.UVKind);
  6508. defines.push("#define UV1");
  6509. }
  6510. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6511. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6512. defines.push("#define UV2");
  6513. }
  6514. }
  6515. // Bones
  6516. if (mesh.useBones) {
  6517. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6518. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6519. defines.push("#define BONES");
  6520. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6521. }
  6522. // Instances
  6523. if (useInstances) {
  6524. defines.push("#define INSTANCES");
  6525. attribs.push("world0");
  6526. attribs.push("world1");
  6527. attribs.push("world2");
  6528. attribs.push("world3");
  6529. }
  6530. // Get correct effect
  6531. var join = defines.join("\n");
  6532. if (this._cachedDefines !== join) {
  6533. this._cachedDefines = join;
  6534. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6535. }
  6536. return this._effect.isReady();
  6537. };
  6538. ShadowGenerator.prototype.getShadowMap = function () {
  6539. return this._shadowMap;
  6540. };
  6541. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6542. if (this._shadowMap2) {
  6543. return this._shadowMap2;
  6544. }
  6545. return this._shadowMap;
  6546. };
  6547. ShadowGenerator.prototype.getLight = function () {
  6548. return this._light;
  6549. };
  6550. // Methods
  6551. ShadowGenerator.prototype.getTransformMatrix = function () {
  6552. var scene = this._scene;
  6553. if (this._currentRenderID === scene.getRenderId()) {
  6554. return this._transformMatrix;
  6555. }
  6556. this._currentRenderID = scene.getRenderId();
  6557. var lightPosition = this._light.position;
  6558. var lightDirection = this._light.direction;
  6559. if (this._light.computeTransformedPosition()) {
  6560. lightPosition = this._light.transformedPosition;
  6561. }
  6562. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6563. this._cachedPosition = lightPosition.clone();
  6564. this._cachedDirection = lightDirection.clone();
  6565. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6566. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6567. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6568. }
  6569. return this._transformMatrix;
  6570. };
  6571. ShadowGenerator.prototype.getDarkness = function () {
  6572. return this._darkness;
  6573. };
  6574. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6575. if (darkness >= 1.0)
  6576. this._darkness = 1.0;
  6577. else if (darkness <= 0.0)
  6578. this._darkness = 0.0;
  6579. else
  6580. this._darkness = darkness;
  6581. };
  6582. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6583. this._transparencyShadow = hasShadow;
  6584. };
  6585. ShadowGenerator.prototype._packHalf = function (depth) {
  6586. var scale = depth * 255.0;
  6587. var fract = scale - Math.floor(scale);
  6588. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6589. };
  6590. ShadowGenerator.prototype.dispose = function () {
  6591. this._shadowMap.dispose();
  6592. if (this._shadowMap2) {
  6593. this._shadowMap2.dispose();
  6594. }
  6595. if (this._downSamplePostprocess) {
  6596. this._downSamplePostprocess.dispose();
  6597. }
  6598. if (this._boxBlurPostprocess) {
  6599. this._boxBlurPostprocess.dispose();
  6600. }
  6601. };
  6602. ShadowGenerator._FILTER_NONE = 0;
  6603. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6604. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6605. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6606. return ShadowGenerator;
  6607. })();
  6608. BABYLON.ShadowGenerator = ShadowGenerator;
  6609. })(BABYLON || (BABYLON = {}));
  6610. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6611. var BABYLON;
  6612. (function (BABYLON) {
  6613. var HemisphericLight = (function (_super) {
  6614. __extends(HemisphericLight, _super);
  6615. function HemisphericLight(name, direction, scene) {
  6616. _super.call(this, name, scene);
  6617. this.direction = direction;
  6618. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6619. }
  6620. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6621. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6622. return this.direction;
  6623. };
  6624. HemisphericLight.prototype.getShadowGenerator = function () {
  6625. return null;
  6626. };
  6627. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6628. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6629. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6630. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6631. };
  6632. HemisphericLight.prototype._getWorldMatrix = function () {
  6633. if (!this._worldMatrix) {
  6634. this._worldMatrix = BABYLON.Matrix.Identity();
  6635. }
  6636. return this._worldMatrix;
  6637. };
  6638. return HemisphericLight;
  6639. })(BABYLON.Light);
  6640. BABYLON.HemisphericLight = HemisphericLight;
  6641. })(BABYLON || (BABYLON = {}));
  6642. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6643. (function (BABYLON) {
  6644. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6645. if (boxMin.x > sphereCenter.x + sphereRadius)
  6646. return false;
  6647. if (sphereCenter.x - sphereRadius > boxMax.x)
  6648. return false;
  6649. if (boxMin.y > sphereCenter.y + sphereRadius)
  6650. return false;
  6651. if (sphereCenter.y - sphereRadius > boxMax.y)
  6652. return false;
  6653. if (boxMin.z > sphereCenter.z + sphereRadius)
  6654. return false;
  6655. if (sphereCenter.z - sphereRadius > boxMax.z)
  6656. return false;
  6657. return true;
  6658. };
  6659. var getLowestRoot = function (a, b, c, maxR) {
  6660. var determinant = b * b - 4.0 * a * c;
  6661. var result = { root: 0, found: false };
  6662. if (determinant < 0)
  6663. return result;
  6664. var sqrtD = Math.sqrt(determinant);
  6665. var r1 = (-b - sqrtD) / (2.0 * a);
  6666. var r2 = (-b + sqrtD) / (2.0 * a);
  6667. if (r1 > r2) {
  6668. var temp = r2;
  6669. r2 = r1;
  6670. r1 = temp;
  6671. }
  6672. if (r1 > 0 && r1 < maxR) {
  6673. result.root = r1;
  6674. result.found = true;
  6675. return result;
  6676. }
  6677. if (r2 > 0 && r2 < maxR) {
  6678. result.root = r2;
  6679. result.found = true;
  6680. return result;
  6681. }
  6682. return result;
  6683. };
  6684. var Collider = (function () {
  6685. function Collider() {
  6686. this.radius = new BABYLON.Vector3(1, 1, 1);
  6687. this.retry = 0;
  6688. this.basePointWorld = BABYLON.Vector3.Zero();
  6689. this.velocityWorld = BABYLON.Vector3.Zero();
  6690. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6691. this._collisionPoint = BABYLON.Vector3.Zero();
  6692. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6693. this._tempVector = BABYLON.Vector3.Zero();
  6694. this._tempVector2 = BABYLON.Vector3.Zero();
  6695. this._tempVector3 = BABYLON.Vector3.Zero();
  6696. this._tempVector4 = BABYLON.Vector3.Zero();
  6697. this._edge = BABYLON.Vector3.Zero();
  6698. this._baseToVertex = BABYLON.Vector3.Zero();
  6699. this._destinationPoint = BABYLON.Vector3.Zero();
  6700. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6701. this._displacementVector = BABYLON.Vector3.Zero();
  6702. }
  6703. // Methods
  6704. Collider.prototype._initialize = function (source, dir, e) {
  6705. this.velocity = dir;
  6706. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6707. this.basePoint = source;
  6708. source.multiplyToRef(this.radius, this.basePointWorld);
  6709. dir.multiplyToRef(this.radius, this.velocityWorld);
  6710. this.velocityWorldLength = this.velocityWorld.length();
  6711. this.epsilon = e;
  6712. this.collisionFound = false;
  6713. };
  6714. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6715. pa.subtractToRef(point, this._tempVector);
  6716. pb.subtractToRef(point, this._tempVector2);
  6717. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6718. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6719. if (d < 0)
  6720. return false;
  6721. pc.subtractToRef(point, this._tempVector3);
  6722. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6723. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6724. if (d < 0)
  6725. return false;
  6726. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6727. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6728. return d >= 0;
  6729. };
  6730. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6731. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6732. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6733. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6734. return false;
  6735. }
  6736. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6737. return false;
  6738. return true;
  6739. };
  6740. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6741. var t0;
  6742. var embeddedInPlane = false;
  6743. if (!subMesh._trianglePlanes) {
  6744. subMesh._trianglePlanes = [];
  6745. }
  6746. if (!subMesh._trianglePlanes[faceIndex]) {
  6747. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6748. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6749. }
  6750. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6751. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6752. return;
  6753. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6754. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6755. if (normalDotVelocity == 0) {
  6756. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6757. return;
  6758. embeddedInPlane = true;
  6759. t0 = 0;
  6760. }
  6761. else {
  6762. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6763. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6764. if (t0 > t1) {
  6765. var temp = t1;
  6766. t1 = t0;
  6767. t0 = temp;
  6768. }
  6769. if (t0 > 1.0 || t1 < 0.0)
  6770. return;
  6771. if (t0 < 0)
  6772. t0 = 0;
  6773. if (t0 > 1.0)
  6774. t0 = 1.0;
  6775. }
  6776. this._collisionPoint.copyFromFloats(0, 0, 0);
  6777. var found = false;
  6778. var t = 1.0;
  6779. if (!embeddedInPlane) {
  6780. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6781. this.velocity.scaleToRef(t0, this._tempVector);
  6782. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6783. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6784. found = true;
  6785. t = t0;
  6786. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6787. }
  6788. }
  6789. if (!found) {
  6790. var velocitySquaredLength = this.velocity.lengthSquared();
  6791. var a = velocitySquaredLength;
  6792. this.basePoint.subtractToRef(p1, this._tempVector);
  6793. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6794. var c = this._tempVector.lengthSquared() - 1.0;
  6795. var lowestRoot = getLowestRoot(a, b, c, t);
  6796. if (lowestRoot.found) {
  6797. t = lowestRoot.root;
  6798. found = true;
  6799. this._collisionPoint.copyFrom(p1);
  6800. }
  6801. this.basePoint.subtractToRef(p2, this._tempVector);
  6802. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6803. c = this._tempVector.lengthSquared() - 1.0;
  6804. lowestRoot = getLowestRoot(a, b, c, t);
  6805. if (lowestRoot.found) {
  6806. t = lowestRoot.root;
  6807. found = true;
  6808. this._collisionPoint.copyFrom(p2);
  6809. }
  6810. this.basePoint.subtractToRef(p3, this._tempVector);
  6811. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6812. c = this._tempVector.lengthSquared() - 1.0;
  6813. lowestRoot = getLowestRoot(a, b, c, t);
  6814. if (lowestRoot.found) {
  6815. t = lowestRoot.root;
  6816. found = true;
  6817. this._collisionPoint.copyFrom(p3);
  6818. }
  6819. p2.subtractToRef(p1, this._edge);
  6820. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6821. var edgeSquaredLength = this._edge.lengthSquared();
  6822. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6823. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6824. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6825. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6826. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6827. lowestRoot = getLowestRoot(a, b, c, t);
  6828. if (lowestRoot.found) {
  6829. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6830. if (f >= 0.0 && f <= 1.0) {
  6831. t = lowestRoot.root;
  6832. found = true;
  6833. this._edge.scaleInPlace(f);
  6834. p1.addToRef(this._edge, this._collisionPoint);
  6835. }
  6836. }
  6837. p3.subtractToRef(p2, this._edge);
  6838. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6839. edgeSquaredLength = this._edge.lengthSquared();
  6840. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6841. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6842. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6843. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6844. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6845. lowestRoot = getLowestRoot(a, b, c, t);
  6846. if (lowestRoot.found) {
  6847. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6848. if (f >= 0.0 && f <= 1.0) {
  6849. t = lowestRoot.root;
  6850. found = true;
  6851. this._edge.scaleInPlace(f);
  6852. p2.addToRef(this._edge, this._collisionPoint);
  6853. }
  6854. }
  6855. p1.subtractToRef(p3, this._edge);
  6856. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6857. edgeSquaredLength = this._edge.lengthSquared();
  6858. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6859. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6860. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6861. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6862. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6863. lowestRoot = getLowestRoot(a, b, c, t);
  6864. if (lowestRoot.found) {
  6865. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6866. if (f >= 0.0 && f <= 1.0) {
  6867. t = lowestRoot.root;
  6868. found = true;
  6869. this._edge.scaleInPlace(f);
  6870. p3.addToRef(this._edge, this._collisionPoint);
  6871. }
  6872. }
  6873. }
  6874. if (found) {
  6875. var distToCollision = t * this.velocity.length();
  6876. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6877. if (!this.intersectionPoint) {
  6878. this.intersectionPoint = this._collisionPoint.clone();
  6879. }
  6880. else {
  6881. this.intersectionPoint.copyFrom(this._collisionPoint);
  6882. }
  6883. this.nearestDistance = distToCollision;
  6884. this.collisionFound = true;
  6885. this.collidedMesh = subMesh.getMesh();
  6886. }
  6887. }
  6888. };
  6889. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6890. for (var i = indexStart; i < indexEnd; i += 3) {
  6891. var p1 = pts[indices[i] - decal];
  6892. var p2 = pts[indices[i + 1] - decal];
  6893. var p3 = pts[indices[i + 2] - decal];
  6894. this._testTriangle(i, subMesh, p3, p2, p1);
  6895. }
  6896. };
  6897. Collider.prototype._getResponse = function (pos, vel) {
  6898. pos.addToRef(vel, this._destinationPoint);
  6899. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6900. this.basePoint.addToRef(vel, pos);
  6901. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6902. this._slidePlaneNormal.normalize();
  6903. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6904. pos.addInPlace(this._displacementVector);
  6905. this.intersectionPoint.addInPlace(this._displacementVector);
  6906. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6907. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6908. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6909. };
  6910. return Collider;
  6911. })();
  6912. BABYLON.Collider = Collider;
  6913. })(BABYLON || (BABYLON = {}));
  6914. //# sourceMappingURL=babylon.collider.js.map
  6915. var BABYLON;
  6916. (function (BABYLON) {
  6917. var Camera = (function (_super) {
  6918. __extends(Camera, _super);
  6919. function Camera(name, position, scene) {
  6920. _super.call(this, name, scene);
  6921. this.position = position;
  6922. // Members
  6923. this.upVector = BABYLON.Vector3.Up();
  6924. this.orthoLeft = null;
  6925. this.orthoRight = null;
  6926. this.orthoBottom = null;
  6927. this.orthoTop = null;
  6928. this.fov = 0.8;
  6929. this.minZ = 1.0;
  6930. this.maxZ = 10000.0;
  6931. this.inertia = 0.9;
  6932. this.mode = Camera.PERSPECTIVE_CAMERA;
  6933. this.isIntermediate = false;
  6934. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6935. this.subCameras = [];
  6936. this.layerMask = 0xFFFFFFFF;
  6937. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6938. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6939. this._projectionMatrix = new BABYLON.Matrix();
  6940. this._postProcesses = new Array();
  6941. this._postProcessesTakenIndices = [];
  6942. this._activeMeshes = new BABYLON.SmartArray(256);
  6943. this._globalPosition = BABYLON.Vector3.Zero();
  6944. scene.addCamera(this);
  6945. if (!scene.activeCamera) {
  6946. scene.activeCamera = this;
  6947. }
  6948. }
  6949. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6950. get: function () {
  6951. return Camera._PERSPECTIVE_CAMERA;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6957. get: function () {
  6958. return Camera._ORTHOGRAPHIC_CAMERA;
  6959. },
  6960. enumerable: true,
  6961. configurable: true
  6962. });
  6963. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6964. get: function () {
  6965. return Camera._FOVMODE_VERTICAL_FIXED;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6971. get: function () {
  6972. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6973. },
  6974. enumerable: true,
  6975. configurable: true
  6976. });
  6977. Object.defineProperty(Camera.prototype, "globalPosition", {
  6978. get: function () {
  6979. return this._globalPosition;
  6980. },
  6981. enumerable: true,
  6982. configurable: true
  6983. });
  6984. Camera.prototype.getActiveMeshes = function () {
  6985. return this._activeMeshes;
  6986. };
  6987. Camera.prototype.isActiveMesh = function (mesh) {
  6988. return (this._activeMeshes.indexOf(mesh) !== -1);
  6989. };
  6990. //Cache
  6991. Camera.prototype._initCache = function () {
  6992. _super.prototype._initCache.call(this);
  6993. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6994. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6995. this._cache.mode = undefined;
  6996. this._cache.minZ = undefined;
  6997. this._cache.maxZ = undefined;
  6998. this._cache.fov = undefined;
  6999. this._cache.aspectRatio = undefined;
  7000. this._cache.orthoLeft = undefined;
  7001. this._cache.orthoRight = undefined;
  7002. this._cache.orthoBottom = undefined;
  7003. this._cache.orthoTop = undefined;
  7004. this._cache.renderWidth = undefined;
  7005. this._cache.renderHeight = undefined;
  7006. };
  7007. Camera.prototype._updateCache = function (ignoreParentClass) {
  7008. if (!ignoreParentClass) {
  7009. _super.prototype._updateCache.call(this);
  7010. }
  7011. var engine = this.getEngine();
  7012. this._cache.position.copyFrom(this.position);
  7013. this._cache.upVector.copyFrom(this.upVector);
  7014. this._cache.mode = this.mode;
  7015. this._cache.minZ = this.minZ;
  7016. this._cache.maxZ = this.maxZ;
  7017. this._cache.fov = this.fov;
  7018. this._cache.aspectRatio = engine.getAspectRatio(this);
  7019. this._cache.orthoLeft = this.orthoLeft;
  7020. this._cache.orthoRight = this.orthoRight;
  7021. this._cache.orthoBottom = this.orthoBottom;
  7022. this._cache.orthoTop = this.orthoTop;
  7023. this._cache.renderWidth = engine.getRenderWidth();
  7024. this._cache.renderHeight = engine.getRenderHeight();
  7025. };
  7026. Camera.prototype._updateFromScene = function () {
  7027. this.updateCache();
  7028. this._update();
  7029. };
  7030. // Synchronized
  7031. Camera.prototype._isSynchronized = function () {
  7032. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  7033. };
  7034. Camera.prototype._isSynchronizedViewMatrix = function () {
  7035. if (!_super.prototype._isSynchronized.call(this))
  7036. return false;
  7037. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  7038. };
  7039. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  7040. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  7041. if (!check) {
  7042. return false;
  7043. }
  7044. var engine = this.getEngine();
  7045. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7046. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  7047. }
  7048. else {
  7049. 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();
  7050. }
  7051. return check;
  7052. };
  7053. // Controls
  7054. Camera.prototype.attachControl = function (element) {
  7055. };
  7056. Camera.prototype.detachControl = function (element) {
  7057. };
  7058. Camera.prototype._update = function () {
  7059. };
  7060. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  7061. if (insertAt === void 0) { insertAt = null; }
  7062. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  7063. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  7064. return 0;
  7065. }
  7066. if (insertAt == null || insertAt < 0) {
  7067. this._postProcesses.push(postProcess);
  7068. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  7069. return this._postProcesses.length - 1;
  7070. }
  7071. var add = 0;
  7072. if (this._postProcesses[insertAt]) {
  7073. var start = this._postProcesses.length - 1;
  7074. for (var i = start; i >= insertAt + 1; --i) {
  7075. this._postProcesses[i + 1] = this._postProcesses[i];
  7076. }
  7077. add = 1;
  7078. }
  7079. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7080. if (this._postProcessesTakenIndices[i] < insertAt) {
  7081. continue;
  7082. }
  7083. start = this._postProcessesTakenIndices.length - 1;
  7084. for (var j = start; j >= i; --j) {
  7085. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  7086. }
  7087. this._postProcessesTakenIndices[i] = insertAt;
  7088. break;
  7089. }
  7090. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  7091. this._postProcessesTakenIndices.push(insertAt);
  7092. }
  7093. var result = insertAt + add;
  7094. this._postProcesses[result] = postProcess;
  7095. return result;
  7096. };
  7097. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  7098. if (atIndices === void 0) { atIndices = null; }
  7099. var result = [];
  7100. if (!atIndices) {
  7101. var length = this._postProcesses.length;
  7102. for (var i = 0; i < length; i++) {
  7103. if (this._postProcesses[i] !== postProcess) {
  7104. continue;
  7105. }
  7106. delete this._postProcesses[i];
  7107. var index = this._postProcessesTakenIndices.indexOf(i);
  7108. this._postProcessesTakenIndices.splice(index, 1);
  7109. }
  7110. }
  7111. else {
  7112. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  7113. for (i = 0; i < atIndices.length; i++) {
  7114. var foundPostProcess = this._postProcesses[atIndices[i]];
  7115. if (foundPostProcess !== postProcess) {
  7116. result.push(i);
  7117. continue;
  7118. }
  7119. delete this._postProcesses[atIndices[i]];
  7120. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  7121. this._postProcessesTakenIndices.splice(index, 1);
  7122. }
  7123. }
  7124. return result;
  7125. };
  7126. Camera.prototype.getWorldMatrix = function () {
  7127. if (!this._worldMatrix) {
  7128. this._worldMatrix = BABYLON.Matrix.Identity();
  7129. }
  7130. var viewMatrix = this.getViewMatrix();
  7131. viewMatrix.invertToRef(this._worldMatrix);
  7132. return this._worldMatrix;
  7133. };
  7134. Camera.prototype._getViewMatrix = function () {
  7135. return BABYLON.Matrix.Identity();
  7136. };
  7137. Camera.prototype.getViewMatrix = function () {
  7138. this._computedViewMatrix = this._computeViewMatrix();
  7139. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  7140. this._globalPosition.copyFrom(this.position);
  7141. return this._computedViewMatrix;
  7142. }
  7143. if (!this._worldMatrix) {
  7144. this._worldMatrix = BABYLON.Matrix.Identity();
  7145. }
  7146. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7147. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7148. this._computedViewMatrix.invert();
  7149. this._currentRenderId = this.getScene().getRenderId();
  7150. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  7151. return this._computedViewMatrix;
  7152. };
  7153. Camera.prototype._computeViewMatrix = function (force) {
  7154. if (!force && this._isSynchronizedViewMatrix()) {
  7155. return this._computedViewMatrix;
  7156. }
  7157. this._computedViewMatrix = this._getViewMatrix();
  7158. if (!this.parent || !this.parent.getWorldMatrix) {
  7159. this._currentRenderId = this.getScene().getRenderId();
  7160. }
  7161. return this._computedViewMatrix;
  7162. };
  7163. Camera.prototype.getProjectionMatrix = function (force) {
  7164. if (!force && this._isSynchronizedProjectionMatrix()) {
  7165. return this._projectionMatrix;
  7166. }
  7167. var engine = this.getEngine();
  7168. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7169. if (this.minZ <= 0) {
  7170. this.minZ = 0.1;
  7171. }
  7172. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7173. return this._projectionMatrix;
  7174. }
  7175. var halfWidth = engine.getRenderWidth() / 2.0;
  7176. var halfHeight = engine.getRenderHeight() / 2.0;
  7177. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7178. return this._projectionMatrix;
  7179. };
  7180. Camera.prototype.dispose = function () {
  7181. // Remove from scene
  7182. this.getScene().removeCamera(this);
  7183. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7184. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7185. }
  7186. };
  7187. // Statics
  7188. Camera._PERSPECTIVE_CAMERA = 0;
  7189. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7190. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7191. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7192. return Camera;
  7193. })(BABYLON.Node);
  7194. BABYLON.Camera = Camera;
  7195. })(BABYLON || (BABYLON = {}));
  7196. //# sourceMappingURL=babylon.camera.js.map
  7197. var BABYLON;
  7198. (function (BABYLON) {
  7199. var TargetCamera = (function (_super) {
  7200. __extends(TargetCamera, _super);
  7201. function TargetCamera(name, position, scene) {
  7202. _super.call(this, name, position, scene);
  7203. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7204. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7205. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7206. this.speed = 2.0;
  7207. this.noRotationConstraint = false;
  7208. this.lockedTarget = null;
  7209. this._currentTarget = BABYLON.Vector3.Zero();
  7210. this._viewMatrix = BABYLON.Matrix.Zero();
  7211. this._camMatrix = BABYLON.Matrix.Zero();
  7212. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7213. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7214. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7215. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7216. this._lookAtTemp = BABYLON.Matrix.Zero();
  7217. this._tempMatrix = BABYLON.Matrix.Zero();
  7218. }
  7219. TargetCamera.prototype._getLockedTargetPosition = function () {
  7220. if (!this.lockedTarget) {
  7221. return null;
  7222. }
  7223. return this.lockedTarget.position || this.lockedTarget;
  7224. };
  7225. // Cache
  7226. TargetCamera.prototype._initCache = function () {
  7227. _super.prototype._initCache.call(this);
  7228. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7229. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7230. };
  7231. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7232. if (!ignoreParentClass) {
  7233. _super.prototype._updateCache.call(this);
  7234. }
  7235. var lockedTargetPosition = this._getLockedTargetPosition();
  7236. if (!lockedTargetPosition) {
  7237. this._cache.lockedTarget = null;
  7238. }
  7239. else {
  7240. if (!this._cache.lockedTarget) {
  7241. this._cache.lockedTarget = lockedTargetPosition.clone();
  7242. }
  7243. else {
  7244. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7245. }
  7246. }
  7247. this._cache.rotation.copyFrom(this.rotation);
  7248. };
  7249. // Synchronized
  7250. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7251. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7252. return false;
  7253. }
  7254. var lockedTargetPosition = this._getLockedTargetPosition();
  7255. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7256. };
  7257. // Methods
  7258. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7259. var engine = this.getEngine();
  7260. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7261. };
  7262. // Target
  7263. TargetCamera.prototype.setTarget = function (target) {
  7264. this.upVector.normalize();
  7265. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7266. this._camMatrix.invert();
  7267. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7268. var vDir = target.subtract(this.position);
  7269. if (vDir.x >= 0.0) {
  7270. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7271. }
  7272. else {
  7273. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7274. }
  7275. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7276. if (isNaN(this.rotation.x)) {
  7277. this.rotation.x = 0;
  7278. }
  7279. if (isNaN(this.rotation.y)) {
  7280. this.rotation.y = 0;
  7281. }
  7282. if (isNaN(this.rotation.z)) {
  7283. this.rotation.z = 0;
  7284. }
  7285. };
  7286. TargetCamera.prototype.getTarget = function () {
  7287. return this._currentTarget;
  7288. };
  7289. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7290. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7291. };
  7292. TargetCamera.prototype._updatePosition = function () {
  7293. this.position.addInPlace(this.cameraDirection);
  7294. };
  7295. TargetCamera.prototype._update = function () {
  7296. var needToMove = this._decideIfNeedsToMove();
  7297. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7298. // Move
  7299. if (needToMove) {
  7300. this._updatePosition();
  7301. }
  7302. // Rotate
  7303. if (needToRotate) {
  7304. this.rotation.x += this.cameraRotation.x;
  7305. this.rotation.y += this.cameraRotation.y;
  7306. if (!this.noRotationConstraint) {
  7307. var limit = (Math.PI / 2) * 0.95;
  7308. if (this.rotation.x > limit)
  7309. this.rotation.x = limit;
  7310. if (this.rotation.x < -limit)
  7311. this.rotation.x = -limit;
  7312. }
  7313. }
  7314. // Inertia
  7315. if (needToMove) {
  7316. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7317. this.cameraDirection.x = 0;
  7318. }
  7319. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7320. this.cameraDirection.y = 0;
  7321. }
  7322. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7323. this.cameraDirection.z = 0;
  7324. }
  7325. this.cameraDirection.scaleInPlace(this.inertia);
  7326. }
  7327. if (needToRotate) {
  7328. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7329. this.cameraRotation.x = 0;
  7330. }
  7331. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7332. this.cameraRotation.y = 0;
  7333. }
  7334. this.cameraRotation.scaleInPlace(this.inertia);
  7335. }
  7336. };
  7337. TargetCamera.prototype._getViewMatrix = function () {
  7338. if (!this.lockedTarget) {
  7339. // Compute
  7340. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7341. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7342. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7343. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7344. this._lookAtTemp.invert();
  7345. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7346. }
  7347. else {
  7348. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7349. }
  7350. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7351. // Computing target and final matrix
  7352. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7353. }
  7354. else {
  7355. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7356. }
  7357. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7358. return this._viewMatrix;
  7359. };
  7360. return TargetCamera;
  7361. })(BABYLON.Camera);
  7362. BABYLON.TargetCamera = TargetCamera;
  7363. })(BABYLON || (BABYLON = {}));
  7364. //# sourceMappingURL=babylon.targetCamera.js.map
  7365. var BABYLON;
  7366. (function (BABYLON) {
  7367. var FollowCamera = (function (_super) {
  7368. __extends(FollowCamera, _super);
  7369. function FollowCamera(name, position, scene) {
  7370. _super.call(this, name, position, scene);
  7371. this.radius = 12;
  7372. this.rotationOffset = 0;
  7373. this.heightOffset = 4;
  7374. this.cameraAcceleration = 0.05;
  7375. this.maxCameraSpeed = 20;
  7376. }
  7377. FollowCamera.prototype.getRadians = function (degrees) {
  7378. return degrees * Math.PI / 180;
  7379. };
  7380. FollowCamera.prototype.follow = function (cameraTarget) {
  7381. if (!cameraTarget)
  7382. return;
  7383. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7384. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7385. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7386. var dx = targetX - this.position.x;
  7387. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7388. var dz = (targetZ) - this.position.z;
  7389. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7390. var vy = dy * this.cameraAcceleration;
  7391. var vz = dz * this.cameraAcceleration * 2;
  7392. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7393. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7394. }
  7395. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7396. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7397. }
  7398. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7399. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7400. }
  7401. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7402. this.setTarget(cameraTarget.position);
  7403. };
  7404. FollowCamera.prototype._update = function () {
  7405. _super.prototype._update.call(this);
  7406. this.follow(this.target);
  7407. };
  7408. return FollowCamera;
  7409. })(BABYLON.TargetCamera);
  7410. BABYLON.FollowCamera = FollowCamera;
  7411. })(BABYLON || (BABYLON = {}));
  7412. //# sourceMappingURL=babylon.followCamera.js.map
  7413. var BABYLON;
  7414. (function (BABYLON) {
  7415. var FreeCamera = (function (_super) {
  7416. __extends(FreeCamera, _super);
  7417. function FreeCamera(name, position, scene) {
  7418. _super.call(this, name, position, scene);
  7419. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7420. this.keysUp = [38];
  7421. this.keysDown = [40];
  7422. this.keysLeft = [37];
  7423. this.keysRight = [39];
  7424. this.checkCollisions = false;
  7425. this.applyGravity = false;
  7426. this.angularSensibility = 2000.0;
  7427. this._keys = [];
  7428. this._collider = new BABYLON.Collider();
  7429. this._needMoveForGravity = true;
  7430. this._oldPosition = BABYLON.Vector3.Zero();
  7431. this._diffPosition = BABYLON.Vector3.Zero();
  7432. this._newPosition = BABYLON.Vector3.Zero();
  7433. }
  7434. // Controls
  7435. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7436. var _this = this;
  7437. var previousPosition;
  7438. var engine = this.getEngine();
  7439. if (this._attachedElement) {
  7440. return;
  7441. }
  7442. this._attachedElement = element;
  7443. if (this._onMouseDown === undefined) {
  7444. this._onMouseDown = function (evt) {
  7445. previousPosition = {
  7446. x: evt.clientX,
  7447. y: evt.clientY
  7448. };
  7449. if (!noPreventDefault) {
  7450. evt.preventDefault();
  7451. }
  7452. };
  7453. this._onMouseUp = function (evt) {
  7454. previousPosition = null;
  7455. if (!noPreventDefault) {
  7456. evt.preventDefault();
  7457. }
  7458. };
  7459. this._onMouseOut = function (evt) {
  7460. previousPosition = null;
  7461. _this._keys = [];
  7462. if (!noPreventDefault) {
  7463. evt.preventDefault();
  7464. }
  7465. };
  7466. this._onMouseMove = function (evt) {
  7467. if (!previousPosition && !engine.isPointerLock) {
  7468. return;
  7469. }
  7470. var offsetX;
  7471. var offsetY;
  7472. if (!engine.isPointerLock) {
  7473. offsetX = evt.clientX - previousPosition.x;
  7474. offsetY = evt.clientY - previousPosition.y;
  7475. }
  7476. else {
  7477. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7478. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7479. }
  7480. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7481. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7482. previousPosition = {
  7483. x: evt.clientX,
  7484. y: evt.clientY
  7485. };
  7486. if (!noPreventDefault) {
  7487. evt.preventDefault();
  7488. }
  7489. };
  7490. this._onKeyDown = function (evt) {
  7491. 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) {
  7492. var index = _this._keys.indexOf(evt.keyCode);
  7493. if (index === -1) {
  7494. _this._keys.push(evt.keyCode);
  7495. }
  7496. if (!noPreventDefault) {
  7497. evt.preventDefault();
  7498. }
  7499. }
  7500. };
  7501. this._onKeyUp = function (evt) {
  7502. 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) {
  7503. var index = _this._keys.indexOf(evt.keyCode);
  7504. if (index >= 0) {
  7505. _this._keys.splice(index, 1);
  7506. }
  7507. if (!noPreventDefault) {
  7508. evt.preventDefault();
  7509. }
  7510. }
  7511. };
  7512. this._onLostFocus = function () {
  7513. _this._keys = [];
  7514. };
  7515. this._reset = function () {
  7516. _this._keys = [];
  7517. previousPosition = null;
  7518. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7519. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7520. };
  7521. }
  7522. element.addEventListener("mousedown", this._onMouseDown, false);
  7523. element.addEventListener("mouseup", this._onMouseUp, false);
  7524. element.addEventListener("mouseout", this._onMouseOut, false);
  7525. element.addEventListener("mousemove", this._onMouseMove, false);
  7526. BABYLON.Tools.RegisterTopRootEvents([
  7527. { name: "keydown", handler: this._onKeyDown },
  7528. { name: "keyup", handler: this._onKeyUp },
  7529. { name: "blur", handler: this._onLostFocus }
  7530. ]);
  7531. };
  7532. FreeCamera.prototype.detachControl = function (element) {
  7533. if (this._attachedElement != element) {
  7534. return;
  7535. }
  7536. element.removeEventListener("mousedown", this._onMouseDown);
  7537. element.removeEventListener("mouseup", this._onMouseUp);
  7538. element.removeEventListener("mouseout", this._onMouseOut);
  7539. element.removeEventListener("mousemove", this._onMouseMove);
  7540. BABYLON.Tools.UnregisterTopRootEvents([
  7541. { name: "keydown", handler: this._onKeyDown },
  7542. { name: "keyup", handler: this._onKeyUp },
  7543. { name: "blur", handler: this._onLostFocus }
  7544. ]);
  7545. this._attachedElement = null;
  7546. if (this._reset) {
  7547. this._reset();
  7548. }
  7549. };
  7550. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7551. var globalPosition;
  7552. if (this.parent) {
  7553. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7554. }
  7555. else {
  7556. globalPosition = this.position;
  7557. }
  7558. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7559. this._collider.radius = this.ellipsoid;
  7560. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7561. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7562. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7563. this.position.addInPlace(this._diffPosition);
  7564. if (this.onCollide) {
  7565. this.onCollide(this._collider.collidedMesh);
  7566. }
  7567. }
  7568. };
  7569. FreeCamera.prototype._checkInputs = function () {
  7570. if (!this._localDirection) {
  7571. this._localDirection = BABYLON.Vector3.Zero();
  7572. this._transformedDirection = BABYLON.Vector3.Zero();
  7573. }
  7574. for (var index = 0; index < this._keys.length; index++) {
  7575. var keyCode = this._keys[index];
  7576. var speed = this._computeLocalCameraSpeed();
  7577. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7578. this._localDirection.copyFromFloats(-speed, 0, 0);
  7579. }
  7580. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7581. this._localDirection.copyFromFloats(0, 0, speed);
  7582. }
  7583. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7584. this._localDirection.copyFromFloats(speed, 0, 0);
  7585. }
  7586. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7587. this._localDirection.copyFromFloats(0, 0, -speed);
  7588. }
  7589. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7590. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7591. this.cameraDirection.addInPlace(this._transformedDirection);
  7592. }
  7593. };
  7594. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7595. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7596. };
  7597. FreeCamera.prototype._updatePosition = function () {
  7598. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7599. this._collideWithWorld(this.cameraDirection);
  7600. if (this.applyGravity) {
  7601. var oldPosition = this.position;
  7602. this._collideWithWorld(this.getScene().gravity);
  7603. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7604. }
  7605. }
  7606. else {
  7607. this.position.addInPlace(this.cameraDirection);
  7608. }
  7609. };
  7610. FreeCamera.prototype._update = function () {
  7611. this._checkInputs();
  7612. _super.prototype._update.call(this);
  7613. };
  7614. return FreeCamera;
  7615. })(BABYLON.TargetCamera);
  7616. BABYLON.FreeCamera = FreeCamera;
  7617. })(BABYLON || (BABYLON = {}));
  7618. //# sourceMappingURL=babylon.freeCamera.js.map
  7619. var BABYLON;
  7620. (function (BABYLON) {
  7621. // We're mainly based on the logic defined into the FreeCamera code
  7622. var TouchCamera = (function (_super) {
  7623. __extends(TouchCamera, _super);
  7624. function TouchCamera(name, position, scene) {
  7625. _super.call(this, name, position, scene);
  7626. this._offsetX = null;
  7627. this._offsetY = null;
  7628. this._pointerCount = 0;
  7629. this._pointerPressed = [];
  7630. this.angularSensibility = 200000.0;
  7631. this.moveSensibility = 500.0;
  7632. }
  7633. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7634. var _this = this;
  7635. var previousPosition;
  7636. if (this._attachedCanvas) {
  7637. return;
  7638. }
  7639. this._attachedCanvas = canvas;
  7640. if (this._onPointerDown === undefined) {
  7641. this._onPointerDown = function (evt) {
  7642. if (!noPreventDefault) {
  7643. evt.preventDefault();
  7644. }
  7645. _this._pointerPressed.push(evt.pointerId);
  7646. if (_this._pointerPressed.length !== 1) {
  7647. return;
  7648. }
  7649. previousPosition = {
  7650. x: evt.clientX,
  7651. y: evt.clientY
  7652. };
  7653. };
  7654. this._onPointerUp = function (evt) {
  7655. if (!noPreventDefault) {
  7656. evt.preventDefault();
  7657. }
  7658. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7659. if (index === -1) {
  7660. return;
  7661. }
  7662. _this._pointerPressed.splice(index, 1);
  7663. if (index != 0) {
  7664. return;
  7665. }
  7666. previousPosition = null;
  7667. _this._offsetX = null;
  7668. _this._offsetY = null;
  7669. };
  7670. this._onPointerMove = function (evt) {
  7671. if (!noPreventDefault) {
  7672. evt.preventDefault();
  7673. }
  7674. if (!previousPosition) {
  7675. return;
  7676. }
  7677. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7678. if (index != 0) {
  7679. return;
  7680. }
  7681. _this._offsetX = evt.clientX - previousPosition.x;
  7682. _this._offsetY = -(evt.clientY - previousPosition.y);
  7683. };
  7684. this._onLostFocus = function () {
  7685. _this._offsetX = null;
  7686. _this._offsetY = null;
  7687. };
  7688. }
  7689. canvas.addEventListener("pointerdown", this._onPointerDown);
  7690. canvas.addEventListener("pointerup", this._onPointerUp);
  7691. canvas.addEventListener("pointerout", this._onPointerUp);
  7692. canvas.addEventListener("pointermove", this._onPointerMove);
  7693. BABYLON.Tools.RegisterTopRootEvents([
  7694. { name: "blur", handler: this._onLostFocus }
  7695. ]);
  7696. };
  7697. TouchCamera.prototype.detachControl = function (canvas) {
  7698. if (this._attachedCanvas != canvas) {
  7699. return;
  7700. }
  7701. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7702. canvas.removeEventListener("pointerup", this._onPointerUp);
  7703. canvas.removeEventListener("pointerout", this._onPointerUp);
  7704. canvas.removeEventListener("pointermove", this._onPointerMove);
  7705. BABYLON.Tools.UnregisterTopRootEvents([
  7706. { name: "blur", handler: this._onLostFocus }
  7707. ]);
  7708. this._attachedCanvas = null;
  7709. };
  7710. TouchCamera.prototype._checkInputs = function () {
  7711. if (!this._offsetX) {
  7712. return;
  7713. }
  7714. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7715. if (this._pointerPressed.length > 1) {
  7716. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7717. }
  7718. else {
  7719. var speed = this._computeLocalCameraSpeed();
  7720. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7721. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7722. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7723. }
  7724. };
  7725. return TouchCamera;
  7726. })(BABYLON.FreeCamera);
  7727. BABYLON.TouchCamera = TouchCamera;
  7728. })(BABYLON || (BABYLON = {}));
  7729. //# sourceMappingURL=babylon.touchCamera.js.map
  7730. var BABYLON;
  7731. (function (BABYLON) {
  7732. // We're mainly based on the logic defined into the FreeCamera code
  7733. var DeviceOrientationCamera = (function (_super) {
  7734. __extends(DeviceOrientationCamera, _super);
  7735. function DeviceOrientationCamera(name, position, scene) {
  7736. var _this = this;
  7737. _super.call(this, name, position, scene);
  7738. this._offsetX = null;
  7739. this._offsetY = null;
  7740. this._orientationGamma = 0;
  7741. this._orientationBeta = 0;
  7742. this._initialOrientationGamma = 0;
  7743. this._initialOrientationBeta = 0;
  7744. this.angularSensibility = 10000.0;
  7745. this.moveSensibility = 50.0;
  7746. window.addEventListener("resize", function () {
  7747. _this._initialOrientationGamma = null;
  7748. }, false);
  7749. }
  7750. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7751. var _this = this;
  7752. if (this._attachedCanvas) {
  7753. return;
  7754. }
  7755. this._attachedCanvas = canvas;
  7756. if (!this._orientationChanged) {
  7757. this._orientationChanged = function (evt) {
  7758. if (!_this._initialOrientationGamma) {
  7759. _this._initialOrientationGamma = evt.gamma;
  7760. _this._initialOrientationBeta = evt.beta;
  7761. }
  7762. _this._orientationGamma = evt.gamma;
  7763. _this._orientationBeta = evt.beta;
  7764. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7765. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7766. };
  7767. }
  7768. window.addEventListener("deviceorientation", this._orientationChanged);
  7769. };
  7770. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7771. if (this._attachedCanvas != canvas) {
  7772. return;
  7773. }
  7774. window.removeEventListener("deviceorientation", this._orientationChanged);
  7775. this._attachedCanvas = null;
  7776. this._orientationGamma = 0;
  7777. this._orientationBeta = 0;
  7778. this._initialOrientationGamma = 0;
  7779. this._initialOrientationBeta = 0;
  7780. };
  7781. DeviceOrientationCamera.prototype._checkInputs = function () {
  7782. if (!this._offsetX) {
  7783. return;
  7784. }
  7785. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7786. var speed = this._computeLocalCameraSpeed();
  7787. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7788. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7789. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7790. };
  7791. return DeviceOrientationCamera;
  7792. })(BABYLON.FreeCamera);
  7793. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7794. })(BABYLON || (BABYLON = {}));
  7795. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7796. var BABYLON;
  7797. (function (BABYLON) {
  7798. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7799. var ArcRotateCamera = (function (_super) {
  7800. __extends(ArcRotateCamera, _super);
  7801. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7802. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7803. this.alpha = alpha;
  7804. this.beta = beta;
  7805. this.radius = radius;
  7806. this.target = target;
  7807. this.inertialAlphaOffset = 0;
  7808. this.inertialBetaOffset = 0;
  7809. this.inertialRadiusOffset = 0;
  7810. this.lowerAlphaLimit = null;
  7811. this.upperAlphaLimit = null;
  7812. this.lowerBetaLimit = 0.01;
  7813. this.upperBetaLimit = Math.PI;
  7814. this.lowerRadiusLimit = null;
  7815. this.upperRadiusLimit = null;
  7816. this.angularSensibility = 1000.0;
  7817. this.wheelPrecision = 3.0;
  7818. this.pinchPrecision = 2.0;
  7819. this.keysUp = [38];
  7820. this.keysDown = [40];
  7821. this.keysLeft = [37];
  7822. this.keysRight = [39];
  7823. this.zoomOnFactor = 1;
  7824. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7825. this._keys = [];
  7826. this._viewMatrix = new BABYLON.Matrix();
  7827. this.checkCollisions = false;
  7828. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7829. this._collider = new BABYLON.Collider();
  7830. this._previousPosition = BABYLON.Vector3.Zero();
  7831. this._collisionVelocity = BABYLON.Vector3.Zero();
  7832. this._newPosition = BABYLON.Vector3.Zero();
  7833. if (!this.target) {
  7834. this.target = BABYLON.Vector3.Zero();
  7835. }
  7836. this.getViewMatrix();
  7837. }
  7838. ArcRotateCamera.prototype._getTargetPosition = function () {
  7839. return this.target.position || this.target;
  7840. };
  7841. // Cache
  7842. ArcRotateCamera.prototype._initCache = function () {
  7843. _super.prototype._initCache.call(this);
  7844. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7845. this._cache.alpha = undefined;
  7846. this._cache.beta = undefined;
  7847. this._cache.radius = undefined;
  7848. this._cache.targetScreenOffset = undefined;
  7849. };
  7850. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7851. if (!ignoreParentClass) {
  7852. _super.prototype._updateCache.call(this);
  7853. }
  7854. this._cache.target.copyFrom(this._getTargetPosition());
  7855. this._cache.alpha = this.alpha;
  7856. this._cache.beta = this.beta;
  7857. this._cache.radius = this.radius;
  7858. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7859. };
  7860. // Synchronized
  7861. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7862. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7863. return false;
  7864. 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);
  7865. };
  7866. // Methods
  7867. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7868. var _this = this;
  7869. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7870. var previousPinchDistance = 0;
  7871. var pointers = new BABYLON.SmartCollection();
  7872. if (this._attachedElement) {
  7873. return;
  7874. }
  7875. this._attachedElement = element;
  7876. var engine = this.getEngine();
  7877. if (this._onPointerDown === undefined) {
  7878. this._onPointerDown = function (evt) {
  7879. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7880. cacheSoloPointer = pointers.item(evt.pointerId);
  7881. if (!noPreventDefault) {
  7882. evt.preventDefault();
  7883. }
  7884. };
  7885. this._onPointerUp = function (evt) {
  7886. cacheSoloPointer = null;
  7887. previousPinchDistance = 0;
  7888. pointers.remove(evt.pointerId);
  7889. if (!noPreventDefault) {
  7890. evt.preventDefault();
  7891. }
  7892. };
  7893. this._onPointerMove = function (evt) {
  7894. if (!noPreventDefault) {
  7895. evt.preventDefault();
  7896. }
  7897. switch (pointers.count) {
  7898. case 1:
  7899. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7900. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7901. var offsetX = evt.clientX - cacheSoloPointer.x;
  7902. var offsetY = evt.clientY - cacheSoloPointer.y;
  7903. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7904. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7905. //pointers.item(evt.pointerId).x = evt.clientX;
  7906. //pointers.item(evt.pointerId).y = evt.clientY;
  7907. cacheSoloPointer.x = evt.clientX;
  7908. cacheSoloPointer.y = evt.clientY;
  7909. break;
  7910. case 2:
  7911. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7912. pointers.item(evt.pointerId).x = evt.clientX;
  7913. pointers.item(evt.pointerId).y = evt.clientY;
  7914. var direction = 1;
  7915. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7916. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7917. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7918. if (previousPinchDistance === 0) {
  7919. previousPinchDistance = pinchSquaredDistance;
  7920. return;
  7921. }
  7922. if (pinchSquaredDistance !== previousPinchDistance) {
  7923. if (pinchSquaredDistance > previousPinchDistance) {
  7924. direction = -1;
  7925. }
  7926. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7927. previousPinchDistance = pinchSquaredDistance;
  7928. }
  7929. break;
  7930. default:
  7931. if (pointers.item(evt.pointerId)) {
  7932. pointers.item(evt.pointerId).x = evt.clientX;
  7933. pointers.item(evt.pointerId).y = evt.clientY;
  7934. }
  7935. }
  7936. };
  7937. this._onMouseMove = function (evt) {
  7938. if (!engine.isPointerLock) {
  7939. return;
  7940. }
  7941. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7942. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7943. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7944. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7945. if (!noPreventDefault) {
  7946. evt.preventDefault();
  7947. }
  7948. };
  7949. this._wheel = function (event) {
  7950. var delta = 0;
  7951. if (event.wheelDelta) {
  7952. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7953. }
  7954. else if (event.detail) {
  7955. delta = -event.detail / _this.wheelPrecision;
  7956. }
  7957. if (delta)
  7958. _this.inertialRadiusOffset += delta;
  7959. if (event.preventDefault) {
  7960. if (!noPreventDefault) {
  7961. event.preventDefault();
  7962. }
  7963. }
  7964. };
  7965. this._onKeyDown = function (evt) {
  7966. 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) {
  7967. var index = _this._keys.indexOf(evt.keyCode);
  7968. if (index === -1) {
  7969. _this._keys.push(evt.keyCode);
  7970. }
  7971. if (evt.preventDefault) {
  7972. if (!noPreventDefault) {
  7973. evt.preventDefault();
  7974. }
  7975. }
  7976. }
  7977. };
  7978. this._onKeyUp = function (evt) {
  7979. 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) {
  7980. var index = _this._keys.indexOf(evt.keyCode);
  7981. if (index >= 0) {
  7982. _this._keys.splice(index, 1);
  7983. }
  7984. if (evt.preventDefault) {
  7985. if (!noPreventDefault) {
  7986. evt.preventDefault();
  7987. }
  7988. }
  7989. }
  7990. };
  7991. this._onLostFocus = function () {
  7992. _this._keys = [];
  7993. pointers.empty();
  7994. previousPinchDistance = 0;
  7995. cacheSoloPointer = null;
  7996. };
  7997. this._onGestureStart = function (e) {
  7998. if (window.MSGesture === undefined) {
  7999. return;
  8000. }
  8001. if (!_this._MSGestureHandler) {
  8002. _this._MSGestureHandler = new MSGesture();
  8003. _this._MSGestureHandler.target = element;
  8004. }
  8005. _this._MSGestureHandler.addPointer(e.pointerId);
  8006. };
  8007. this._onGesture = function (e) {
  8008. _this.radius *= e.scale;
  8009. if (e.preventDefault) {
  8010. if (!noPreventDefault) {
  8011. e.stopPropagation();
  8012. e.preventDefault();
  8013. }
  8014. }
  8015. };
  8016. this._reset = function () {
  8017. _this._keys = [];
  8018. _this.inertialAlphaOffset = 0;
  8019. _this.inertialBetaOffset = 0;
  8020. _this.inertialRadiusOffset = 0;
  8021. pointers.empty();
  8022. previousPinchDistance = 0;
  8023. cacheSoloPointer = null;
  8024. };
  8025. }
  8026. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8027. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  8028. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  8029. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8030. element.addEventListener("mousemove", this._onMouseMove, false);
  8031. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  8032. element.addEventListener("MSGestureChange", this._onGesture, false);
  8033. element.addEventListener('mousewheel', this._wheel, false);
  8034. element.addEventListener('DOMMouseScroll', this._wheel, false);
  8035. BABYLON.Tools.RegisterTopRootEvents([
  8036. { name: "keydown", handler: this._onKeyDown },
  8037. { name: "keyup", handler: this._onKeyUp },
  8038. { name: "blur", handler: this._onLostFocus }
  8039. ]);
  8040. };
  8041. ArcRotateCamera.prototype.detachControl = function (element) {
  8042. if (this._attachedElement !== element) {
  8043. return;
  8044. }
  8045. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  8046. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  8047. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  8048. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  8049. element.removeEventListener("mousemove", this._onMouseMove);
  8050. element.removeEventListener("MSPointerDown", this._onGestureStart);
  8051. element.removeEventListener("MSGestureChange", this._onGesture);
  8052. element.removeEventListener('mousewheel', this._wheel);
  8053. element.removeEventListener('DOMMouseScroll', this._wheel);
  8054. BABYLON.Tools.UnregisterTopRootEvents([
  8055. { name: "keydown", handler: this._onKeyDown },
  8056. { name: "keyup", handler: this._onKeyUp },
  8057. { name: "blur", handler: this._onLostFocus }
  8058. ]);
  8059. this._MSGestureHandler = null;
  8060. this._attachedElement = null;
  8061. if (this._reset) {
  8062. this._reset();
  8063. }
  8064. };
  8065. ArcRotateCamera.prototype._update = function () {
  8066. for (var index = 0; index < this._keys.length; index++) {
  8067. var keyCode = this._keys[index];
  8068. if (this.keysLeft.indexOf(keyCode) !== -1) {
  8069. this.inertialAlphaOffset -= 0.01;
  8070. }
  8071. else if (this.keysUp.indexOf(keyCode) !== -1) {
  8072. this.inertialBetaOffset -= 0.01;
  8073. }
  8074. else if (this.keysRight.indexOf(keyCode) !== -1) {
  8075. this.inertialAlphaOffset += 0.01;
  8076. }
  8077. else if (this.keysDown.indexOf(keyCode) !== -1) {
  8078. this.inertialBetaOffset += 0.01;
  8079. }
  8080. }
  8081. // Inertia
  8082. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  8083. this.alpha += this.inertialAlphaOffset;
  8084. this.beta += this.inertialBetaOffset;
  8085. this.radius -= this.inertialRadiusOffset;
  8086. this.inertialAlphaOffset *= this.inertia;
  8087. this.inertialBetaOffset *= this.inertia;
  8088. this.inertialRadiusOffset *= this.inertia;
  8089. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  8090. this.inertialAlphaOffset = 0;
  8091. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  8092. this.inertialBetaOffset = 0;
  8093. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  8094. this.inertialRadiusOffset = 0;
  8095. }
  8096. // Limits
  8097. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  8098. this.alpha = this.lowerAlphaLimit;
  8099. }
  8100. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  8101. this.alpha = this.upperAlphaLimit;
  8102. }
  8103. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  8104. this.beta = this.lowerBetaLimit;
  8105. }
  8106. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  8107. this.beta = this.upperBetaLimit;
  8108. }
  8109. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  8110. this.radius = this.lowerRadiusLimit;
  8111. }
  8112. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  8113. this.radius = this.upperRadiusLimit;
  8114. }
  8115. };
  8116. ArcRotateCamera.prototype.setPosition = function (position) {
  8117. var radiusv3 = position.subtract(this._getTargetPosition());
  8118. this.radius = radiusv3.length();
  8119. // Alpha
  8120. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  8121. if (radiusv3.z < 0) {
  8122. this.alpha = 2 * Math.PI - this.alpha;
  8123. }
  8124. // Beta
  8125. this.beta = Math.acos(radiusv3.y / this.radius);
  8126. };
  8127. ArcRotateCamera.prototype._getViewMatrix = function () {
  8128. // Compute
  8129. var cosa = Math.cos(this.alpha);
  8130. var sina = Math.sin(this.alpha);
  8131. var cosb = Math.cos(this.beta);
  8132. var sinb = Math.sin(this.beta);
  8133. var target = this._getTargetPosition();
  8134. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8135. if (this.checkCollisions) {
  8136. this._collider.radius = this.collisionRadius;
  8137. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8138. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8139. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8140. this.position.copyFrom(this._previousPosition);
  8141. this.alpha = this._previousAlpha;
  8142. this.beta = this._previousBeta;
  8143. this.radius = this._previousRadius;
  8144. if (this.onCollide) {
  8145. this.onCollide(this._collider.collidedMesh);
  8146. }
  8147. }
  8148. }
  8149. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8150. this._previousAlpha = this.alpha;
  8151. this._previousBeta = this.beta;
  8152. this._previousRadius = this.radius;
  8153. this._previousPosition.copyFrom(this.position);
  8154. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8155. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8156. return this._viewMatrix;
  8157. };
  8158. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8159. meshes = meshes || this.getScene().meshes;
  8160. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8161. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8162. this.radius = distance * this.zoomOnFactor;
  8163. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8164. };
  8165. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8166. var meshesOrMinMaxVector;
  8167. var distance;
  8168. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8169. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8170. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8171. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8172. }
  8173. else {
  8174. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8175. distance = meshesOrMinMaxVectorAndDistance.distance;
  8176. }
  8177. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8178. this.maxZ = distance * 2;
  8179. };
  8180. return ArcRotateCamera;
  8181. })(BABYLON.Camera);
  8182. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8183. })(BABYLON || (BABYLON = {}));
  8184. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8185. (function (BABYLON) {
  8186. /**
  8187. * Represents a scene to be rendered by the engine.
  8188. * @see http://doc.babylonjs.com/page.php?p=21911
  8189. */
  8190. var Scene = (function () {
  8191. /**
  8192. * @constructor
  8193. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8194. */
  8195. function Scene(engine) {
  8196. // Members
  8197. this.autoClear = true;
  8198. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8199. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8200. this.forceWireframe = false;
  8201. this.forcePointsCloud = false;
  8202. this.forceShowBoundingBoxes = false;
  8203. this.animationsEnabled = true;
  8204. 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
  8205. // Fog
  8206. /**
  8207. * is fog enabled on this scene.
  8208. * @type {boolean}
  8209. */
  8210. this.fogEnabled = true;
  8211. this.fogMode = Scene.FOGMODE_NONE;
  8212. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8213. this.fogDensity = 0.1;
  8214. this.fogStart = 0;
  8215. this.fogEnd = 1000.0;
  8216. // Lights
  8217. /**
  8218. * is shadow enabled on this scene.
  8219. * @type {boolean}
  8220. */
  8221. this.shadowsEnabled = true;
  8222. /**
  8223. * is light enabled on this scene.
  8224. * @type {boolean}
  8225. */
  8226. this.lightsEnabled = true;
  8227. /**
  8228. * All of the lights added to this scene.
  8229. * @see BABYLON.Light
  8230. * @type {BABYLON.Light[]}
  8231. */
  8232. this.lights = new Array();
  8233. // Cameras
  8234. /**
  8235. * All of the cameras added to this scene.
  8236. * @see BABYLON.Camera
  8237. * @type {BABYLON.Camera[]}
  8238. */
  8239. this.cameras = new Array();
  8240. this.activeCameras = new Array();
  8241. // Meshes
  8242. /**
  8243. * All of the (abstract) meshes added to this scene.
  8244. * @see BABYLON.AbstractMesh
  8245. * @type {BABYLON.AbstractMesh[]}
  8246. */
  8247. this.meshes = new Array();
  8248. // Geometries
  8249. this._geometries = new Array();
  8250. this.materials = new Array();
  8251. this.multiMaterials = new Array();
  8252. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8253. // Textures
  8254. this.texturesEnabled = true;
  8255. this.textures = new Array();
  8256. // Particles
  8257. this.particlesEnabled = true;
  8258. this.particleSystems = new Array();
  8259. // Sprites
  8260. this.spritesEnabled = true;
  8261. this.spriteManagers = new Array();
  8262. // Layers
  8263. this.layers = new Array();
  8264. // Skeletons
  8265. this.skeletonsEnabled = true;
  8266. this.skeletons = new Array();
  8267. // Lens flares
  8268. this.lensFlaresEnabled = true;
  8269. this.lensFlareSystems = new Array();
  8270. // Collisions
  8271. this.collisionsEnabled = true;
  8272. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8273. // Postprocesses
  8274. this.postProcessesEnabled = true;
  8275. // Customs render targets
  8276. this.renderTargetsEnabled = true;
  8277. this.dumpNextRenderTargets = false;
  8278. this.customRenderTargets = new Array();
  8279. // Imported meshes
  8280. this.importedMeshesFiles = new Array();
  8281. this._actionManagers = new Array();
  8282. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8283. // Procedural textures
  8284. this.proceduralTexturesEnabled = true;
  8285. this._proceduralTextures = new Array();
  8286. this.soundTracks = new Array();
  8287. this._audioEnabled = true;
  8288. this._headphone = false;
  8289. this._totalVertices = 0;
  8290. this._activeVertices = 0;
  8291. this._activeParticles = 0;
  8292. this._lastFrameDuration = 0;
  8293. this._evaluateActiveMeshesDuration = 0;
  8294. this._renderTargetsDuration = 0;
  8295. this._particlesDuration = 0;
  8296. this._renderDuration = 0;
  8297. this._spritesDuration = 0;
  8298. this._animationRatio = 0;
  8299. this._renderId = 0;
  8300. this._executeWhenReadyTimeoutId = -1;
  8301. this._toBeDisposed = new BABYLON.SmartArray(256);
  8302. this._onReadyCallbacks = new Array();
  8303. this._pendingData = []; //ANY
  8304. this._onBeforeRenderCallbacks = new Array();
  8305. this._onAfterRenderCallbacks = new Array();
  8306. this._activeMeshes = new BABYLON.SmartArray(256);
  8307. this._processedMaterials = new BABYLON.SmartArray(256);
  8308. this._renderTargets = new BABYLON.SmartArray(256);
  8309. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8310. this._activeSkeletons = new BABYLON.SmartArray(32);
  8311. this._activeBones = 0;
  8312. this._activeAnimatables = new Array();
  8313. this._transformMatrix = BABYLON.Matrix.Zero();
  8314. this._scaledPosition = BABYLON.Vector3.Zero();
  8315. this._scaledVelocity = BABYLON.Vector3.Zero();
  8316. this._uniqueIdCounter = 0;
  8317. this._engine = engine;
  8318. engine.scenes.push(this);
  8319. this._renderingManager = new BABYLON.RenderingManager(this);
  8320. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8321. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8322. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8323. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8324. this.attachControl();
  8325. this._debugLayer = new BABYLON.DebugLayer(this);
  8326. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8327. //simplification queue
  8328. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8329. }
  8330. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8331. get: function () {
  8332. return Scene._FOGMODE_NONE;
  8333. },
  8334. enumerable: true,
  8335. configurable: true
  8336. });
  8337. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8338. get: function () {
  8339. return Scene._FOGMODE_EXP;
  8340. },
  8341. enumerable: true,
  8342. configurable: true
  8343. });
  8344. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8345. get: function () {
  8346. return Scene._FOGMODE_EXP2;
  8347. },
  8348. enumerable: true,
  8349. configurable: true
  8350. });
  8351. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8352. get: function () {
  8353. return Scene._FOGMODE_LINEAR;
  8354. },
  8355. enumerable: true,
  8356. configurable: true
  8357. });
  8358. Object.defineProperty(Scene.prototype, "debugLayer", {
  8359. // Properties
  8360. get: function () {
  8361. return this._debugLayer;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8367. /**
  8368. * The mesh that is currently under the pointer.
  8369. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8370. */
  8371. get: function () {
  8372. return this._meshUnderPointer;
  8373. },
  8374. enumerable: true,
  8375. configurable: true
  8376. });
  8377. Object.defineProperty(Scene.prototype, "pointerX", {
  8378. /**
  8379. * Current on-screen X position of the pointer
  8380. * @return {number} X position of the pointer
  8381. */
  8382. get: function () {
  8383. return this._pointerX;
  8384. },
  8385. enumerable: true,
  8386. configurable: true
  8387. });
  8388. Object.defineProperty(Scene.prototype, "pointerY", {
  8389. /**
  8390. * Current on-screen Y position of the pointer
  8391. * @return {number} Y position of the pointer
  8392. */
  8393. get: function () {
  8394. return this._pointerY;
  8395. },
  8396. enumerable: true,
  8397. configurable: true
  8398. });
  8399. Scene.prototype.getCachedMaterial = function () {
  8400. return this._cachedMaterial;
  8401. };
  8402. Scene.prototype.getBoundingBoxRenderer = function () {
  8403. return this._boundingBoxRenderer;
  8404. };
  8405. Scene.prototype.getOutlineRenderer = function () {
  8406. return this._outlineRenderer;
  8407. };
  8408. Scene.prototype.getEngine = function () {
  8409. return this._engine;
  8410. };
  8411. Scene.prototype.getTotalVertices = function () {
  8412. return this._totalVertices;
  8413. };
  8414. Scene.prototype.getActiveVertices = function () {
  8415. return this._activeVertices;
  8416. };
  8417. Scene.prototype.getActiveParticles = function () {
  8418. return this._activeParticles;
  8419. };
  8420. Scene.prototype.getActiveBones = function () {
  8421. return this._activeBones;
  8422. };
  8423. // Stats
  8424. Scene.prototype.getLastFrameDuration = function () {
  8425. return this._lastFrameDuration;
  8426. };
  8427. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8428. return this._evaluateActiveMeshesDuration;
  8429. };
  8430. Scene.prototype.getActiveMeshes = function () {
  8431. return this._activeMeshes;
  8432. };
  8433. Scene.prototype.getRenderTargetsDuration = function () {
  8434. return this._renderTargetsDuration;
  8435. };
  8436. Scene.prototype.getRenderDuration = function () {
  8437. return this._renderDuration;
  8438. };
  8439. Scene.prototype.getParticlesDuration = function () {
  8440. return this._particlesDuration;
  8441. };
  8442. Scene.prototype.getSpritesDuration = function () {
  8443. return this._spritesDuration;
  8444. };
  8445. Scene.prototype.getAnimationRatio = function () {
  8446. return this._animationRatio;
  8447. };
  8448. Scene.prototype.getRenderId = function () {
  8449. return this._renderId;
  8450. };
  8451. Scene.prototype.incrementRenderId = function () {
  8452. this._renderId++;
  8453. };
  8454. Scene.prototype._updatePointerPosition = function (evt) {
  8455. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8456. this._pointerX = evt.clientX - canvasRect.left;
  8457. this._pointerY = evt.clientY - canvasRect.top;
  8458. if (this.cameraToUseForPointers) {
  8459. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8460. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8461. }
  8462. };
  8463. // Pointers handling
  8464. Scene.prototype.attachControl = function () {
  8465. var _this = this;
  8466. this._onPointerMove = function (evt) {
  8467. var canvas = _this._engine.getRenderingCanvas();
  8468. _this._updatePointerPosition(evt);
  8469. 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);
  8470. if (pickResult.hit) {
  8471. _this._meshUnderPointer = pickResult.pickedMesh;
  8472. _this.setPointerOverMesh(pickResult.pickedMesh);
  8473. canvas.style.cursor = "pointer";
  8474. }
  8475. else {
  8476. _this.setPointerOverMesh(null);
  8477. canvas.style.cursor = "";
  8478. _this._meshUnderPointer = null;
  8479. }
  8480. };
  8481. this._onPointerDown = function (evt) {
  8482. var predicate = null;
  8483. if (!_this.onPointerDown) {
  8484. predicate = function (mesh) {
  8485. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8486. };
  8487. }
  8488. _this._updatePointerPosition(evt);
  8489. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8490. if (pickResult.hit) {
  8491. if (pickResult.pickedMesh.actionManager) {
  8492. switch (evt.button) {
  8493. case 0:
  8494. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8495. break;
  8496. case 1:
  8497. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8498. break;
  8499. case 2:
  8500. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8501. break;
  8502. }
  8503. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8504. }
  8505. }
  8506. if (_this.onPointerDown) {
  8507. _this.onPointerDown(evt, pickResult);
  8508. }
  8509. };
  8510. this._onKeyDown = function (evt) {
  8511. if (_this.actionManager) {
  8512. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8513. }
  8514. };
  8515. this._onKeyUp = function (evt) {
  8516. if (_this.actionManager) {
  8517. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8518. }
  8519. };
  8520. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8521. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8522. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8523. BABYLON.Tools.RegisterTopRootEvents([
  8524. { name: "keydown", handler: this._onKeyDown },
  8525. { name: "keyup", handler: this._onKeyUp }
  8526. ]);
  8527. };
  8528. Scene.prototype.detachControl = function () {
  8529. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8530. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8531. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8532. BABYLON.Tools.UnregisterTopRootEvents([
  8533. { name: "keydown", handler: this._onKeyDown },
  8534. { name: "keyup", handler: this._onKeyUp }
  8535. ]);
  8536. };
  8537. // Ready
  8538. Scene.prototype.isReady = function () {
  8539. if (this._pendingData.length > 0) {
  8540. return false;
  8541. }
  8542. for (var index = 0; index < this._geometries.length; index++) {
  8543. var geometry = this._geometries[index];
  8544. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8545. return false;
  8546. }
  8547. }
  8548. for (index = 0; index < this.meshes.length; index++) {
  8549. var mesh = this.meshes[index];
  8550. if (!mesh.isReady()) {
  8551. return false;
  8552. }
  8553. var mat = mesh.material;
  8554. if (mat) {
  8555. if (!mat.isReady(mesh)) {
  8556. return false;
  8557. }
  8558. }
  8559. }
  8560. return true;
  8561. };
  8562. Scene.prototype.resetCachedMaterial = function () {
  8563. this._cachedMaterial = null;
  8564. };
  8565. Scene.prototype.registerBeforeRender = function (func) {
  8566. this._onBeforeRenderCallbacks.push(func);
  8567. };
  8568. Scene.prototype.unregisterBeforeRender = function (func) {
  8569. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8570. if (index > -1) {
  8571. this._onBeforeRenderCallbacks.splice(index, 1);
  8572. }
  8573. };
  8574. Scene.prototype.registerAfterRender = function (func) {
  8575. this._onAfterRenderCallbacks.push(func);
  8576. };
  8577. Scene.prototype.unregisterAfterRender = function (func) {
  8578. var index = this._onAfterRenderCallbacks.indexOf(func);
  8579. if (index > -1) {
  8580. this._onAfterRenderCallbacks.splice(index, 1);
  8581. }
  8582. };
  8583. Scene.prototype._addPendingData = function (data) {
  8584. this._pendingData.push(data);
  8585. };
  8586. Scene.prototype._removePendingData = function (data) {
  8587. var index = this._pendingData.indexOf(data);
  8588. if (index !== -1) {
  8589. this._pendingData.splice(index, 1);
  8590. }
  8591. };
  8592. Scene.prototype.getWaitingItemsCount = function () {
  8593. return this._pendingData.length;
  8594. };
  8595. /**
  8596. * Registers a function to be executed when the scene is ready.
  8597. * @param {Function} func - the function to be executed.
  8598. */
  8599. Scene.prototype.executeWhenReady = function (func) {
  8600. var _this = this;
  8601. this._onReadyCallbacks.push(func);
  8602. if (this._executeWhenReadyTimeoutId !== -1) {
  8603. return;
  8604. }
  8605. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8606. _this._checkIsReady();
  8607. }, 150);
  8608. };
  8609. Scene.prototype._checkIsReady = function () {
  8610. var _this = this;
  8611. if (this.isReady()) {
  8612. this._onReadyCallbacks.forEach(function (func) {
  8613. func();
  8614. });
  8615. this._onReadyCallbacks = [];
  8616. this._executeWhenReadyTimeoutId = -1;
  8617. return;
  8618. }
  8619. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8620. _this._checkIsReady();
  8621. }, 150);
  8622. };
  8623. // Animations
  8624. /**
  8625. * Will start the animation sequence of a given target
  8626. * @param target - the target
  8627. * @param {number} from - from which frame should animation start
  8628. * @param {number} to - till which frame should animation run.
  8629. * @param {boolean} [loop] - should the animation loop
  8630. * @param {number} [speedRatio] - the speed in which to run the animation
  8631. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8632. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8633. * @return {BABYLON.Animatable} the animatable object created for this animation
  8634. * @see BABYLON.Animatable
  8635. * @see http://doc.babylonjs.com/page.php?p=22081
  8636. */
  8637. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8638. if (speedRatio === undefined) {
  8639. speedRatio = 1.0;
  8640. }
  8641. this.stopAnimation(target);
  8642. if (!animatable) {
  8643. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8644. }
  8645. // Local animations
  8646. if (target.animations) {
  8647. animatable.appendAnimations(target, target.animations);
  8648. }
  8649. // Children animations
  8650. if (target.getAnimatables) {
  8651. var animatables = target.getAnimatables();
  8652. for (var index = 0; index < animatables.length; index++) {
  8653. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8654. }
  8655. }
  8656. return animatable;
  8657. };
  8658. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8659. if (speedRatio === undefined) {
  8660. speedRatio = 1.0;
  8661. }
  8662. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8663. return animatable;
  8664. };
  8665. Scene.prototype.getAnimatableByTarget = function (target) {
  8666. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8667. if (this._activeAnimatables[index].target === target) {
  8668. return this._activeAnimatables[index];
  8669. }
  8670. }
  8671. return null;
  8672. };
  8673. /**
  8674. * Will stop the animation of the given target
  8675. * @param target - the target
  8676. * @see beginAnimation
  8677. */
  8678. Scene.prototype.stopAnimation = function (target) {
  8679. var animatable = this.getAnimatableByTarget(target);
  8680. if (animatable) {
  8681. animatable.stop();
  8682. }
  8683. };
  8684. Scene.prototype._animate = function () {
  8685. if (!this.animationsEnabled) {
  8686. return;
  8687. }
  8688. if (!this._animationStartDate) {
  8689. this._animationStartDate = BABYLON.Tools.Now;
  8690. }
  8691. // Getting time
  8692. var now = BABYLON.Tools.Now;
  8693. var delay = now - this._animationStartDate;
  8694. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8695. this._activeAnimatables[index]._animate(delay);
  8696. }
  8697. };
  8698. // Matrix
  8699. Scene.prototype.getViewMatrix = function () {
  8700. return this._viewMatrix;
  8701. };
  8702. Scene.prototype.getProjectionMatrix = function () {
  8703. return this._projectionMatrix;
  8704. };
  8705. Scene.prototype.getTransformMatrix = function () {
  8706. return this._transformMatrix;
  8707. };
  8708. Scene.prototype.setTransformMatrix = function (view, projection) {
  8709. this._viewMatrix = view;
  8710. this._projectionMatrix = projection;
  8711. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8712. };
  8713. // Methods
  8714. Scene.prototype.addMesh = function (newMesh) {
  8715. newMesh.uniqueId = this._uniqueIdCounter++;
  8716. var position = this.meshes.push(newMesh);
  8717. if (this.onNewMeshAdded) {
  8718. this.onNewMeshAdded(newMesh, position, this);
  8719. }
  8720. };
  8721. Scene.prototype.removeMesh = function (toRemove) {
  8722. var index = this.meshes.indexOf(toRemove);
  8723. if (index !== -1) {
  8724. // Remove from the scene if mesh found
  8725. this.meshes.splice(index, 1);
  8726. }
  8727. if (this.onMeshRemoved) {
  8728. this.onMeshRemoved(toRemove);
  8729. }
  8730. return index;
  8731. };
  8732. Scene.prototype.removeLight = function (toRemove) {
  8733. var index = this.lights.indexOf(toRemove);
  8734. if (index !== -1) {
  8735. // Remove from the scene if mesh found
  8736. this.lights.splice(index, 1);
  8737. }
  8738. if (this.onLightRemoved) {
  8739. this.onLightRemoved(toRemove);
  8740. }
  8741. return index;
  8742. };
  8743. Scene.prototype.removeCamera = function (toRemove) {
  8744. var index = this.cameras.indexOf(toRemove);
  8745. if (index !== -1) {
  8746. // Remove from the scene if mesh found
  8747. this.cameras.splice(index, 1);
  8748. }
  8749. if (this.onCameraRemoved) {
  8750. this.onCameraRemoved(toRemove);
  8751. }
  8752. return index;
  8753. };
  8754. Scene.prototype.addLight = function (newLight) {
  8755. newLight.uniqueId = this._uniqueIdCounter++;
  8756. var position = this.lights.push(newLight);
  8757. if (this.onNewLightAdded) {
  8758. this.onNewLightAdded(newLight, position, this);
  8759. }
  8760. };
  8761. Scene.prototype.addCamera = function (newCamera) {
  8762. newCamera.uniqueId = this._uniqueIdCounter++;
  8763. var position = this.cameras.push(newCamera);
  8764. if (this.onNewCameraAdded) {
  8765. this.onNewCameraAdded(newCamera, position, this);
  8766. }
  8767. };
  8768. /**
  8769. * sets the active camera of the scene using its ID
  8770. * @param {string} id - the camera's ID
  8771. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8772. * @see activeCamera
  8773. */
  8774. Scene.prototype.setActiveCameraByID = function (id) {
  8775. var camera = this.getCameraByID(id);
  8776. if (camera) {
  8777. this.activeCamera = camera;
  8778. return camera;
  8779. }
  8780. return null;
  8781. };
  8782. /**
  8783. * sets the active camera of the scene using its name
  8784. * @param {string} name - the camera's name
  8785. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8786. * @see activeCamera
  8787. */
  8788. Scene.prototype.setActiveCameraByName = function (name) {
  8789. var camera = this.getCameraByName(name);
  8790. if (camera) {
  8791. this.activeCamera = camera;
  8792. return camera;
  8793. }
  8794. return null;
  8795. };
  8796. /**
  8797. * get a material using its id
  8798. * @param {string} the material's ID
  8799. * @return {BABYLON.Material|null} the material or null if none found.
  8800. */
  8801. Scene.prototype.getMaterialByID = function (id) {
  8802. for (var index = 0; index < this.materials.length; index++) {
  8803. if (this.materials[index].id === id) {
  8804. return this.materials[index];
  8805. }
  8806. }
  8807. return null;
  8808. };
  8809. /**
  8810. * get a material using its name
  8811. * @param {string} the material's name
  8812. * @return {BABYLON.Material|null} the material or null if none found.
  8813. */
  8814. Scene.prototype.getMaterialByName = function (name) {
  8815. for (var index = 0; index < this.materials.length; index++) {
  8816. if (this.materials[index].name === name) {
  8817. return this.materials[index];
  8818. }
  8819. }
  8820. return null;
  8821. };
  8822. Scene.prototype.getCameraByID = function (id) {
  8823. for (var index = 0; index < this.cameras.length; index++) {
  8824. if (this.cameras[index].id === id) {
  8825. return this.cameras[index];
  8826. }
  8827. }
  8828. return null;
  8829. };
  8830. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  8831. for (var index = 0; index < this.cameras.length; index++) {
  8832. if (this.cameras[index].uniqueId === uniqueId) {
  8833. return this.cameras[index];
  8834. }
  8835. }
  8836. return null;
  8837. };
  8838. /**
  8839. * get a camera using its name
  8840. * @param {string} the camera's name
  8841. * @return {BABYLON.Camera|null} the camera or null if none found.
  8842. */
  8843. Scene.prototype.getCameraByName = function (name) {
  8844. for (var index = 0; index < this.cameras.length; index++) {
  8845. if (this.cameras[index].name === name) {
  8846. return this.cameras[index];
  8847. }
  8848. }
  8849. return null;
  8850. };
  8851. /**
  8852. * get a light node using its name
  8853. * @param {string} the light's name
  8854. * @return {BABYLON.Light|null} the light or null if none found.
  8855. */
  8856. Scene.prototype.getLightByName = function (name) {
  8857. for (var index = 0; index < this.lights.length; index++) {
  8858. if (this.lights[index].name === name) {
  8859. return this.lights[index];
  8860. }
  8861. }
  8862. return null;
  8863. };
  8864. /**
  8865. * get a light node using its ID
  8866. * @param {string} the light's id
  8867. * @return {BABYLON.Light|null} the light or null if none found.
  8868. */
  8869. Scene.prototype.getLightByID = function (id) {
  8870. for (var index = 0; index < this.lights.length; index++) {
  8871. if (this.lights[index].id === id) {
  8872. return this.lights[index];
  8873. }
  8874. }
  8875. return null;
  8876. };
  8877. /**
  8878. * get a light node using its scene-generated unique ID
  8879. * @param {number} the light's unique id
  8880. * @return {BABYLON.Light|null} the light or null if none found.
  8881. */
  8882. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  8883. for (var index = 0; index < this.lights.length; index++) {
  8884. if (this.lights[index].uniqueId === uniqueId) {
  8885. return this.lights[index];
  8886. }
  8887. }
  8888. return null;
  8889. };
  8890. /**
  8891. * get a geometry using its ID
  8892. * @param {string} the geometry's id
  8893. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8894. */
  8895. Scene.prototype.getGeometryByID = function (id) {
  8896. for (var index = 0; index < this._geometries.length; index++) {
  8897. if (this._geometries[index].id === id) {
  8898. return this._geometries[index];
  8899. }
  8900. }
  8901. return null;
  8902. };
  8903. /**
  8904. * add a new geometry to this scene.
  8905. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8906. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8907. * @return {boolean} was the geometry added or not
  8908. */
  8909. Scene.prototype.pushGeometry = function (geometry, force) {
  8910. if (!force && this.getGeometryByID(geometry.id)) {
  8911. return false;
  8912. }
  8913. this._geometries.push(geometry);
  8914. if (this.onGeometryAdded) {
  8915. this.onGeometryAdded(geometry);
  8916. }
  8917. return true;
  8918. };
  8919. /**
  8920. * Removes an existing geometry
  8921. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  8922. * @return {boolean} was the geometry removed or not
  8923. */
  8924. Scene.prototype.removeGeometry = function (geometry) {
  8925. var index = this._geometries.indexOf(geometry);
  8926. if (index > -1) {
  8927. this._geometries.splice(index, 1);
  8928. if (this.onGeometryRemoved) {
  8929. this.onGeometryRemoved(geometry);
  8930. }
  8931. return true;
  8932. }
  8933. return false;
  8934. };
  8935. Scene.prototype.getGeometries = function () {
  8936. return this._geometries;
  8937. };
  8938. /**
  8939. * Get the first added mesh found of a given ID
  8940. * @param {string} id - the id to search for
  8941. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8942. */
  8943. Scene.prototype.getMeshByID = function (id) {
  8944. for (var index = 0; index < this.meshes.length; index++) {
  8945. if (this.meshes[index].id === id) {
  8946. return this.meshes[index];
  8947. }
  8948. }
  8949. return null;
  8950. };
  8951. /**
  8952. * Get a mesh with its auto-generated unique id
  8953. * @param {number} uniqueId - the unique id to search for
  8954. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8955. */
  8956. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  8957. for (var index = 0; index < this.meshes.length; index++) {
  8958. if (this.meshes[index].uniqueId === uniqueId) {
  8959. return this.meshes[index];
  8960. }
  8961. }
  8962. return null;
  8963. };
  8964. /**
  8965. * Get a the last added mesh found of a given ID
  8966. * @param {string} id - the id to search for
  8967. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8968. */
  8969. Scene.prototype.getLastMeshByID = function (id) {
  8970. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8971. if (this.meshes[index].id === id) {
  8972. return this.meshes[index];
  8973. }
  8974. }
  8975. return null;
  8976. };
  8977. /**
  8978. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8979. * @param {string} id - the id to search for
  8980. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8981. */
  8982. Scene.prototype.getLastEntryByID = function (id) {
  8983. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8984. if (this.meshes[index].id === id) {
  8985. return this.meshes[index];
  8986. }
  8987. }
  8988. for (index = this.cameras.length - 1; index >= 0; index--) {
  8989. if (this.cameras[index].id === id) {
  8990. return this.cameras[index];
  8991. }
  8992. }
  8993. for (index = this.lights.length - 1; index >= 0; index--) {
  8994. if (this.lights[index].id === id) {
  8995. return this.lights[index];
  8996. }
  8997. }
  8998. return null;
  8999. };
  9000. Scene.prototype.getNodeByName = function (name) {
  9001. var mesh = this.getMeshByName(name);
  9002. if (mesh) {
  9003. return mesh;
  9004. }
  9005. var light = this.getLightByName(name);
  9006. if (light) {
  9007. return light;
  9008. }
  9009. return this.getCameraByName(name);
  9010. };
  9011. Scene.prototype.getMeshByName = function (name) {
  9012. for (var index = 0; index < this.meshes.length; index++) {
  9013. if (this.meshes[index].name === name) {
  9014. return this.meshes[index];
  9015. }
  9016. }
  9017. return null;
  9018. };
  9019. Scene.prototype.getSoundByName = function (name) {
  9020. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  9021. if (this.mainSoundTrack.soundCollection[index].name === name) {
  9022. return this.mainSoundTrack.soundCollection[index];
  9023. }
  9024. }
  9025. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  9026. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  9027. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  9028. return this.soundTracks[sdIndex].soundCollection[index];
  9029. }
  9030. }
  9031. }
  9032. return null;
  9033. };
  9034. Scene.prototype.getLastSkeletonByID = function (id) {
  9035. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  9036. if (this.skeletons[index].id === id) {
  9037. return this.skeletons[index];
  9038. }
  9039. }
  9040. return null;
  9041. };
  9042. Scene.prototype.getSkeletonById = function (id) {
  9043. for (var index = 0; index < this.skeletons.length; index++) {
  9044. if (this.skeletons[index].id === id) {
  9045. return this.skeletons[index];
  9046. }
  9047. }
  9048. return null;
  9049. };
  9050. Scene.prototype.getSkeletonByName = function (name) {
  9051. for (var index = 0; index < this.skeletons.length; index++) {
  9052. if (this.skeletons[index].name === name) {
  9053. return this.skeletons[index];
  9054. }
  9055. }
  9056. return null;
  9057. };
  9058. Scene.prototype.isActiveMesh = function (mesh) {
  9059. return (this._activeMeshes.indexOf(mesh) !== -1);
  9060. };
  9061. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  9062. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  9063. var material = subMesh.getMaterial();
  9064. if (mesh.showSubMeshesBoundingBox) {
  9065. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  9066. }
  9067. if (material) {
  9068. // Render targets
  9069. if (material.getRenderTargetTextures) {
  9070. if (this._processedMaterials.indexOf(material) === -1) {
  9071. this._processedMaterials.push(material);
  9072. this._renderTargets.concat(material.getRenderTargetTextures());
  9073. }
  9074. }
  9075. // Dispatch
  9076. this._activeVertices += subMesh.indexCount;
  9077. this._renderingManager.dispatch(subMesh);
  9078. }
  9079. }
  9080. };
  9081. Scene.prototype._evaluateActiveMeshes = function () {
  9082. this.activeCamera._activeMeshes.reset();
  9083. this._activeMeshes.reset();
  9084. this._renderingManager.reset();
  9085. this._processedMaterials.reset();
  9086. this._activeParticleSystems.reset();
  9087. this._activeSkeletons.reset();
  9088. this._boundingBoxRenderer.reset();
  9089. if (!this._frustumPlanes) {
  9090. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  9091. }
  9092. else {
  9093. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  9094. }
  9095. // Meshes
  9096. var meshes;
  9097. var len;
  9098. if (this._selectionOctree) {
  9099. var selection = this._selectionOctree.select(this._frustumPlanes);
  9100. meshes = selection.data;
  9101. len = selection.length;
  9102. }
  9103. else {
  9104. len = this.meshes.length;
  9105. meshes = this.meshes;
  9106. }
  9107. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  9108. var mesh = meshes[meshIndex];
  9109. if (mesh.isBlocked) {
  9110. continue;
  9111. }
  9112. this._totalVertices += mesh.getTotalVertices();
  9113. if (!mesh.isReady()) {
  9114. continue;
  9115. }
  9116. mesh.computeWorldMatrix();
  9117. // Intersections
  9118. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  9119. this._meshesForIntersections.pushNoDuplicate(mesh);
  9120. }
  9121. // Switch to current LOD
  9122. var meshLOD = mesh.getLOD(this.activeCamera);
  9123. if (!meshLOD) {
  9124. continue;
  9125. }
  9126. mesh._preActivate();
  9127. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  9128. this._activeMeshes.push(mesh);
  9129. this.activeCamera._activeMeshes.push(mesh);
  9130. mesh._activate(this._renderId);
  9131. this._activeMesh(meshLOD);
  9132. }
  9133. }
  9134. // Particle systems
  9135. var beforeParticlesDate = BABYLON.Tools.Now;
  9136. if (this.particlesEnabled) {
  9137. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  9138. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  9139. var particleSystem = this.particleSystems[particleIndex];
  9140. if (!particleSystem.isStarted()) {
  9141. continue;
  9142. }
  9143. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  9144. this._activeParticleSystems.push(particleSystem);
  9145. particleSystem.animate();
  9146. }
  9147. }
  9148. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  9149. }
  9150. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9151. };
  9152. Scene.prototype._activeMesh = function (mesh) {
  9153. if (mesh.skeleton && this.skeletonsEnabled) {
  9154. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  9155. }
  9156. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  9157. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  9158. }
  9159. if (mesh && mesh.subMeshes) {
  9160. // Submeshes Octrees
  9161. var len;
  9162. var subMeshes;
  9163. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  9164. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  9165. len = intersections.length;
  9166. subMeshes = intersections.data;
  9167. }
  9168. else {
  9169. subMeshes = mesh.subMeshes;
  9170. len = subMeshes.length;
  9171. }
  9172. for (var subIndex = 0; subIndex < len; subIndex++) {
  9173. var subMesh = subMeshes[subIndex];
  9174. this._evaluateSubMesh(subMesh, mesh);
  9175. }
  9176. }
  9177. };
  9178. Scene.prototype.updateTransformMatrix = function (force) {
  9179. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  9180. };
  9181. Scene.prototype._renderForCamera = function (camera) {
  9182. var engine = this._engine;
  9183. this.activeCamera = camera;
  9184. if (!this.activeCamera)
  9185. throw new Error("Active camera not set");
  9186. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9187. // Viewport
  9188. engine.setViewport(this.activeCamera.viewport);
  9189. // Camera
  9190. this._renderId++;
  9191. this.updateTransformMatrix();
  9192. if (this.beforeCameraRender) {
  9193. this.beforeCameraRender(this.activeCamera);
  9194. }
  9195. // Meshes
  9196. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9197. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9198. this._evaluateActiveMeshes();
  9199. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9200. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9201. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9202. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9203. skeleton.prepare();
  9204. }
  9205. // Render targets
  9206. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9207. if (this.renderTargetsEnabled) {
  9208. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9209. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9210. var renderTarget = this._renderTargets.data[renderIndex];
  9211. if (renderTarget._shouldRender()) {
  9212. this._renderId++;
  9213. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9214. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9215. }
  9216. }
  9217. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9218. this._renderId++;
  9219. }
  9220. if (this._renderTargets.length > 0) {
  9221. engine.restoreDefaultFramebuffer();
  9222. }
  9223. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9224. // Prepare Frame
  9225. this.postProcessManager._prepareFrame();
  9226. var beforeRenderDate = BABYLON.Tools.Now;
  9227. // Backgrounds
  9228. if (this.layers.length) {
  9229. engine.setDepthBuffer(false);
  9230. var layerIndex;
  9231. var layer;
  9232. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9233. layer = this.layers[layerIndex];
  9234. if (layer.isBackground) {
  9235. layer.render();
  9236. }
  9237. }
  9238. engine.setDepthBuffer(true);
  9239. }
  9240. // Render
  9241. BABYLON.Tools.StartPerformanceCounter("Main render");
  9242. this._renderingManager.render(null, null, true, true);
  9243. BABYLON.Tools.EndPerformanceCounter("Main render");
  9244. // Bounding boxes
  9245. this._boundingBoxRenderer.render();
  9246. // Lens flares
  9247. if (this.lensFlaresEnabled) {
  9248. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9249. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9250. this.lensFlareSystems[lensFlareSystemIndex].render();
  9251. }
  9252. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9253. }
  9254. // Foregrounds
  9255. if (this.layers.length) {
  9256. engine.setDepthBuffer(false);
  9257. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9258. layer = this.layers[layerIndex];
  9259. if (!layer.isBackground) {
  9260. layer.render();
  9261. }
  9262. }
  9263. engine.setDepthBuffer(true);
  9264. }
  9265. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9266. // Finalize frame
  9267. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9268. // Update camera
  9269. this.activeCamera._updateFromScene();
  9270. // Reset some special arrays
  9271. this._renderTargets.reset();
  9272. if (this.afterCameraRender) {
  9273. this.afterCameraRender(this.activeCamera);
  9274. }
  9275. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9276. };
  9277. Scene.prototype._processSubCameras = function (camera) {
  9278. if (camera.subCameras.length === 0) {
  9279. this._renderForCamera(camera);
  9280. return;
  9281. }
  9282. for (var index = 0; index < camera.subCameras.length; index++) {
  9283. this._renderForCamera(camera.subCameras[index]);
  9284. }
  9285. this.activeCamera = camera;
  9286. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9287. // Update camera
  9288. this.activeCamera._updateFromScene();
  9289. };
  9290. Scene.prototype._checkIntersections = function () {
  9291. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9292. var sourceMesh = this._meshesForIntersections.data[index];
  9293. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9294. var action = sourceMesh.actionManager.actions[actionIndex];
  9295. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9296. var parameters = action.getTriggerParameter();
  9297. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9298. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9299. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9300. if (areIntersecting && currentIntersectionInProgress === -1) {
  9301. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9302. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9303. sourceMesh._intersectionsInProgress.push(otherMesh);
  9304. }
  9305. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9306. sourceMesh._intersectionsInProgress.push(otherMesh);
  9307. }
  9308. }
  9309. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9310. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9311. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9312. if (indexOfOther > -1) {
  9313. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9314. }
  9315. }
  9316. }
  9317. }
  9318. }
  9319. };
  9320. Scene.prototype.render = function () {
  9321. var startDate = BABYLON.Tools.Now;
  9322. this._particlesDuration = 0;
  9323. this._spritesDuration = 0;
  9324. this._activeParticles = 0;
  9325. this._renderDuration = 0;
  9326. this._renderTargetsDuration = 0;
  9327. this._evaluateActiveMeshesDuration = 0;
  9328. this._totalVertices = 0;
  9329. this._activeVertices = 0;
  9330. this._activeBones = 0;
  9331. this.getEngine().resetDrawCalls();
  9332. this._meshesForIntersections.reset();
  9333. this.resetCachedMaterial();
  9334. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9335. // Actions
  9336. if (this.actionManager) {
  9337. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9338. }
  9339. //Simplification Queue
  9340. if (!this.simplificationQueue.running) {
  9341. this.simplificationQueue.executeNext();
  9342. }
  9343. // Before render
  9344. if (this.beforeRender) {
  9345. this.beforeRender();
  9346. }
  9347. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9348. this._onBeforeRenderCallbacks[callbackIndex]();
  9349. }
  9350. // Animations
  9351. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9352. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9353. this._animate();
  9354. // Physics
  9355. if (this._physicsEngine) {
  9356. BABYLON.Tools.StartPerformanceCounter("Physics");
  9357. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9358. BABYLON.Tools.EndPerformanceCounter("Physics");
  9359. }
  9360. // Customs render targets
  9361. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9362. var engine = this.getEngine();
  9363. var currentActiveCamera = this.activeCamera;
  9364. if (this.renderTargetsEnabled) {
  9365. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9366. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9367. var renderTarget = this.customRenderTargets[customIndex];
  9368. if (renderTarget._shouldRender()) {
  9369. this._renderId++;
  9370. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9371. if (!this.activeCamera)
  9372. throw new Error("Active camera not set");
  9373. // Viewport
  9374. engine.setViewport(this.activeCamera.viewport);
  9375. // Camera
  9376. this.updateTransformMatrix();
  9377. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9378. }
  9379. }
  9380. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9381. this._renderId++;
  9382. }
  9383. if (this.customRenderTargets.length > 0) {
  9384. engine.restoreDefaultFramebuffer();
  9385. }
  9386. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9387. this.activeCamera = currentActiveCamera;
  9388. // Procedural textures
  9389. if (this.proceduralTexturesEnabled) {
  9390. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9391. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9392. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9393. if (proceduralTexture._shouldRender()) {
  9394. proceduralTexture.render();
  9395. }
  9396. }
  9397. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9398. }
  9399. // Clear
  9400. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9401. // Shadows
  9402. if (this.shadowsEnabled) {
  9403. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9404. var light = this.lights[lightIndex];
  9405. var shadowGenerator = light.getShadowGenerator();
  9406. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9407. this._renderTargets.push(shadowGenerator.getShadowMap());
  9408. }
  9409. }
  9410. }
  9411. // Depth renderer
  9412. if (this._depthRenderer) {
  9413. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9414. }
  9415. // RenderPipeline
  9416. this.postProcessRenderPipelineManager.update();
  9417. // Multi-cameras?
  9418. if (this.activeCameras.length > 0) {
  9419. var currentRenderId = this._renderId;
  9420. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9421. this._renderId = currentRenderId;
  9422. this._processSubCameras(this.activeCameras[cameraIndex]);
  9423. }
  9424. }
  9425. else {
  9426. if (!this.activeCamera) {
  9427. throw new Error("No camera defined");
  9428. }
  9429. this._processSubCameras(this.activeCamera);
  9430. }
  9431. // Intersection checks
  9432. this._checkIntersections();
  9433. // Update the audio listener attached to the camera
  9434. this._updateAudioParameters();
  9435. // After render
  9436. if (this.afterRender) {
  9437. this.afterRender();
  9438. }
  9439. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9440. this._onAfterRenderCallbacks[callbackIndex]();
  9441. }
  9442. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9443. this._toBeDisposed.data[index].dispose();
  9444. this._toBeDisposed[index] = null;
  9445. }
  9446. this._toBeDisposed.reset();
  9447. if (this.dumpNextRenderTargets) {
  9448. this.dumpNextRenderTargets = false;
  9449. }
  9450. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9451. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9452. };
  9453. Scene.prototype._updateAudioParameters = function () {
  9454. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9455. return;
  9456. }
  9457. var listeningCamera;
  9458. var audioEngine = BABYLON.Engine.audioEngine;
  9459. if (this.activeCameras.length > 0) {
  9460. listeningCamera = this.activeCameras[0];
  9461. }
  9462. else {
  9463. listeningCamera = this.activeCamera;
  9464. }
  9465. if (listeningCamera && audioEngine.canUseWebAudio) {
  9466. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9467. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9468. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9469. cameraDirection.normalize();
  9470. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9471. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9472. var sound = this.mainSoundTrack.soundCollection[i];
  9473. if (sound.useCustomAttenuation) {
  9474. sound.updateDistanceFromListener();
  9475. }
  9476. }
  9477. for (i = 0; i < this.soundTracks.length; i++) {
  9478. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9479. sound = this.soundTracks[i].soundCollection[j];
  9480. if (sound.useCustomAttenuation) {
  9481. sound.updateDistanceFromListener();
  9482. }
  9483. }
  9484. }
  9485. }
  9486. };
  9487. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9488. // Audio
  9489. get: function () {
  9490. return this._audioEnabled;
  9491. },
  9492. set: function (value) {
  9493. this._audioEnabled = value;
  9494. if (this._audioEnabled) {
  9495. this._enableAudio();
  9496. }
  9497. else {
  9498. this._disableAudio();
  9499. }
  9500. },
  9501. enumerable: true,
  9502. configurable: true
  9503. });
  9504. Scene.prototype._disableAudio = function () {
  9505. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9506. this.mainSoundTrack.soundCollection[i].pause();
  9507. }
  9508. for (i = 0; i < this.soundTracks.length; i++) {
  9509. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9510. this.soundTracks[i].soundCollection[j].pause();
  9511. }
  9512. }
  9513. };
  9514. Scene.prototype._enableAudio = function () {
  9515. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9516. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9517. this.mainSoundTrack.soundCollection[i].play();
  9518. }
  9519. }
  9520. for (i = 0; i < this.soundTracks.length; i++) {
  9521. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9522. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9523. this.soundTracks[i].soundCollection[j].play();
  9524. }
  9525. }
  9526. }
  9527. };
  9528. Object.defineProperty(Scene.prototype, "headphone", {
  9529. get: function () {
  9530. return this._headphone;
  9531. },
  9532. set: function (value) {
  9533. this._headphone = value;
  9534. if (this._headphone) {
  9535. this._switchAudioModeForHeadphones();
  9536. }
  9537. else {
  9538. this._switchAudioModeForNormalSpeakers();
  9539. }
  9540. },
  9541. enumerable: true,
  9542. configurable: true
  9543. });
  9544. Scene.prototype._switchAudioModeForHeadphones = function () {
  9545. this.mainSoundTrack.switchPanningModelToHRTF();
  9546. for (var i = 0; i < this.soundTracks.length; i++) {
  9547. this.soundTracks[i].switchPanningModelToHRTF();
  9548. }
  9549. };
  9550. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9551. this.mainSoundTrack.switchPanningModelToEqualPower();
  9552. for (var i = 0; i < this.soundTracks.length; i++) {
  9553. this.soundTracks[i].switchPanningModelToEqualPower();
  9554. }
  9555. };
  9556. Scene.prototype.enableDepthRenderer = function () {
  9557. if (this._depthRenderer) {
  9558. return this._depthRenderer;
  9559. }
  9560. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9561. return this._depthRenderer;
  9562. };
  9563. Scene.prototype.disableDepthRenderer = function () {
  9564. if (!this._depthRenderer) {
  9565. return;
  9566. }
  9567. this._depthRenderer.dispose();
  9568. this._depthRenderer = null;
  9569. };
  9570. Scene.prototype.dispose = function () {
  9571. this.beforeRender = null;
  9572. this.afterRender = null;
  9573. this.skeletons = [];
  9574. this._boundingBoxRenderer.dispose();
  9575. if (this._depthRenderer) {
  9576. this._depthRenderer.dispose();
  9577. }
  9578. // Debug layer
  9579. this.debugLayer.hide();
  9580. // Events
  9581. if (this.onDispose) {
  9582. this.onDispose();
  9583. }
  9584. this._onBeforeRenderCallbacks = [];
  9585. this._onAfterRenderCallbacks = [];
  9586. this.detachControl();
  9587. // Release sounds & sounds tracks
  9588. this.disposeSounds();
  9589. // Detach cameras
  9590. var canvas = this._engine.getRenderingCanvas();
  9591. var index;
  9592. for (index = 0; index < this.cameras.length; index++) {
  9593. this.cameras[index].detachControl(canvas);
  9594. }
  9595. while (this.lights.length) {
  9596. this.lights[0].dispose();
  9597. }
  9598. while (this.meshes.length) {
  9599. this.meshes[0].dispose(true);
  9600. }
  9601. while (this.cameras.length) {
  9602. this.cameras[0].dispose();
  9603. }
  9604. while (this.materials.length) {
  9605. this.materials[0].dispose();
  9606. }
  9607. while (this.particleSystems.length) {
  9608. this.particleSystems[0].dispose();
  9609. }
  9610. while (this.spriteManagers.length) {
  9611. this.spriteManagers[0].dispose();
  9612. }
  9613. while (this.layers.length) {
  9614. this.layers[0].dispose();
  9615. }
  9616. while (this.textures.length) {
  9617. this.textures[0].dispose();
  9618. }
  9619. // Post-processes
  9620. this.postProcessManager.dispose();
  9621. // Physics
  9622. if (this._physicsEngine) {
  9623. this.disablePhysicsEngine();
  9624. }
  9625. // Remove from engine
  9626. index = this._engine.scenes.indexOf(this);
  9627. if (index > -1) {
  9628. this._engine.scenes.splice(index, 1);
  9629. }
  9630. this._engine.wipeCaches();
  9631. };
  9632. // Release sounds & sounds tracks
  9633. Scene.prototype.disposeSounds = function () {
  9634. this.mainSoundTrack.dispose();
  9635. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9636. this.soundTracks[scIndex].dispose();
  9637. }
  9638. };
  9639. // Collisions
  9640. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9641. if (excludedMesh === void 0) { excludedMesh = null; }
  9642. position.divideToRef(collider.radius, this._scaledPosition);
  9643. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9644. collider.retry = 0;
  9645. collider.initialVelocity = this._scaledVelocity;
  9646. collider.initialPosition = this._scaledPosition;
  9647. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9648. finalPosition.multiplyInPlace(collider.radius);
  9649. };
  9650. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9651. if (excludedMesh === void 0) { excludedMesh = null; }
  9652. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9653. if (collider.retry >= maximumRetry) {
  9654. finalPosition.copyFrom(position);
  9655. return;
  9656. }
  9657. collider._initialize(position, velocity, closeDistance);
  9658. for (var index = 0; index < this.meshes.length; index++) {
  9659. var mesh = this.meshes[index];
  9660. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9661. mesh._checkCollision(collider);
  9662. }
  9663. }
  9664. if (!collider.collisionFound) {
  9665. position.addToRef(velocity, finalPosition);
  9666. return;
  9667. }
  9668. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9669. collider._getResponse(position, velocity);
  9670. }
  9671. if (velocity.length() <= closeDistance) {
  9672. finalPosition.copyFrom(position);
  9673. return;
  9674. }
  9675. collider.retry++;
  9676. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9677. };
  9678. // Octrees
  9679. Scene.prototype.getWorldExtends = function () {
  9680. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9681. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9682. for (var index = 0; index < this.meshes.length; index++) {
  9683. var mesh = this.meshes[index];
  9684. mesh.computeWorldMatrix(true);
  9685. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9686. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9687. BABYLON.Tools.CheckExtends(minBox, min, max);
  9688. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9689. }
  9690. return {
  9691. min: min,
  9692. max: max
  9693. };
  9694. };
  9695. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9696. if (maxCapacity === void 0) { maxCapacity = 64; }
  9697. if (maxDepth === void 0) { maxDepth = 2; }
  9698. if (!this._selectionOctree) {
  9699. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9700. }
  9701. var worldExtends = this.getWorldExtends();
  9702. // Update octree
  9703. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9704. return this._selectionOctree;
  9705. };
  9706. // Picking
  9707. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9708. var engine = this._engine;
  9709. if (!camera) {
  9710. if (!this.activeCamera)
  9711. throw new Error("Active camera not set");
  9712. camera = this.activeCamera;
  9713. }
  9714. var cameraViewport = camera.viewport;
  9715. var viewport = cameraViewport.toGlobal(engine);
  9716. // Moving coordinates to local viewport world
  9717. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9718. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9719. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9720. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9721. };
  9722. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9723. var pickingInfo = null;
  9724. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9725. var mesh = this.meshes[meshIndex];
  9726. if (predicate) {
  9727. if (!predicate(mesh)) {
  9728. continue;
  9729. }
  9730. }
  9731. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9732. continue;
  9733. }
  9734. var world = mesh.getWorldMatrix();
  9735. var ray = rayFunction(world);
  9736. var result = mesh.intersects(ray, fastCheck);
  9737. if (!result || !result.hit)
  9738. continue;
  9739. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9740. continue;
  9741. pickingInfo = result;
  9742. if (fastCheck) {
  9743. break;
  9744. }
  9745. }
  9746. return pickingInfo || new BABYLON.PickingInfo();
  9747. };
  9748. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9749. var _this = this;
  9750. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9751. /// <param name="x">X position on screen</param>
  9752. /// <param name="y">Y position on screen</param>
  9753. /// <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>
  9754. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9755. /// <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>
  9756. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9757. };
  9758. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9759. var _this = this;
  9760. return this._internalPick(function (world) {
  9761. if (!_this._pickWithRayInverseMatrix) {
  9762. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9763. }
  9764. world.invertToRef(_this._pickWithRayInverseMatrix);
  9765. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9766. }, predicate, fastCheck);
  9767. };
  9768. Scene.prototype.setPointerOverMesh = function (mesh) {
  9769. if (this._pointerOverMesh === mesh) {
  9770. return;
  9771. }
  9772. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9773. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9774. }
  9775. this._pointerOverMesh = mesh;
  9776. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9777. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9778. }
  9779. };
  9780. Scene.prototype.getPointerOverMesh = function () {
  9781. return this._pointerOverMesh;
  9782. };
  9783. // Physics
  9784. Scene.prototype.getPhysicsEngine = function () {
  9785. return this._physicsEngine;
  9786. };
  9787. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9788. if (this._physicsEngine) {
  9789. return true;
  9790. }
  9791. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9792. if (!this._physicsEngine.isSupported()) {
  9793. this._physicsEngine = null;
  9794. return false;
  9795. }
  9796. this._physicsEngine._initialize(gravity);
  9797. return true;
  9798. };
  9799. Scene.prototype.disablePhysicsEngine = function () {
  9800. if (!this._physicsEngine) {
  9801. return;
  9802. }
  9803. this._physicsEngine.dispose();
  9804. this._physicsEngine = undefined;
  9805. };
  9806. Scene.prototype.isPhysicsEnabled = function () {
  9807. return this._physicsEngine !== undefined;
  9808. };
  9809. Scene.prototype.setGravity = function (gravity) {
  9810. if (!this._physicsEngine) {
  9811. return;
  9812. }
  9813. this._physicsEngine._setGravity(gravity);
  9814. };
  9815. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9816. if (parts.parts) {
  9817. options = parts;
  9818. parts = parts.parts;
  9819. }
  9820. if (!this._physicsEngine) {
  9821. return null;
  9822. }
  9823. for (var index = 0; index < parts.length; index++) {
  9824. var mesh = parts[index].mesh;
  9825. mesh._physicImpostor = parts[index].impostor;
  9826. mesh._physicsMass = options.mass / parts.length;
  9827. mesh._physicsFriction = options.friction;
  9828. mesh._physicRestitution = options.restitution;
  9829. }
  9830. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9831. };
  9832. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9833. for (var index = 0; index < compound.parts.length; index++) {
  9834. var mesh = compound.parts[index].mesh;
  9835. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9836. this._physicsEngine._unregisterMesh(mesh);
  9837. }
  9838. };
  9839. // Misc.
  9840. Scene.prototype.createDefaultCameraOrLight = function () {
  9841. // Light
  9842. if (this.lights.length === 0) {
  9843. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9844. }
  9845. // Camera
  9846. if (!this.activeCamera) {
  9847. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9848. // Compute position
  9849. var worldExtends = this.getWorldExtends();
  9850. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9851. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9852. camera.setTarget(worldCenter);
  9853. this.activeCamera = camera;
  9854. }
  9855. };
  9856. // Tags
  9857. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9858. if (tagsQuery === undefined) {
  9859. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9860. return list;
  9861. }
  9862. var listByTags = [];
  9863. forEach = forEach || (function (item) {
  9864. return;
  9865. });
  9866. for (var i in list) {
  9867. var item = list[i];
  9868. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9869. listByTags.push(item);
  9870. forEach(item);
  9871. }
  9872. }
  9873. return listByTags;
  9874. };
  9875. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9876. return this._getByTags(this.meshes, tagsQuery, forEach);
  9877. };
  9878. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9879. return this._getByTags(this.cameras, tagsQuery, forEach);
  9880. };
  9881. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9882. return this._getByTags(this.lights, tagsQuery, forEach);
  9883. };
  9884. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9885. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9886. };
  9887. // Statics
  9888. Scene._FOGMODE_NONE = 0;
  9889. Scene._FOGMODE_EXP = 1;
  9890. Scene._FOGMODE_EXP2 = 2;
  9891. Scene._FOGMODE_LINEAR = 3;
  9892. Scene.MinDeltaTime = 1.0;
  9893. Scene.MaxDeltaTime = 1000.0;
  9894. return Scene;
  9895. })();
  9896. BABYLON.Scene = Scene;
  9897. })(BABYLON || (BABYLON = {}));
  9898. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9899. (function (BABYLON) {
  9900. var VertexBuffer = (function () {
  9901. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9902. if (engine instanceof BABYLON.Mesh) {
  9903. this._engine = engine.getScene().getEngine();
  9904. }
  9905. else {
  9906. this._engine = engine;
  9907. }
  9908. this._updatable = updatable;
  9909. this._data = data;
  9910. if (!postponeInternalCreation) {
  9911. this.create();
  9912. }
  9913. this._kind = kind;
  9914. if (stride) {
  9915. this._strideSize = stride;
  9916. return;
  9917. }
  9918. switch (kind) {
  9919. case VertexBuffer.PositionKind:
  9920. this._strideSize = 3;
  9921. break;
  9922. case VertexBuffer.NormalKind:
  9923. this._strideSize = 3;
  9924. break;
  9925. case VertexBuffer.UVKind:
  9926. this._strideSize = 2;
  9927. break;
  9928. case VertexBuffer.UV2Kind:
  9929. this._strideSize = 2;
  9930. break;
  9931. case VertexBuffer.ColorKind:
  9932. this._strideSize = 4;
  9933. break;
  9934. case VertexBuffer.MatricesIndicesKind:
  9935. this._strideSize = 4;
  9936. break;
  9937. case VertexBuffer.MatricesWeightsKind:
  9938. this._strideSize = 4;
  9939. break;
  9940. }
  9941. }
  9942. // Properties
  9943. VertexBuffer.prototype.isUpdatable = function () {
  9944. return this._updatable;
  9945. };
  9946. VertexBuffer.prototype.getData = function () {
  9947. return this._data;
  9948. };
  9949. VertexBuffer.prototype.getBuffer = function () {
  9950. return this._buffer;
  9951. };
  9952. VertexBuffer.prototype.getStrideSize = function () {
  9953. return this._strideSize;
  9954. };
  9955. // Methods
  9956. VertexBuffer.prototype.create = function (data) {
  9957. if (!data && this._buffer) {
  9958. return; // nothing to do
  9959. }
  9960. data = data || this._data;
  9961. if (!this._buffer) {
  9962. if (this._updatable) {
  9963. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9964. }
  9965. else {
  9966. this._buffer = this._engine.createVertexBuffer(data);
  9967. }
  9968. }
  9969. if (this._updatable) {
  9970. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9971. this._data = data;
  9972. }
  9973. };
  9974. VertexBuffer.prototype.update = function (data) {
  9975. this.create(data);
  9976. };
  9977. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9978. if (!this._buffer) {
  9979. return;
  9980. }
  9981. if (this._updatable) {
  9982. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9983. this._data = null;
  9984. }
  9985. };
  9986. VertexBuffer.prototype.dispose = function () {
  9987. if (!this._buffer) {
  9988. return;
  9989. }
  9990. if (this._engine._releaseBuffer(this._buffer)) {
  9991. this._buffer = null;
  9992. }
  9993. };
  9994. Object.defineProperty(VertexBuffer, "PositionKind", {
  9995. get: function () {
  9996. return VertexBuffer._PositionKind;
  9997. },
  9998. enumerable: true,
  9999. configurable: true
  10000. });
  10001. Object.defineProperty(VertexBuffer, "NormalKind", {
  10002. get: function () {
  10003. return VertexBuffer._NormalKind;
  10004. },
  10005. enumerable: true,
  10006. configurable: true
  10007. });
  10008. Object.defineProperty(VertexBuffer, "UVKind", {
  10009. get: function () {
  10010. return VertexBuffer._UVKind;
  10011. },
  10012. enumerable: true,
  10013. configurable: true
  10014. });
  10015. Object.defineProperty(VertexBuffer, "UV2Kind", {
  10016. get: function () {
  10017. return VertexBuffer._UV2Kind;
  10018. },
  10019. enumerable: true,
  10020. configurable: true
  10021. });
  10022. Object.defineProperty(VertexBuffer, "ColorKind", {
  10023. get: function () {
  10024. return VertexBuffer._ColorKind;
  10025. },
  10026. enumerable: true,
  10027. configurable: true
  10028. });
  10029. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  10030. get: function () {
  10031. return VertexBuffer._MatricesIndicesKind;
  10032. },
  10033. enumerable: true,
  10034. configurable: true
  10035. });
  10036. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  10037. get: function () {
  10038. return VertexBuffer._MatricesWeightsKind;
  10039. },
  10040. enumerable: true,
  10041. configurable: true
  10042. });
  10043. // Enums
  10044. VertexBuffer._PositionKind = "position";
  10045. VertexBuffer._NormalKind = "normal";
  10046. VertexBuffer._UVKind = "uv";
  10047. VertexBuffer._UV2Kind = "uv2";
  10048. VertexBuffer._ColorKind = "color";
  10049. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  10050. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  10051. return VertexBuffer;
  10052. })();
  10053. BABYLON.VertexBuffer = VertexBuffer;
  10054. })(BABYLON || (BABYLON = {}));
  10055. //# sourceMappingURL=babylon.vertexBuffer.js.map
  10056. var BABYLON;
  10057. (function (BABYLON) {
  10058. var AbstractMesh = (function (_super) {
  10059. __extends(AbstractMesh, _super);
  10060. function AbstractMesh(name, scene) {
  10061. _super.call(this, name, scene);
  10062. // Properties
  10063. this.definedFacingForward = true; // orientation for POV movement & rotation
  10064. this.position = new BABYLON.Vector3(0, 0, 0);
  10065. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10066. this.scaling = new BABYLON.Vector3(1, 1, 1);
  10067. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10068. this.visibility = 1.0;
  10069. this.alphaIndex = Number.MAX_VALUE;
  10070. this.infiniteDistance = false;
  10071. this.isVisible = true;
  10072. this.isPickable = true;
  10073. this.showBoundingBox = false;
  10074. this.showSubMeshesBoundingBox = false;
  10075. this.onDispose = null;
  10076. this.checkCollisions = false;
  10077. this.isBlocker = false;
  10078. this.renderingGroupId = 0;
  10079. this.receiveShadows = false;
  10080. this.renderOutline = false;
  10081. this.outlineColor = BABYLON.Color3.Red();
  10082. this.outlineWidth = 0.02;
  10083. this.renderOverlay = false;
  10084. this.overlayColor = BABYLON.Color3.Red();
  10085. this.overlayAlpha = 0.5;
  10086. this.hasVertexAlpha = false;
  10087. this.useVertexColors = true;
  10088. this.applyFog = true;
  10089. this.useOctreeForRenderingSelection = true;
  10090. this.useOctreeForPicking = true;
  10091. this.useOctreeForCollisions = true;
  10092. this.layerMask = 0x0FFFFFFF;
  10093. // Physics
  10094. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  10095. // Collisions
  10096. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10097. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10098. this._collider = new BABYLON.Collider();
  10099. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10100. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10101. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10102. // Cache
  10103. this._localScaling = BABYLON.Matrix.Zero();
  10104. this._localRotation = BABYLON.Matrix.Zero();
  10105. this._localTranslation = BABYLON.Matrix.Zero();
  10106. this._localBillboard = BABYLON.Matrix.Zero();
  10107. this._localPivotScaling = BABYLON.Matrix.Zero();
  10108. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  10109. this._localWorld = BABYLON.Matrix.Zero();
  10110. this._worldMatrix = BABYLON.Matrix.Zero();
  10111. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10112. this._absolutePosition = BABYLON.Vector3.Zero();
  10113. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10114. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10115. this._isDirty = false;
  10116. this._pivotMatrix = BABYLON.Matrix.Identity();
  10117. this._isDisposed = false;
  10118. this._renderId = 0;
  10119. this._intersectionsInProgress = new Array();
  10120. this._onAfterWorldMatrixUpdate = new Array();
  10121. scene.addMesh(this);
  10122. }
  10123. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10124. get: function () {
  10125. return AbstractMesh._BILLBOARDMODE_NONE;
  10126. },
  10127. enumerable: true,
  10128. configurable: true
  10129. });
  10130. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10131. get: function () {
  10132. return AbstractMesh._BILLBOARDMODE_X;
  10133. },
  10134. enumerable: true,
  10135. configurable: true
  10136. });
  10137. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10138. get: function () {
  10139. return AbstractMesh._BILLBOARDMODE_Y;
  10140. },
  10141. enumerable: true,
  10142. configurable: true
  10143. });
  10144. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10145. get: function () {
  10146. return AbstractMesh._BILLBOARDMODE_Z;
  10147. },
  10148. enumerable: true,
  10149. configurable: true
  10150. });
  10151. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10152. get: function () {
  10153. return AbstractMesh._BILLBOARDMODE_ALL;
  10154. },
  10155. enumerable: true,
  10156. configurable: true
  10157. });
  10158. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10159. // Methods
  10160. get: function () {
  10161. return false;
  10162. },
  10163. enumerable: true,
  10164. configurable: true
  10165. });
  10166. AbstractMesh.prototype.getLOD = function (camera) {
  10167. return this;
  10168. };
  10169. AbstractMesh.prototype.getTotalVertices = function () {
  10170. return 0;
  10171. };
  10172. AbstractMesh.prototype.getIndices = function () {
  10173. return null;
  10174. };
  10175. AbstractMesh.prototype.getVerticesData = function (kind) {
  10176. return null;
  10177. };
  10178. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10179. return false;
  10180. };
  10181. AbstractMesh.prototype.getBoundingInfo = function () {
  10182. if (this._masterMesh) {
  10183. return this._masterMesh.getBoundingInfo();
  10184. }
  10185. if (!this._boundingInfo) {
  10186. this._updateBoundingInfo();
  10187. }
  10188. return this._boundingInfo;
  10189. };
  10190. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10191. get: function () {
  10192. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10193. },
  10194. enumerable: true,
  10195. configurable: true
  10196. });
  10197. AbstractMesh.prototype._preActivate = function () {
  10198. };
  10199. AbstractMesh.prototype._activate = function (renderId) {
  10200. this._renderId = renderId;
  10201. };
  10202. AbstractMesh.prototype.getWorldMatrix = function () {
  10203. if (this._masterMesh) {
  10204. return this._masterMesh.getWorldMatrix();
  10205. }
  10206. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10207. this.computeWorldMatrix();
  10208. }
  10209. return this._worldMatrix;
  10210. };
  10211. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10212. get: function () {
  10213. return this._worldMatrix;
  10214. },
  10215. enumerable: true,
  10216. configurable: true
  10217. });
  10218. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10219. get: function () {
  10220. return this._absolutePosition;
  10221. },
  10222. enumerable: true,
  10223. configurable: true
  10224. });
  10225. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10226. if (!this.rotationQuaternion) {
  10227. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10228. this.rotation = BABYLON.Vector3.Zero();
  10229. }
  10230. if (!space || space === 0 /* LOCAL */) {
  10231. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10232. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10233. }
  10234. else {
  10235. if (this.parent) {
  10236. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10237. invertParentWorldMatrix.invert();
  10238. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10239. }
  10240. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10241. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10242. }
  10243. };
  10244. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10245. var displacementVector = axis.scale(distance);
  10246. if (!space || space === 0 /* LOCAL */) {
  10247. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10248. this.setPositionWithLocalVector(tempV3);
  10249. }
  10250. else {
  10251. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10252. }
  10253. };
  10254. AbstractMesh.prototype.getAbsolutePosition = function () {
  10255. this.computeWorldMatrix();
  10256. return this._absolutePosition;
  10257. };
  10258. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10259. if (!absolutePosition) {
  10260. return;
  10261. }
  10262. var absolutePositionX;
  10263. var absolutePositionY;
  10264. var absolutePositionZ;
  10265. if (absolutePosition.x === undefined) {
  10266. if (arguments.length < 3) {
  10267. return;
  10268. }
  10269. absolutePositionX = arguments[0];
  10270. absolutePositionY = arguments[1];
  10271. absolutePositionZ = arguments[2];
  10272. }
  10273. else {
  10274. absolutePositionX = absolutePosition.x;
  10275. absolutePositionY = absolutePosition.y;
  10276. absolutePositionZ = absolutePosition.z;
  10277. }
  10278. if (this.parent) {
  10279. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10280. invertParentWorldMatrix.invert();
  10281. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10282. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10283. }
  10284. else {
  10285. this.position.x = absolutePositionX;
  10286. this.position.y = absolutePositionY;
  10287. this.position.z = absolutePositionZ;
  10288. }
  10289. };
  10290. // ================================== Point of View Movement =================================
  10291. /**
  10292. * Perform relative position change from the point of view of behind the front of the mesh.
  10293. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10294. * Supports definition of mesh facing forward or backward.
  10295. * @param {number} amountRight
  10296. * @param {number} amountUp
  10297. * @param {number} amountForward
  10298. */
  10299. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10300. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10301. };
  10302. /**
  10303. * Calculate 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.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10311. var rotMatrix = new BABYLON.Matrix();
  10312. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10313. rotQuaternion.toRotationMatrix(rotMatrix);
  10314. var translationDelta = BABYLON.Vector3.Zero();
  10315. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10316. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10317. return translationDelta;
  10318. };
  10319. // ================================== Point of View Rotation =================================
  10320. /**
  10321. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10322. * Supports definition of mesh facing forward or backward.
  10323. * @param {number} flipBack
  10324. * @param {number} twirlClockwise
  10325. * @param {number} tiltRight
  10326. */
  10327. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10328. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10329. };
  10330. /**
  10331. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10332. * Supports definition of mesh facing forward or backward.
  10333. * @param {number} flipBack
  10334. * @param {number} twirlClockwise
  10335. * @param {number} tiltRight
  10336. */
  10337. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10338. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10339. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10340. };
  10341. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10342. this._pivotMatrix = matrix;
  10343. this._cache.pivotMatrixUpdated = true;
  10344. };
  10345. AbstractMesh.prototype.getPivotMatrix = function () {
  10346. return this._pivotMatrix;
  10347. };
  10348. AbstractMesh.prototype._isSynchronized = function () {
  10349. if (this._isDirty) {
  10350. return false;
  10351. }
  10352. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10353. return false;
  10354. if (this._cache.pivotMatrixUpdated) {
  10355. return false;
  10356. }
  10357. if (this.infiniteDistance) {
  10358. return false;
  10359. }
  10360. if (!this._cache.position.equals(this.position))
  10361. return false;
  10362. if (this.rotationQuaternion) {
  10363. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10364. return false;
  10365. }
  10366. else {
  10367. if (!this._cache.rotation.equals(this.rotation))
  10368. return false;
  10369. }
  10370. if (!this._cache.scaling.equals(this.scaling))
  10371. return false;
  10372. return true;
  10373. };
  10374. AbstractMesh.prototype._initCache = function () {
  10375. _super.prototype._initCache.call(this);
  10376. this._cache.localMatrixUpdated = false;
  10377. this._cache.position = BABYLON.Vector3.Zero();
  10378. this._cache.scaling = BABYLON.Vector3.Zero();
  10379. this._cache.rotation = BABYLON.Vector3.Zero();
  10380. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10381. };
  10382. AbstractMesh.prototype.markAsDirty = function (property) {
  10383. if (property === "rotation") {
  10384. this.rotationQuaternion = null;
  10385. }
  10386. this._currentRenderId = Number.MAX_VALUE;
  10387. this._isDirty = true;
  10388. };
  10389. AbstractMesh.prototype._updateBoundingInfo = function () {
  10390. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10391. this._boundingInfo._update(this.worldMatrixFromCache);
  10392. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10393. };
  10394. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10395. if (!this.subMeshes) {
  10396. return;
  10397. }
  10398. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10399. var subMesh = this.subMeshes[subIndex];
  10400. subMesh.updateBoundingInfo(matrix);
  10401. }
  10402. };
  10403. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10404. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10405. return this._worldMatrix;
  10406. }
  10407. this._cache.position.copyFrom(this.position);
  10408. this._cache.scaling.copyFrom(this.scaling);
  10409. this._cache.pivotMatrixUpdated = false;
  10410. this._currentRenderId = this.getScene().getRenderId();
  10411. this._isDirty = false;
  10412. // Scaling
  10413. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10414. // Rotation
  10415. if (this.rotationQuaternion) {
  10416. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10417. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10418. }
  10419. else {
  10420. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10421. this._cache.rotation.copyFrom(this.rotation);
  10422. }
  10423. // Translation
  10424. if (this.infiniteDistance && !this.parent) {
  10425. var camera = this.getScene().activeCamera;
  10426. var cameraWorldMatrix = camera.getWorldMatrix();
  10427. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10428. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10429. }
  10430. else {
  10431. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10432. }
  10433. // Composing transformations
  10434. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10435. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10436. // Billboarding
  10437. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10438. var localPosition = this.position.clone();
  10439. var zero = this.getScene().activeCamera.position.clone();
  10440. if (this.parent && this.parent.position) {
  10441. localPosition.addInPlace(this.parent.position);
  10442. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10443. }
  10444. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  10445. zero = this.getScene().activeCamera.position;
  10446. }
  10447. else {
  10448. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10449. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10450. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10451. zero.y = localPosition.y + 0.001;
  10452. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10453. zero.z = localPosition.z + 0.001;
  10454. }
  10455. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10456. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10457. this._localBillboard.invert();
  10458. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10459. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10460. }
  10461. // Local world
  10462. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10463. // Parent
  10464. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10465. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10466. }
  10467. else {
  10468. this._worldMatrix.copyFrom(this._localWorld);
  10469. }
  10470. // Bounding info
  10471. this._updateBoundingInfo();
  10472. // Absolute position
  10473. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10474. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10475. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10476. }
  10477. return this._worldMatrix;
  10478. };
  10479. /**
  10480. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10481. * @param func: callback function to add
  10482. */
  10483. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10484. this._onAfterWorldMatrixUpdate.push(func);
  10485. };
  10486. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10487. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10488. if (index > -1) {
  10489. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10490. }
  10491. };
  10492. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10493. this.computeWorldMatrix();
  10494. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10495. };
  10496. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10497. this.computeWorldMatrix();
  10498. var invLocalWorldMatrix = this._localWorld.clone();
  10499. invLocalWorldMatrix.invert();
  10500. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10501. };
  10502. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10503. this.computeWorldMatrix();
  10504. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10505. };
  10506. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10507. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10508. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10509. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10510. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10511. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10512. /// <returns>Mesh oriented towards targetMesh</returns>
  10513. yawCor = yawCor || 0; // default to zero if undefined
  10514. pitchCor = pitchCor || 0;
  10515. rollCor = rollCor || 0;
  10516. var dv = targetPoint.subtract(this.position);
  10517. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10518. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10519. var pitch = Math.atan2(dv.y, len);
  10520. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10521. };
  10522. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10523. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10524. return false;
  10525. }
  10526. return true;
  10527. };
  10528. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10529. if (!camera) {
  10530. camera = this.getScene().activeCamera;
  10531. }
  10532. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10533. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10534. return false;
  10535. }
  10536. return true;
  10537. };
  10538. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10539. if (!this._boundingInfo || !mesh._boundingInfo) {
  10540. return false;
  10541. }
  10542. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10543. };
  10544. AbstractMesh.prototype.intersectsPoint = function (point) {
  10545. if (!this._boundingInfo) {
  10546. return false;
  10547. }
  10548. return this._boundingInfo.intersectsPoint(point);
  10549. };
  10550. // Physics
  10551. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10552. var physicsEngine = this.getScene().getPhysicsEngine();
  10553. if (!physicsEngine) {
  10554. return;
  10555. }
  10556. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10557. if (impostor.impostor) {
  10558. // Old API
  10559. options = impostor;
  10560. impostor = impostor.impostor;
  10561. }
  10562. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10563. physicsEngine._unregisterMesh(this);
  10564. return;
  10565. }
  10566. if (!options) {
  10567. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10568. }
  10569. else {
  10570. if (!options.mass && options.mass !== 0)
  10571. options.mass = 0;
  10572. if (!options.friction && options.friction !== 0)
  10573. options.friction = 0.2;
  10574. if (!options.restitution && options.restitution !== 0)
  10575. options.restitution = 0.2;
  10576. }
  10577. this._physicImpostor = impostor;
  10578. this._physicsMass = options.mass;
  10579. this._physicsFriction = options.friction;
  10580. this._physicRestitution = options.restitution;
  10581. return physicsEngine._registerMesh(this, impostor, options);
  10582. };
  10583. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10584. if (!this._physicImpostor) {
  10585. return BABYLON.PhysicsEngine.NoImpostor;
  10586. }
  10587. return this._physicImpostor;
  10588. };
  10589. AbstractMesh.prototype.getPhysicsMass = function () {
  10590. if (!this._physicsMass) {
  10591. return 0;
  10592. }
  10593. return this._physicsMass;
  10594. };
  10595. AbstractMesh.prototype.getPhysicsFriction = function () {
  10596. if (!this._physicsFriction) {
  10597. return 0;
  10598. }
  10599. return this._physicsFriction;
  10600. };
  10601. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10602. if (!this._physicRestitution) {
  10603. return 0;
  10604. }
  10605. return this._physicRestitution;
  10606. };
  10607. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10608. if (!camera) {
  10609. camera = this.getScene().activeCamera;
  10610. }
  10611. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10612. };
  10613. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10614. if (!camera) {
  10615. camera = this.getScene().activeCamera;
  10616. }
  10617. return this.absolutePosition.subtract(camera.position).length();
  10618. };
  10619. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10620. if (!this._physicImpostor) {
  10621. return;
  10622. }
  10623. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10624. };
  10625. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10626. if (!this._physicImpostor) {
  10627. return;
  10628. }
  10629. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10630. };
  10631. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10632. if (!this._physicImpostor) {
  10633. return;
  10634. }
  10635. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10636. };
  10637. // Collisions
  10638. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10639. var globalPosition = this.getAbsolutePosition();
  10640. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10641. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10642. this._collider.radius = this.ellipsoid;
  10643. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10644. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10645. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10646. this.position.addInPlace(this._diffPositionForCollisions);
  10647. }
  10648. };
  10649. // Submeshes octree
  10650. /**
  10651. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10652. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10653. */
  10654. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10655. if (maxCapacity === void 0) { maxCapacity = 64; }
  10656. if (maxDepth === void 0) { maxDepth = 2; }
  10657. if (!this._submeshesOctree) {
  10658. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10659. }
  10660. this.computeWorldMatrix(true);
  10661. // Update octree
  10662. var bbox = this.getBoundingInfo().boundingBox;
  10663. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10664. return this._submeshesOctree;
  10665. };
  10666. // Collisions
  10667. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10668. this._generatePointsArray();
  10669. // Transformation
  10670. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10671. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10672. subMesh._lastColliderWorldVertices = [];
  10673. subMesh._trianglePlanes = [];
  10674. var start = subMesh.verticesStart;
  10675. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10676. for (var i = start; i < end; i++) {
  10677. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10678. }
  10679. }
  10680. // Collide
  10681. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10682. };
  10683. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10684. var subMeshes;
  10685. var len;
  10686. // Octrees
  10687. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10688. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10689. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10690. len = intersections.length;
  10691. subMeshes = intersections.data;
  10692. }
  10693. else {
  10694. subMeshes = this.subMeshes;
  10695. len = subMeshes.length;
  10696. }
  10697. for (var index = 0; index < len; index++) {
  10698. var subMesh = subMeshes[index];
  10699. // Bounding test
  10700. if (len > 1 && !subMesh._checkCollision(collider))
  10701. continue;
  10702. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10703. }
  10704. };
  10705. AbstractMesh.prototype._checkCollision = function (collider) {
  10706. // Bounding box test
  10707. if (!this._boundingInfo._checkCollision(collider))
  10708. return;
  10709. // Transformation matrix
  10710. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10711. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10712. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10713. };
  10714. // Picking
  10715. AbstractMesh.prototype._generatePointsArray = function () {
  10716. return false;
  10717. };
  10718. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10719. var pickingInfo = new BABYLON.PickingInfo();
  10720. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10721. return pickingInfo;
  10722. }
  10723. if (!this._generatePointsArray()) {
  10724. return pickingInfo;
  10725. }
  10726. var intersectInfo = null;
  10727. // Octrees
  10728. var subMeshes;
  10729. var len;
  10730. if (this._submeshesOctree && this.useOctreeForPicking) {
  10731. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10732. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10733. len = intersections.length;
  10734. subMeshes = intersections.data;
  10735. }
  10736. else {
  10737. subMeshes = this.subMeshes;
  10738. len = subMeshes.length;
  10739. }
  10740. for (var index = 0; index < len; index++) {
  10741. var subMesh = subMeshes[index];
  10742. // Bounding test
  10743. if (len > 1 && !subMesh.canIntersects(ray))
  10744. continue;
  10745. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10746. if (currentIntersectInfo) {
  10747. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10748. intersectInfo = currentIntersectInfo;
  10749. intersectInfo.subMeshId = index;
  10750. if (fastCheck) {
  10751. break;
  10752. }
  10753. }
  10754. }
  10755. }
  10756. if (intersectInfo) {
  10757. // Get picked point
  10758. var world = this.getWorldMatrix();
  10759. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10760. var direction = ray.direction.clone();
  10761. direction = direction.scale(intersectInfo.distance);
  10762. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10763. var pickedPoint = worldOrigin.add(worldDirection);
  10764. // Return result
  10765. pickingInfo.hit = true;
  10766. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10767. pickingInfo.pickedPoint = pickedPoint;
  10768. pickingInfo.pickedMesh = this;
  10769. pickingInfo.bu = intersectInfo.bu;
  10770. pickingInfo.bv = intersectInfo.bv;
  10771. pickingInfo.faceId = intersectInfo.faceId;
  10772. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10773. return pickingInfo;
  10774. }
  10775. return pickingInfo;
  10776. };
  10777. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10778. return null;
  10779. };
  10780. AbstractMesh.prototype.releaseSubMeshes = function () {
  10781. if (this.subMeshes) {
  10782. while (this.subMeshes.length) {
  10783. this.subMeshes[0].dispose();
  10784. }
  10785. }
  10786. else {
  10787. this.subMeshes = new Array();
  10788. }
  10789. };
  10790. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10791. var index;
  10792. // Physics
  10793. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10794. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10795. }
  10796. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10797. var other = this._intersectionsInProgress[index];
  10798. var pos = other._intersectionsInProgress.indexOf(this);
  10799. other._intersectionsInProgress.splice(pos, 1);
  10800. }
  10801. this._intersectionsInProgress = [];
  10802. // SubMeshes
  10803. this.releaseSubMeshes();
  10804. // Remove from scene
  10805. this.getScene().removeMesh(this);
  10806. if (!doNotRecurse) {
  10807. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10808. if (this.getScene().particleSystems[index].emitter === this) {
  10809. this.getScene().particleSystems[index].dispose();
  10810. index--;
  10811. }
  10812. }
  10813. // Children
  10814. var objects = this.getScene().meshes.slice(0);
  10815. for (index = 0; index < objects.length; index++) {
  10816. if (objects[index].parent === this) {
  10817. objects[index].dispose();
  10818. }
  10819. }
  10820. }
  10821. else {
  10822. for (index = 0; index < this.getScene().meshes.length; index++) {
  10823. var obj = this.getScene().meshes[index];
  10824. if (obj.parent === this) {
  10825. obj.parent = null;
  10826. obj.computeWorldMatrix(true);
  10827. }
  10828. }
  10829. }
  10830. this._onAfterWorldMatrixUpdate = [];
  10831. this._isDisposed = true;
  10832. // Callback
  10833. if (this.onDispose) {
  10834. this.onDispose();
  10835. }
  10836. };
  10837. // Statics
  10838. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10839. AbstractMesh._BILLBOARDMODE_X = 1;
  10840. AbstractMesh._BILLBOARDMODE_Y = 2;
  10841. AbstractMesh._BILLBOARDMODE_Z = 4;
  10842. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10843. return AbstractMesh;
  10844. })(BABYLON.Node);
  10845. BABYLON.AbstractMesh = AbstractMesh;
  10846. })(BABYLON || (BABYLON = {}));
  10847. //# sourceMappingURL=babylon.abstractMesh.js.map
  10848. var BABYLON;
  10849. (function (BABYLON) {
  10850. var _InstancesBatch = (function () {
  10851. function _InstancesBatch() {
  10852. this.mustReturn = false;
  10853. this.visibleInstances = new Array();
  10854. this.renderSelf = new Array();
  10855. }
  10856. return _InstancesBatch;
  10857. })();
  10858. BABYLON._InstancesBatch = _InstancesBatch;
  10859. var Mesh = (function (_super) {
  10860. __extends(Mesh, _super);
  10861. /**
  10862. * @constructor
  10863. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10864. * @param {Scene} scene - The scene to add this mesh to.
  10865. * @param {Node} parent - The parent of this mesh, if it has one
  10866. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10867. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10868. * When false, achieved by calling a clone(), also passing False.
  10869. * This will make creation of children, recursive.
  10870. */
  10871. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10872. if (parent === void 0) { parent = null; }
  10873. _super.call(this, name, scene);
  10874. // Members
  10875. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10876. this.instances = new Array();
  10877. this._LODLevels = new Array();
  10878. this._onBeforeRenderCallbacks = new Array();
  10879. this._onAfterRenderCallbacks = new Array();
  10880. this._visibleInstances = {};
  10881. this._renderIdForInstances = new Array();
  10882. this._batchCache = new _InstancesBatch();
  10883. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10884. this._sideOrientation = Mesh._DEFAULTSIDE;
  10885. if (source) {
  10886. // Geometry
  10887. if (source._geometry) {
  10888. source._geometry.applyToMesh(this);
  10889. }
  10890. // Deep copy
  10891. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10892. // Material
  10893. this.material = source.material;
  10894. if (!doNotCloneChildren) {
  10895. for (var index = 0; index < scene.meshes.length; index++) {
  10896. var mesh = scene.meshes[index];
  10897. if (mesh.parent === source) {
  10898. // doNotCloneChildren is always going to be False
  10899. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10900. }
  10901. }
  10902. }
  10903. for (index = 0; index < scene.particleSystems.length; index++) {
  10904. var system = scene.particleSystems[index];
  10905. if (system.emitter === source) {
  10906. system.clone(system.name, this);
  10907. }
  10908. }
  10909. this.computeWorldMatrix(true);
  10910. }
  10911. // Parent
  10912. if (parent !== null) {
  10913. this.parent = parent;
  10914. }
  10915. }
  10916. Object.defineProperty(Mesh, "FRONTSIDE", {
  10917. get: function () {
  10918. return Mesh._FRONTSIDE;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(Mesh, "BACKSIDE", {
  10924. get: function () {
  10925. return Mesh._BACKSIDE;
  10926. },
  10927. enumerable: true,
  10928. configurable: true
  10929. });
  10930. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10931. get: function () {
  10932. return Mesh._DOUBLESIDE;
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10938. get: function () {
  10939. return Mesh._DEFAULTSIDE;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10945. // Methods
  10946. get: function () {
  10947. return this._LODLevels.length > 0;
  10948. },
  10949. enumerable: true,
  10950. configurable: true
  10951. });
  10952. Mesh.prototype._sortLODLevels = function () {
  10953. this._LODLevels.sort(function (a, b) {
  10954. if (a.distance < b.distance) {
  10955. return 1;
  10956. }
  10957. if (a.distance > b.distance) {
  10958. return -1;
  10959. }
  10960. return 0;
  10961. });
  10962. };
  10963. /**
  10964. * Add a mesh as LOD level triggered at the given distance.
  10965. * @param {number} distance - the distance from the center of the object to show this level
  10966. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10967. * @return {BABYLON.Mesh} this mesh (for chaining)
  10968. */
  10969. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10970. if (mesh && mesh._masterMesh) {
  10971. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10972. return this;
  10973. }
  10974. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10975. this._LODLevels.push(level);
  10976. if (mesh) {
  10977. mesh._masterMesh = this;
  10978. }
  10979. this._sortLODLevels();
  10980. return this;
  10981. };
  10982. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10983. for (var index = 0; index < this._LODLevels.length; index++) {
  10984. var level = this._LODLevels[index];
  10985. if (level.distance === distance) {
  10986. return level.mesh;
  10987. }
  10988. }
  10989. return null;
  10990. };
  10991. /**
  10992. * Remove a mesh from the LOD array
  10993. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10994. * @return {BABYLON.Mesh} this mesh (for chaining)
  10995. */
  10996. Mesh.prototype.removeLODLevel = function (mesh) {
  10997. for (var index = 0; index < this._LODLevels.length; index++) {
  10998. if (this._LODLevels[index].mesh === mesh) {
  10999. this._LODLevels.splice(index, 1);
  11000. if (mesh) {
  11001. mesh._masterMesh = null;
  11002. }
  11003. }
  11004. }
  11005. this._sortLODLevels();
  11006. return this;
  11007. };
  11008. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  11009. if (!this._LODLevels || this._LODLevels.length === 0) {
  11010. return this;
  11011. }
  11012. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  11013. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  11014. if (this.onLODLevelSelection) {
  11015. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  11016. }
  11017. return this;
  11018. }
  11019. for (var index = 0; index < this._LODLevels.length; index++) {
  11020. var level = this._LODLevels[index];
  11021. if (level.distance < distanceToCamera) {
  11022. if (level.mesh) {
  11023. level.mesh._preActivate();
  11024. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11025. }
  11026. if (this.onLODLevelSelection) {
  11027. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  11028. }
  11029. return level.mesh;
  11030. }
  11031. }
  11032. if (this.onLODLevelSelection) {
  11033. this.onLODLevelSelection(distanceToCamera, this, this);
  11034. }
  11035. return this;
  11036. };
  11037. Object.defineProperty(Mesh.prototype, "geometry", {
  11038. get: function () {
  11039. return this._geometry;
  11040. },
  11041. enumerable: true,
  11042. configurable: true
  11043. });
  11044. Mesh.prototype.getTotalVertices = function () {
  11045. if (!this._geometry) {
  11046. return 0;
  11047. }
  11048. return this._geometry.getTotalVertices();
  11049. };
  11050. Mesh.prototype.getVerticesData = function (kind) {
  11051. if (!this._geometry) {
  11052. return null;
  11053. }
  11054. return this._geometry.getVerticesData(kind);
  11055. };
  11056. Mesh.prototype.getVertexBuffer = function (kind) {
  11057. if (!this._geometry) {
  11058. return undefined;
  11059. }
  11060. return this._geometry.getVertexBuffer(kind);
  11061. };
  11062. Mesh.prototype.isVerticesDataPresent = function (kind) {
  11063. if (!this._geometry) {
  11064. if (this._delayInfo) {
  11065. return this._delayInfo.indexOf(kind) !== -1;
  11066. }
  11067. return false;
  11068. }
  11069. return this._geometry.isVerticesDataPresent(kind);
  11070. };
  11071. Mesh.prototype.getVerticesDataKinds = function () {
  11072. if (!this._geometry) {
  11073. var result = [];
  11074. if (this._delayInfo) {
  11075. for (var kind in this._delayInfo) {
  11076. result.push(kind);
  11077. }
  11078. }
  11079. return result;
  11080. }
  11081. return this._geometry.getVerticesDataKinds();
  11082. };
  11083. Mesh.prototype.getTotalIndices = function () {
  11084. if (!this._geometry) {
  11085. return 0;
  11086. }
  11087. return this._geometry.getTotalIndices();
  11088. };
  11089. Mesh.prototype.getIndices = function () {
  11090. if (!this._geometry) {
  11091. return [];
  11092. }
  11093. return this._geometry.getIndices();
  11094. };
  11095. Object.defineProperty(Mesh.prototype, "isBlocked", {
  11096. get: function () {
  11097. return this._masterMesh !== null && this._masterMesh !== undefined;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Mesh.prototype.isReady = function () {
  11103. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11104. return false;
  11105. }
  11106. return _super.prototype.isReady.call(this);
  11107. };
  11108. Mesh.prototype.isDisposed = function () {
  11109. return this._isDisposed;
  11110. };
  11111. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  11112. get: function () {
  11113. return this._sideOrientation;
  11114. },
  11115. set: function (sideO) {
  11116. this._sideOrientation = sideO;
  11117. },
  11118. enumerable: true,
  11119. configurable: true
  11120. });
  11121. // Methods
  11122. Mesh.prototype._preActivate = function () {
  11123. var sceneRenderId = this.getScene().getRenderId();
  11124. if (this._preActivateId === sceneRenderId) {
  11125. return;
  11126. }
  11127. this._preActivateId = sceneRenderId;
  11128. this._visibleInstances = null;
  11129. };
  11130. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  11131. if (!this._visibleInstances) {
  11132. this._visibleInstances = {};
  11133. this._visibleInstances.defaultRenderId = renderId;
  11134. this._visibleInstances.selfDefaultRenderId = this._renderId;
  11135. }
  11136. if (!this._visibleInstances[renderId]) {
  11137. this._visibleInstances[renderId] = new Array();
  11138. }
  11139. this._visibleInstances[renderId].push(instance);
  11140. };
  11141. Mesh.prototype.refreshBoundingInfo = function () {
  11142. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11143. if (data) {
  11144. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  11145. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11146. }
  11147. if (this.subMeshes) {
  11148. for (var index = 0; index < this.subMeshes.length; index++) {
  11149. this.subMeshes[index].refreshBoundingInfo();
  11150. }
  11151. }
  11152. this._updateBoundingInfo();
  11153. };
  11154. Mesh.prototype._createGlobalSubMesh = function () {
  11155. var totalVertices = this.getTotalVertices();
  11156. if (!totalVertices || !this.getIndices()) {
  11157. return null;
  11158. }
  11159. this.releaseSubMeshes();
  11160. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  11161. };
  11162. Mesh.prototype.subdivide = function (count) {
  11163. if (count < 1) {
  11164. return;
  11165. }
  11166. var totalIndices = this.getTotalIndices();
  11167. var subdivisionSize = (totalIndices / count) | 0;
  11168. var offset = 0;
  11169. while (subdivisionSize % 3 !== 0) {
  11170. subdivisionSize++;
  11171. }
  11172. this.releaseSubMeshes();
  11173. for (var index = 0; index < count; index++) {
  11174. if (offset >= totalIndices) {
  11175. break;
  11176. }
  11177. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  11178. offset += subdivisionSize;
  11179. }
  11180. this.synchronizeInstances();
  11181. };
  11182. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11183. if (kind instanceof Array) {
  11184. var temp = data;
  11185. data = kind;
  11186. kind = temp;
  11187. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  11188. }
  11189. if (!this._geometry) {
  11190. var vertexData = new BABYLON.VertexData();
  11191. vertexData.set(data, kind);
  11192. var scene = this.getScene();
  11193. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  11194. }
  11195. else {
  11196. this._geometry.setVerticesData(kind, data, updatable, stride);
  11197. }
  11198. };
  11199. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11200. if (!this._geometry) {
  11201. return;
  11202. }
  11203. if (!makeItUnique) {
  11204. this._geometry.updateVerticesData(kind, data, updateExtends);
  11205. }
  11206. else {
  11207. this.makeGeometryUnique();
  11208. this.updateVerticesData(kind, data, updateExtends, false);
  11209. }
  11210. };
  11211. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11212. if (!this._geometry) {
  11213. return;
  11214. }
  11215. if (!makeItUnique) {
  11216. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11217. }
  11218. else {
  11219. this.makeGeometryUnique();
  11220. this.updateVerticesDataDirectly(kind, data, offset, false);
  11221. }
  11222. };
  11223. // Mesh positions update function :
  11224. // updates the mesh positions according to the positionFunction returned values.
  11225. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  11226. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  11227. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  11228. if (computeNormals === void 0) { computeNormals = true; }
  11229. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11230. positionFunction(positions);
  11231. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  11232. if (computeNormals) {
  11233. var indices = this.getIndices();
  11234. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11235. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  11236. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  11237. }
  11238. };
  11239. Mesh.prototype.makeGeometryUnique = function () {
  11240. if (!this._geometry) {
  11241. return;
  11242. }
  11243. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11244. geometry.applyToMesh(this);
  11245. };
  11246. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11247. if (!this._geometry) {
  11248. var vertexData = new BABYLON.VertexData();
  11249. vertexData.indices = indices;
  11250. var scene = this.getScene();
  11251. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11252. }
  11253. else {
  11254. this._geometry.setIndices(indices, totalVertices);
  11255. }
  11256. };
  11257. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11258. var engine = this.getScene().getEngine();
  11259. // Wireframe
  11260. var indexToBind;
  11261. switch (fillMode) {
  11262. case BABYLON.Material.PointFillMode:
  11263. indexToBind = null;
  11264. break;
  11265. case BABYLON.Material.WireFrameFillMode:
  11266. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11267. break;
  11268. default:
  11269. case BABYLON.Material.TriangleFillMode:
  11270. indexToBind = this._geometry.getIndexBuffer();
  11271. break;
  11272. }
  11273. // VBOs
  11274. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11275. };
  11276. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11277. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11278. return;
  11279. }
  11280. var engine = this.getScene().getEngine();
  11281. switch (fillMode) {
  11282. case BABYLON.Material.PointFillMode:
  11283. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11284. break;
  11285. case BABYLON.Material.WireFrameFillMode:
  11286. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11287. break;
  11288. default:
  11289. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11290. }
  11291. };
  11292. Mesh.prototype.registerBeforeRender = function (func) {
  11293. this._onBeforeRenderCallbacks.push(func);
  11294. };
  11295. Mesh.prototype.unregisterBeforeRender = function (func) {
  11296. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11297. if (index > -1) {
  11298. this._onBeforeRenderCallbacks.splice(index, 1);
  11299. }
  11300. };
  11301. Mesh.prototype.registerAfterRender = function (func) {
  11302. this._onAfterRenderCallbacks.push(func);
  11303. };
  11304. Mesh.prototype.unregisterAfterRender = function (func) {
  11305. var index = this._onAfterRenderCallbacks.indexOf(func);
  11306. if (index > -1) {
  11307. this._onAfterRenderCallbacks.splice(index, 1);
  11308. }
  11309. };
  11310. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11311. var scene = this.getScene();
  11312. this._batchCache.mustReturn = false;
  11313. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11314. this._batchCache.visibleInstances[subMeshId] = null;
  11315. if (this._visibleInstances) {
  11316. var currentRenderId = scene.getRenderId();
  11317. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11318. var selfRenderId = this._renderId;
  11319. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11320. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11321. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11322. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11323. }
  11324. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11325. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11326. this._batchCache.mustReturn = true;
  11327. return this._batchCache;
  11328. }
  11329. if (currentRenderId !== selfRenderId) {
  11330. this._batchCache.renderSelf[subMeshId] = false;
  11331. }
  11332. }
  11333. this._renderIdForInstances[subMeshId] = currentRenderId;
  11334. }
  11335. return this._batchCache;
  11336. };
  11337. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11338. var visibleInstances = batch.visibleInstances[subMesh._id];
  11339. var matricesCount = visibleInstances.length + 1;
  11340. var bufferSize = matricesCount * 16 * 4;
  11341. while (this._instancesBufferSize < bufferSize) {
  11342. this._instancesBufferSize *= 2;
  11343. }
  11344. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11345. if (this._worldMatricesInstancesBuffer) {
  11346. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11347. }
  11348. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11349. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11350. }
  11351. var offset = 0;
  11352. var instancesCount = 0;
  11353. var world = this.getWorldMatrix();
  11354. if (batch.renderSelf[subMesh._id]) {
  11355. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11356. offset += 16;
  11357. instancesCount++;
  11358. }
  11359. if (visibleInstances) {
  11360. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11361. var instance = visibleInstances[instanceIndex];
  11362. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11363. offset += 16;
  11364. instancesCount++;
  11365. }
  11366. }
  11367. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11368. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11369. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11370. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11371. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11372. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11373. this._draw(subMesh, fillMode, instancesCount);
  11374. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11375. };
  11376. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11377. var scene = this.getScene();
  11378. var engine = scene.getEngine();
  11379. if (hardwareInstancedRendering) {
  11380. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11381. }
  11382. else {
  11383. if (batch.renderSelf[subMesh._id]) {
  11384. // Draw
  11385. if (onBeforeDraw) {
  11386. onBeforeDraw(false, this.getWorldMatrix());
  11387. }
  11388. this._draw(subMesh, fillMode);
  11389. }
  11390. if (batch.visibleInstances[subMesh._id]) {
  11391. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11392. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11393. // World
  11394. var world = instance.getWorldMatrix();
  11395. if (onBeforeDraw) {
  11396. onBeforeDraw(true, world);
  11397. }
  11398. // Draw
  11399. this._draw(subMesh, fillMode);
  11400. }
  11401. }
  11402. }
  11403. };
  11404. Mesh.prototype.render = function (subMesh) {
  11405. var scene = this.getScene();
  11406. // Managing instances
  11407. var batch = this._getInstancesRenderList(subMesh._id);
  11408. if (batch.mustReturn) {
  11409. return;
  11410. }
  11411. // Checking geometry state
  11412. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11413. return;
  11414. }
  11415. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11416. this._onBeforeRenderCallbacks[callbackIndex](this);
  11417. }
  11418. var engine = scene.getEngine();
  11419. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11420. // Material
  11421. var effectiveMaterial = subMesh.getMaterial();
  11422. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11423. return;
  11424. }
  11425. // Outline - step 1
  11426. var savedDepthWrite = engine.getDepthWrite();
  11427. if (this.renderOutline) {
  11428. engine.setDepthWrite(false);
  11429. scene.getOutlineRenderer().render(subMesh, batch);
  11430. engine.setDepthWrite(savedDepthWrite);
  11431. }
  11432. effectiveMaterial._preBind();
  11433. var effect = effectiveMaterial.getEffect();
  11434. // Bind
  11435. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11436. this._bind(subMesh, effect, fillMode);
  11437. var world = this.getWorldMatrix();
  11438. effectiveMaterial.bind(world, this);
  11439. // Draw
  11440. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11441. if (isInstance) {
  11442. effectiveMaterial.bindOnlyWorldMatrix(world);
  11443. }
  11444. });
  11445. // Unbind
  11446. effectiveMaterial.unbind();
  11447. // Outline - step 2
  11448. if (this.renderOutline && savedDepthWrite) {
  11449. engine.setDepthWrite(true);
  11450. engine.setColorWrite(false);
  11451. scene.getOutlineRenderer().render(subMesh, batch);
  11452. engine.setColorWrite(true);
  11453. }
  11454. // Overlay
  11455. if (this.renderOverlay) {
  11456. var currentMode = engine.getAlphaMode();
  11457. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11458. scene.getOutlineRenderer().render(subMesh, batch, true);
  11459. engine.setAlphaMode(currentMode);
  11460. }
  11461. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11462. this._onAfterRenderCallbacks[callbackIndex](this);
  11463. }
  11464. };
  11465. Mesh.prototype.getEmittedParticleSystems = function () {
  11466. var results = new Array();
  11467. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11468. var particleSystem = this.getScene().particleSystems[index];
  11469. if (particleSystem.emitter === this) {
  11470. results.push(particleSystem);
  11471. }
  11472. }
  11473. return results;
  11474. };
  11475. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11476. var results = new Array();
  11477. var descendants = this.getDescendants();
  11478. descendants.push(this);
  11479. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11480. var particleSystem = this.getScene().particleSystems[index];
  11481. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11482. results.push(particleSystem);
  11483. }
  11484. }
  11485. return results;
  11486. };
  11487. Mesh.prototype.getChildren = function () {
  11488. var results = [];
  11489. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11490. var mesh = this.getScene().meshes[index];
  11491. if (mesh.parent === this) {
  11492. results.push(mesh);
  11493. }
  11494. }
  11495. return results;
  11496. };
  11497. Mesh.prototype._checkDelayState = function () {
  11498. var _this = this;
  11499. var that = this;
  11500. var scene = this.getScene();
  11501. if (this._geometry) {
  11502. this._geometry.load(scene);
  11503. }
  11504. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11505. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11506. scene._addPendingData(that);
  11507. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11508. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11509. if (data instanceof ArrayBuffer) {
  11510. _this._delayLoadingFunction(data, _this);
  11511. }
  11512. else {
  11513. _this._delayLoadingFunction(JSON.parse(data), _this);
  11514. }
  11515. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11516. scene._removePendingData(_this);
  11517. }, function () {
  11518. }, scene.database, getBinaryData);
  11519. }
  11520. };
  11521. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11522. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11523. return false;
  11524. }
  11525. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11526. return false;
  11527. }
  11528. this._checkDelayState();
  11529. return true;
  11530. };
  11531. Mesh.prototype.setMaterialByID = function (id) {
  11532. var materials = this.getScene().materials;
  11533. for (var index = 0; index < materials.length; index++) {
  11534. if (materials[index].id === id) {
  11535. this.material = materials[index];
  11536. return;
  11537. }
  11538. }
  11539. // Multi
  11540. var multiMaterials = this.getScene().multiMaterials;
  11541. for (index = 0; index < multiMaterials.length; index++) {
  11542. if (multiMaterials[index].id === id) {
  11543. this.material = multiMaterials[index];
  11544. return;
  11545. }
  11546. }
  11547. };
  11548. Mesh.prototype.getAnimatables = function () {
  11549. var results = [];
  11550. if (this.material) {
  11551. results.push(this.material);
  11552. }
  11553. if (this.skeleton) {
  11554. results.push(this.skeleton);
  11555. }
  11556. return results;
  11557. };
  11558. // Geometry
  11559. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11560. // Position
  11561. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11562. return;
  11563. }
  11564. this._resetPointsArrayCache();
  11565. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11566. var temp = [];
  11567. for (var index = 0; index < data.length; index += 3) {
  11568. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11569. }
  11570. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11571. // Normals
  11572. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11573. return;
  11574. }
  11575. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11576. for (index = 0; index < data.length; index += 3) {
  11577. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11578. }
  11579. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11580. };
  11581. // Cache
  11582. Mesh.prototype._resetPointsArrayCache = function () {
  11583. this._positions = null;
  11584. };
  11585. Mesh.prototype._generatePointsArray = function () {
  11586. if (this._positions)
  11587. return true;
  11588. this._positions = [];
  11589. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11590. if (!data) {
  11591. return false;
  11592. }
  11593. for (var index = 0; index < data.length; index += 3) {
  11594. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11595. }
  11596. return true;
  11597. };
  11598. // Clone
  11599. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11600. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11601. };
  11602. // Dispose
  11603. Mesh.prototype.dispose = function (doNotRecurse) {
  11604. if (this._geometry) {
  11605. this._geometry.releaseForMesh(this, true);
  11606. }
  11607. // Instances
  11608. if (this._worldMatricesInstancesBuffer) {
  11609. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11610. this._worldMatricesInstancesBuffer = null;
  11611. }
  11612. while (this.instances.length) {
  11613. this.instances[0].dispose();
  11614. }
  11615. _super.prototype.dispose.call(this, doNotRecurse);
  11616. };
  11617. // Geometric tools
  11618. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11619. var _this = this;
  11620. var scene = this.getScene();
  11621. var onload = function (img) {
  11622. // Getting height map data
  11623. var canvas = document.createElement("canvas");
  11624. var context = canvas.getContext("2d");
  11625. var heightMapWidth = img.width;
  11626. var heightMapHeight = img.height;
  11627. canvas.width = heightMapWidth;
  11628. canvas.height = heightMapHeight;
  11629. context.drawImage(img, 0, 0);
  11630. // Create VertexData from map data
  11631. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11632. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11633. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11634. //execute success callback, if set
  11635. if (onSuccess) {
  11636. onSuccess(_this);
  11637. }
  11638. };
  11639. BABYLON.Tools.LoadImage(url, onload, function () {
  11640. }, scene.database);
  11641. };
  11642. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11643. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11644. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11645. return;
  11646. }
  11647. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11648. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11649. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11650. var position = BABYLON.Vector3.Zero();
  11651. var normal = BABYLON.Vector3.Zero();
  11652. var uv = BABYLON.Vector2.Zero();
  11653. for (var index = 0; index < positions.length; index += 3) {
  11654. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11655. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11656. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11657. // Compute height
  11658. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11659. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11660. var pos = (u + v * heightMapWidth) * 4;
  11661. var r = buffer[pos] / 255.0;
  11662. var g = buffer[pos + 1] / 255.0;
  11663. var b = buffer[pos + 2] / 255.0;
  11664. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11665. normal.normalize();
  11666. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11667. position = position.add(normal);
  11668. position.toArray(positions, index);
  11669. }
  11670. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11671. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11672. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11673. };
  11674. Mesh.prototype.convertToFlatShadedMesh = function () {
  11675. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11676. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11677. var kinds = this.getVerticesDataKinds();
  11678. var vbs = [];
  11679. var data = [];
  11680. var newdata = [];
  11681. var updatableNormals = false;
  11682. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11683. var kind = kinds[kindIndex];
  11684. var vertexBuffer = this.getVertexBuffer(kind);
  11685. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11686. updatableNormals = vertexBuffer.isUpdatable();
  11687. kinds.splice(kindIndex, 1);
  11688. kindIndex--;
  11689. continue;
  11690. }
  11691. vbs[kind] = vertexBuffer;
  11692. data[kind] = vbs[kind].getData();
  11693. newdata[kind] = [];
  11694. }
  11695. // Save previous submeshes
  11696. var previousSubmeshes = this.subMeshes.slice(0);
  11697. var indices = this.getIndices();
  11698. var totalIndices = this.getTotalIndices();
  11699. for (var index = 0; index < totalIndices; index++) {
  11700. var vertexIndex = indices[index];
  11701. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11702. kind = kinds[kindIndex];
  11703. var stride = vbs[kind].getStrideSize();
  11704. for (var offset = 0; offset < stride; offset++) {
  11705. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11706. }
  11707. }
  11708. }
  11709. // Updating faces & normal
  11710. var normals = [];
  11711. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11712. for (index = 0; index < totalIndices; index += 3) {
  11713. indices[index] = index;
  11714. indices[index + 1] = index + 1;
  11715. indices[index + 2] = index + 2;
  11716. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11717. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11718. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11719. var p1p2 = p1.subtract(p2);
  11720. var p3p2 = p3.subtract(p2);
  11721. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11722. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11723. normals.push(normal.x);
  11724. normals.push(normal.y);
  11725. normals.push(normal.z);
  11726. }
  11727. }
  11728. this.setIndices(indices);
  11729. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11730. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11731. kind = kinds[kindIndex];
  11732. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11733. }
  11734. // Updating submeshes
  11735. this.releaseSubMeshes();
  11736. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11737. var previousOne = previousSubmeshes[submeshIndex];
  11738. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11739. }
  11740. this.synchronizeInstances();
  11741. };
  11742. // Instances
  11743. Mesh.prototype.createInstance = function (name) {
  11744. return new BABYLON.InstancedMesh(name, this);
  11745. };
  11746. Mesh.prototype.synchronizeInstances = function () {
  11747. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11748. var instance = this.instances[instanceIndex];
  11749. instance._syncSubMeshes();
  11750. }
  11751. };
  11752. /**
  11753. * Simplify the mesh according to the given array of settings.
  11754. * Function will return immediately and will simplify async.
  11755. * @param settings a collection of simplification settings.
  11756. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11757. * @param type the type of simplification to run.
  11758. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11759. */
  11760. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11761. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11762. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11763. this.getScene().simplificationQueue.addTask({
  11764. settings: settings,
  11765. parallelProcessing: parallelProcessing,
  11766. mesh: this,
  11767. simplificationType: simplificationType,
  11768. successCallback: successCallback
  11769. });
  11770. };
  11771. /**
  11772. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11773. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11774. * This should be used together with the simplification to avoid disappearing triangles.
  11775. * @param successCallback an optional success callback to be called after the optimization finished.
  11776. */
  11777. Mesh.prototype.optimizeIndices = function (successCallback) {
  11778. var _this = this;
  11779. var indices = this.getIndices();
  11780. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11781. var vectorPositions = [];
  11782. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11783. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11784. }
  11785. var dupes = [];
  11786. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11787. var realPos = vectorPositions.length - 1 - iteration;
  11788. var testedPosition = vectorPositions[realPos];
  11789. for (var j = 0; j < realPos; ++j) {
  11790. var againstPosition = vectorPositions[j];
  11791. if (testedPosition.equals(againstPosition)) {
  11792. dupes[realPos] = j;
  11793. break;
  11794. }
  11795. }
  11796. }, function () {
  11797. for (var i = 0; i < indices.length; ++i) {
  11798. indices[i] = dupes[indices[i]] || indices[i];
  11799. }
  11800. //indices are now reordered
  11801. var originalSubMeshes = _this.subMeshes.slice(0);
  11802. _this.setIndices(indices);
  11803. _this.subMeshes = originalSubMeshes;
  11804. if (successCallback) {
  11805. successCallback(_this);
  11806. }
  11807. });
  11808. };
  11809. // Statics
  11810. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  11811. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11812. if (ribbonInstance === void 0) { ribbonInstance = null; }
  11813. if (ribbonInstance) {
  11814. // positionFunction : ribbon case
  11815. // only pathArray and sideOrientation parameters are taken into account for positions update
  11816. var positionsOfRibbon = function (pathArray, sideOrientation) {
  11817. var positionFunction = function (positions) {
  11818. var minlg = pathArray[0].length;
  11819. var i = 0;
  11820. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  11821. for (var si = 1; si <= ns; si++) {
  11822. for (var p = 0; p < pathArray.length; p++) {
  11823. var path = pathArray[p];
  11824. var l = path.length;
  11825. minlg = (minlg < l) ? minlg : l;
  11826. var j = 0;
  11827. while (j < minlg) {
  11828. positions[i] = path[j].x;
  11829. positions[i + 1] = path[j].y;
  11830. positions[i + 2] = path[j].z;
  11831. j++;
  11832. i += 3;
  11833. }
  11834. }
  11835. }
  11836. };
  11837. return positionFunction;
  11838. };
  11839. var sideOrientation = ribbonInstance.sideOrientation;
  11840. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  11841. ribbonInstance.updateMeshPositions(positionFunction, true);
  11842. return ribbonInstance;
  11843. }
  11844. else {
  11845. var ribbon = new Mesh(name, scene);
  11846. ribbon.sideOrientation = sideOrientation;
  11847. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11848. vertexData.applyToMesh(ribbon, updatable);
  11849. return ribbon;
  11850. }
  11851. };
  11852. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11853. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11854. var box = new Mesh(name, scene);
  11855. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11856. vertexData.applyToMesh(box, updatable);
  11857. return box;
  11858. };
  11859. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11860. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11861. var sphere = new Mesh(name, scene);
  11862. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11863. vertexData.applyToMesh(sphere, updatable);
  11864. return sphere;
  11865. };
  11866. // Cylinder and cone (Code inspired by SharpDX.org)
  11867. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11868. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11869. // subdivisions is a new parameter, we need to support old signature
  11870. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11871. if (scene !== undefined) {
  11872. updatable = scene;
  11873. }
  11874. scene = subdivisions;
  11875. subdivisions = 1;
  11876. }
  11877. var cylinder = new Mesh(name, scene);
  11878. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11879. vertexData.applyToMesh(cylinder, updatable);
  11880. return cylinder;
  11881. };
  11882. // Torus (Code from SharpDX.org)
  11883. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11884. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11885. var torus = new Mesh(name, scene);
  11886. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11887. vertexData.applyToMesh(torus, updatable);
  11888. return torus;
  11889. };
  11890. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11891. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11892. var torusKnot = new Mesh(name, scene);
  11893. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11894. vertexData.applyToMesh(torusKnot, updatable);
  11895. return torusKnot;
  11896. };
  11897. // Lines
  11898. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  11899. if (linesInstance === void 0) { linesInstance = null; }
  11900. if (linesInstance) {
  11901. var positionsOfLines = function (points) {
  11902. var positionFunction = function (positions) {
  11903. var i = 0;
  11904. for (var p = 0; p < points.length; p++) {
  11905. positions[i] = points[p].x;
  11906. positions[i + 1] = points[p].y;
  11907. positions[i + 2] = points[p].z;
  11908. i += 3;
  11909. }
  11910. };
  11911. return positionFunction;
  11912. };
  11913. var positionFunction = positionsOfLines(points);
  11914. linesInstance.updateMeshPositions(positionFunction, false);
  11915. return linesInstance;
  11916. }
  11917. // lines creation
  11918. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11919. var vertexData = BABYLON.VertexData.CreateLines(points);
  11920. vertexData.applyToMesh(lines, updatable);
  11921. return lines;
  11922. };
  11923. // Extrusion
  11924. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation, extrudedInstance) {
  11925. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11926. if (extrudedInstance === void 0) { extrudedInstance = null; }
  11927. scale = scale || 1;
  11928. rotation = rotation || 0;
  11929. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation, extrudedInstance);
  11930. return extruded;
  11931. };
  11932. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation, extrudedInstance) {
  11933. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11934. if (extrudedInstance === void 0) { extrudedInstance = null; }
  11935. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation, extrudedInstance);
  11936. return extrudedCustom;
  11937. };
  11938. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side, instance) {
  11939. // extrusion geometry
  11940. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, custom) {
  11941. var tangents = path3D.getTangents();
  11942. var normals = path3D.getNormals();
  11943. var binormals = path3D.getBinormals();
  11944. var distances = path3D.getDistances();
  11945. var angle = 0;
  11946. var returnScale = function (i, distance) {
  11947. return scale;
  11948. };
  11949. var returnRotation = function (i, distance) {
  11950. return rotation;
  11951. };
  11952. var rotate = custom ? rotateFunction : returnRotation;
  11953. var scl = custom ? scaleFunction : returnScale;
  11954. var index = 0;
  11955. for (var i = 0; i < curve.length; i++) {
  11956. var shapePath = new Array();
  11957. var angleStep = rotate(i, distances[i]);
  11958. var scaleRatio = scl(i, distances[i]);
  11959. for (var p = 0; p < shape.length; p++) {
  11960. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11961. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11962. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11963. shapePath.push(rotated);
  11964. }
  11965. shapePaths[index] = shapePath;
  11966. angle += angleStep;
  11967. index++;
  11968. }
  11969. return shapePaths;
  11970. };
  11971. if (instance) {
  11972. var path3D = (instance.path3D).update(curve);
  11973. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, custom);
  11974. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  11975. return instance;
  11976. }
  11977. // extruded shape creation
  11978. var path3D = new BABYLON.Path3D(curve);
  11979. var newShapePaths = new Array();
  11980. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, custom);
  11981. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  11982. extrudedGeneric.pathArray = pathArray;
  11983. extrudedGeneric.path3D = path3D;
  11984. return extrudedGeneric;
  11985. };
  11986. // Plane & ground
  11987. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11988. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11989. var plane = new Mesh(name, scene);
  11990. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11991. vertexData.applyToMesh(plane, updatable);
  11992. return plane;
  11993. };
  11994. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11995. var ground = new BABYLON.GroundMesh(name, scene);
  11996. ground._setReady(false);
  11997. ground._subdivisions = subdivisions;
  11998. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11999. vertexData.applyToMesh(ground, updatable);
  12000. ground._setReady(true);
  12001. return ground;
  12002. };
  12003. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  12004. var tiledGround = new Mesh(name, scene);
  12005. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  12006. vertexData.applyToMesh(tiledGround, updatable);
  12007. return tiledGround;
  12008. };
  12009. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  12010. var ground = new BABYLON.GroundMesh(name, scene);
  12011. ground._subdivisions = subdivisions;
  12012. ground._setReady(false);
  12013. var onload = function (img) {
  12014. // Getting height map data
  12015. var canvas = document.createElement("canvas");
  12016. var context = canvas.getContext("2d");
  12017. var heightMapWidth = img.width;
  12018. var heightMapHeight = img.height;
  12019. canvas.width = heightMapWidth;
  12020. canvas.height = heightMapHeight;
  12021. context.drawImage(img, 0, 0);
  12022. // Create VertexData from map data
  12023. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  12024. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  12025. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  12026. vertexData.applyToMesh(ground, updatable);
  12027. ground._setReady(true);
  12028. //execute ready callback, if set
  12029. if (onReady) {
  12030. onReady(ground);
  12031. }
  12032. };
  12033. BABYLON.Tools.LoadImage(url, onload, function () {
  12034. }, scene.database);
  12035. return ground;
  12036. };
  12037. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, scene, updatable, sideOrientation, tubeInstance) {
  12038. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12039. if (tubeInstance === void 0) { tubeInstance = null; }
  12040. // tube geometry
  12041. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction) {
  12042. var tangents = path3D.getTangents();
  12043. var normals = path3D.getNormals();
  12044. var distances = path3D.getDistances();
  12045. var pi2 = Math.PI * 2;
  12046. var step = pi2 / tessellation;
  12047. var returnRadius = function (i, distance) { return radius; };
  12048. var radiusFunctionFinal = radiusFunction || returnRadius;
  12049. var circlePath;
  12050. var rad;
  12051. var normal;
  12052. var rotated;
  12053. var rotationMatrix;
  12054. var index = 0;
  12055. for (var i = 0; i < path.length; i++) {
  12056. rad = radiusFunctionFinal(i, distances[i]); // current radius
  12057. circlePath = Array(); // current circle array
  12058. normal = normals[i]; // current normal
  12059. for (var ang = 0; ang < pi2; ang += step) {
  12060. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  12061. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  12062. circlePath.push(rotated);
  12063. }
  12064. circlePaths[index] = circlePath;
  12065. index++;
  12066. }
  12067. return circlePaths;
  12068. };
  12069. if (tubeInstance) {
  12070. var path3D = (tubeInstance.path3D).update(path);
  12071. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction);
  12072. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  12073. return tubeInstance;
  12074. }
  12075. // tube creation
  12076. var path3D = new BABYLON.Path3D(path);
  12077. var newPathArray = new Array();
  12078. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction);
  12079. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  12080. tube.pathArray = pathArray;
  12081. tube.path3D = path3D;
  12082. tube.tessellation = tessellation;
  12083. return tube;
  12084. };
  12085. // Decals
  12086. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  12087. if (angle === void 0) { angle = 0; }
  12088. var indices = sourceMesh.getIndices();
  12089. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12090. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12091. // Getting correct rotation
  12092. if (!normal) {
  12093. var target = new BABYLON.Vector3(0, 0, 1);
  12094. var camera = sourceMesh.getScene().activeCamera;
  12095. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  12096. normal = camera.globalPosition.subtract(cameraWorldTarget);
  12097. }
  12098. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  12099. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  12100. var pitch = Math.atan2(normal.y, len);
  12101. // Matrix
  12102. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  12103. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  12104. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  12105. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  12106. var vertexData = new BABYLON.VertexData();
  12107. vertexData.indices = [];
  12108. vertexData.positions = [];
  12109. vertexData.normals = [];
  12110. vertexData.uvs = [];
  12111. var currentVertexDataIndex = 0;
  12112. var extractDecalVector3 = function (indexId) {
  12113. var vertexId = indices[indexId];
  12114. var result = new BABYLON.PositionNormalVertex();
  12115. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  12116. // Send vector to decal local world
  12117. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  12118. // Get normal
  12119. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  12120. return result;
  12121. };
  12122. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  12123. var clip = function (vertices, axis) {
  12124. if (vertices.length === 0) {
  12125. return vertices;
  12126. }
  12127. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  12128. var clipVertices = function (v0, v1) {
  12129. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  12130. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  12131. };
  12132. var result = new Array();
  12133. for (var index = 0; index < vertices.length; index += 3) {
  12134. var v1Out;
  12135. var v2Out;
  12136. var v3Out;
  12137. var total = 0;
  12138. var nV1, nV2, nV3, nV4;
  12139. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  12140. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  12141. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  12142. v1Out = d1 > 0;
  12143. v2Out = d2 > 0;
  12144. v3Out = d3 > 0;
  12145. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  12146. switch (total) {
  12147. case 0:
  12148. result.push(vertices[index]);
  12149. result.push(vertices[index + 1]);
  12150. result.push(vertices[index + 2]);
  12151. break;
  12152. case 1:
  12153. if (v1Out) {
  12154. nV1 = vertices[index + 1];
  12155. nV2 = vertices[index + 2];
  12156. nV3 = clipVertices(vertices[index], nV1);
  12157. nV4 = clipVertices(vertices[index], nV2);
  12158. }
  12159. if (v2Out) {
  12160. nV1 = vertices[index];
  12161. nV2 = vertices[index + 2];
  12162. nV3 = clipVertices(vertices[index + 1], nV1);
  12163. nV4 = clipVertices(vertices[index + 1], nV2);
  12164. result.push(nV3);
  12165. result.push(nV2.clone());
  12166. result.push(nV1.clone());
  12167. result.push(nV2.clone());
  12168. result.push(nV3.clone());
  12169. result.push(nV4);
  12170. break;
  12171. }
  12172. if (v3Out) {
  12173. nV1 = vertices[index];
  12174. nV2 = vertices[index + 1];
  12175. nV3 = clipVertices(vertices[index + 2], nV1);
  12176. nV4 = clipVertices(vertices[index + 2], nV2);
  12177. }
  12178. result.push(nV1.clone());
  12179. result.push(nV2.clone());
  12180. result.push(nV3);
  12181. result.push(nV4);
  12182. result.push(nV3.clone());
  12183. result.push(nV2.clone());
  12184. break;
  12185. case 2:
  12186. if (!v1Out) {
  12187. nV1 = vertices[index].clone();
  12188. nV2 = clipVertices(nV1, vertices[index + 1]);
  12189. nV3 = clipVertices(nV1, vertices[index + 2]);
  12190. result.push(nV1);
  12191. result.push(nV2);
  12192. result.push(nV3);
  12193. }
  12194. if (!v2Out) {
  12195. nV1 = vertices[index + 1].clone();
  12196. nV2 = clipVertices(nV1, vertices[index + 2]);
  12197. nV3 = clipVertices(nV1, vertices[index]);
  12198. result.push(nV1);
  12199. result.push(nV2);
  12200. result.push(nV3);
  12201. }
  12202. if (!v3Out) {
  12203. nV1 = vertices[index + 2].clone();
  12204. nV2 = clipVertices(nV1, vertices[index]);
  12205. nV3 = clipVertices(nV1, vertices[index + 1]);
  12206. result.push(nV1);
  12207. result.push(nV2);
  12208. result.push(nV3);
  12209. }
  12210. break;
  12211. case 3:
  12212. break;
  12213. }
  12214. }
  12215. return result;
  12216. };
  12217. for (var index = 0; index < indices.length; index += 3) {
  12218. var faceVertices = new Array();
  12219. faceVertices.push(extractDecalVector3(index));
  12220. faceVertices.push(extractDecalVector3(index + 1));
  12221. faceVertices.push(extractDecalVector3(index + 2));
  12222. // Clip
  12223. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  12224. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  12225. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  12226. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  12227. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  12228. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  12229. if (faceVertices.length === 0) {
  12230. continue;
  12231. }
  12232. // Add UVs and get back to world
  12233. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  12234. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  12235. var vertex = faceVertices[vIndex];
  12236. vertexData.indices.push(currentVertexDataIndex);
  12237. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  12238. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  12239. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  12240. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  12241. currentVertexDataIndex++;
  12242. }
  12243. }
  12244. // Return mesh
  12245. var decal = new Mesh(name, sourceMesh.getScene());
  12246. vertexData.applyToMesh(decal);
  12247. decal.position = position.clone();
  12248. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  12249. return decal;
  12250. };
  12251. // Tools
  12252. Mesh.MinMax = function (meshes) {
  12253. var minVector = null;
  12254. var maxVector = null;
  12255. for (var i in meshes) {
  12256. var mesh = meshes[i];
  12257. var boundingBox = mesh.getBoundingInfo().boundingBox;
  12258. if (!minVector) {
  12259. minVector = boundingBox.minimumWorld;
  12260. maxVector = boundingBox.maximumWorld;
  12261. continue;
  12262. }
  12263. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  12264. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  12265. }
  12266. return {
  12267. min: minVector,
  12268. max: maxVector
  12269. };
  12270. };
  12271. Mesh.Center = function (meshesOrMinMaxVector) {
  12272. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  12273. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  12274. };
  12275. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  12276. if (disposeSource === void 0) { disposeSource = true; }
  12277. var source = meshes[0];
  12278. var material = source.material;
  12279. var scene = source.getScene();
  12280. if (!allow32BitsIndices) {
  12281. var totalVertices = 0;
  12282. for (var index = 0; index < meshes.length; index++) {
  12283. totalVertices += meshes[index].getTotalVertices();
  12284. if (totalVertices > 65536) {
  12285. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  12286. return null;
  12287. }
  12288. }
  12289. }
  12290. // Merge
  12291. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  12292. vertexData.transform(source.getWorldMatrix());
  12293. for (index = 1; index < meshes.length; index++) {
  12294. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  12295. otherVertexData.transform(meshes[index].getWorldMatrix());
  12296. vertexData.merge(otherVertexData);
  12297. }
  12298. var newMesh = new Mesh(source.name + "_merged", scene);
  12299. vertexData.applyToMesh(newMesh);
  12300. // Setting properties
  12301. newMesh.material = material;
  12302. newMesh.checkCollisions = source.checkCollisions;
  12303. // Cleaning
  12304. if (disposeSource) {
  12305. for (index = 0; index < meshes.length; index++) {
  12306. meshes[index].dispose();
  12307. }
  12308. }
  12309. return newMesh;
  12310. };
  12311. // Consts
  12312. Mesh._FRONTSIDE = 0;
  12313. Mesh._BACKSIDE = 1;
  12314. Mesh._DOUBLESIDE = 2;
  12315. Mesh._DEFAULTSIDE = 0;
  12316. return Mesh;
  12317. })(BABYLON.AbstractMesh);
  12318. BABYLON.Mesh = Mesh;
  12319. })(BABYLON || (BABYLON = {}));
  12320. //# sourceMappingURL=babylon.mesh.js.map
  12321. var BABYLON;
  12322. (function (BABYLON) {
  12323. var GroundMesh = (function (_super) {
  12324. __extends(GroundMesh, _super);
  12325. function GroundMesh(name, scene) {
  12326. _super.call(this, name, scene);
  12327. this.generateOctree = false;
  12328. this._worldInverse = new BABYLON.Matrix();
  12329. }
  12330. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  12331. get: function () {
  12332. return this._subdivisions;
  12333. },
  12334. enumerable: true,
  12335. configurable: true
  12336. });
  12337. GroundMesh.prototype.optimize = function (chunksCount) {
  12338. this.subdivide(this._subdivisions);
  12339. this.createOrUpdateSubmeshesOctree(32);
  12340. };
  12341. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  12342. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  12343. this.getWorldMatrix().invertToRef(this._worldInverse);
  12344. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  12345. var pickInfo = this.intersects(ray);
  12346. if (pickInfo.hit) {
  12347. return pickInfo.pickedPoint.y;
  12348. }
  12349. return 0;
  12350. };
  12351. return GroundMesh;
  12352. })(BABYLON.Mesh);
  12353. BABYLON.GroundMesh = GroundMesh;
  12354. })(BABYLON || (BABYLON = {}));
  12355. //# sourceMappingURL=babylon.groundMesh.js.map
  12356. var BABYLON;
  12357. (function (BABYLON) {
  12358. /**
  12359. * Creates an instance based on a source mesh.
  12360. */
  12361. var InstancedMesh = (function (_super) {
  12362. __extends(InstancedMesh, _super);
  12363. function InstancedMesh(name, source) {
  12364. _super.call(this, name, source.getScene());
  12365. source.instances.push(this);
  12366. this._sourceMesh = source;
  12367. this.position.copyFrom(source.position);
  12368. this.rotation.copyFrom(source.rotation);
  12369. this.scaling.copyFrom(source.scaling);
  12370. if (source.rotationQuaternion) {
  12371. this.rotationQuaternion = source.rotationQuaternion.clone();
  12372. }
  12373. this.infiniteDistance = source.infiniteDistance;
  12374. this.setPivotMatrix(source.getPivotMatrix());
  12375. this.refreshBoundingInfo();
  12376. this._syncSubMeshes();
  12377. }
  12378. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12379. // Methods
  12380. get: function () {
  12381. return this._sourceMesh.receiveShadows;
  12382. },
  12383. enumerable: true,
  12384. configurable: true
  12385. });
  12386. Object.defineProperty(InstancedMesh.prototype, "material", {
  12387. get: function () {
  12388. return this._sourceMesh.material;
  12389. },
  12390. enumerable: true,
  12391. configurable: true
  12392. });
  12393. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12394. get: function () {
  12395. return this._sourceMesh.visibility;
  12396. },
  12397. enumerable: true,
  12398. configurable: true
  12399. });
  12400. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12401. get: function () {
  12402. return this._sourceMesh.skeleton;
  12403. },
  12404. enumerable: true,
  12405. configurable: true
  12406. });
  12407. InstancedMesh.prototype.getTotalVertices = function () {
  12408. return this._sourceMesh.getTotalVertices();
  12409. };
  12410. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12411. get: function () {
  12412. return this._sourceMesh;
  12413. },
  12414. enumerable: true,
  12415. configurable: true
  12416. });
  12417. InstancedMesh.prototype.getVerticesData = function (kind) {
  12418. return this._sourceMesh.getVerticesData(kind);
  12419. };
  12420. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12421. return this._sourceMesh.isVerticesDataPresent(kind);
  12422. };
  12423. InstancedMesh.prototype.getIndices = function () {
  12424. return this._sourceMesh.getIndices();
  12425. };
  12426. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12427. get: function () {
  12428. return this._sourceMesh._positions;
  12429. },
  12430. enumerable: true,
  12431. configurable: true
  12432. });
  12433. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12434. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12435. if (data) {
  12436. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12437. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12438. }
  12439. this._updateBoundingInfo();
  12440. };
  12441. InstancedMesh.prototype._preActivate = function () {
  12442. if (this._currentLOD) {
  12443. this._currentLOD._preActivate();
  12444. }
  12445. };
  12446. InstancedMesh.prototype._activate = function (renderId) {
  12447. if (this._currentLOD) {
  12448. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12449. }
  12450. };
  12451. InstancedMesh.prototype.getLOD = function (camera) {
  12452. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12453. if (this._currentLOD === this.sourceMesh) {
  12454. return this;
  12455. }
  12456. return this._currentLOD;
  12457. };
  12458. InstancedMesh.prototype._syncSubMeshes = function () {
  12459. this.releaseSubMeshes();
  12460. if (this._sourceMesh.subMeshes) {
  12461. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12462. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12463. }
  12464. }
  12465. };
  12466. InstancedMesh.prototype._generatePointsArray = function () {
  12467. return this._sourceMesh._generatePointsArray();
  12468. };
  12469. // Clone
  12470. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12471. var result = this._sourceMesh.createInstance(name);
  12472. // Deep copy
  12473. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12474. // Bounding info
  12475. this.refreshBoundingInfo();
  12476. // Parent
  12477. if (newParent) {
  12478. result.parent = newParent;
  12479. }
  12480. if (!doNotCloneChildren) {
  12481. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12482. var mesh = this.getScene().meshes[index];
  12483. if (mesh.parent === this) {
  12484. mesh.clone(mesh.name, result);
  12485. }
  12486. }
  12487. }
  12488. result.computeWorldMatrix(true);
  12489. return result;
  12490. };
  12491. // Dispoe
  12492. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12493. // Remove from mesh
  12494. var index = this._sourceMesh.instances.indexOf(this);
  12495. this._sourceMesh.instances.splice(index, 1);
  12496. _super.prototype.dispose.call(this, doNotRecurse);
  12497. };
  12498. return InstancedMesh;
  12499. })(BABYLON.AbstractMesh);
  12500. BABYLON.InstancedMesh = InstancedMesh;
  12501. })(BABYLON || (BABYLON = {}));
  12502. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12503. (function (BABYLON) {
  12504. var SubMesh = (function () {
  12505. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12506. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12507. this.materialIndex = materialIndex;
  12508. this.verticesStart = verticesStart;
  12509. this.verticesCount = verticesCount;
  12510. this.indexStart = indexStart;
  12511. this.indexCount = indexCount;
  12512. this._renderId = 0;
  12513. this._mesh = mesh;
  12514. this._renderingMesh = renderingMesh || mesh;
  12515. mesh.subMeshes.push(this);
  12516. this._id = mesh.subMeshes.length - 1;
  12517. if (createBoundingBox) {
  12518. this.refreshBoundingInfo();
  12519. mesh.computeWorldMatrix(true);
  12520. }
  12521. }
  12522. SubMesh.prototype.getBoundingInfo = function () {
  12523. return this._boundingInfo;
  12524. };
  12525. SubMesh.prototype.getMesh = function () {
  12526. return this._mesh;
  12527. };
  12528. SubMesh.prototype.getRenderingMesh = function () {
  12529. return this._renderingMesh;
  12530. };
  12531. SubMesh.prototype.getMaterial = function () {
  12532. var rootMaterial = this._renderingMesh.material;
  12533. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12534. var multiMaterial = rootMaterial;
  12535. return multiMaterial.getSubMaterial(this.materialIndex);
  12536. }
  12537. if (!rootMaterial) {
  12538. return this._mesh.getScene().defaultMaterial;
  12539. }
  12540. return rootMaterial;
  12541. };
  12542. // Methods
  12543. SubMesh.prototype.refreshBoundingInfo = function () {
  12544. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12545. if (!data) {
  12546. this._boundingInfo = this._mesh._boundingInfo;
  12547. return;
  12548. }
  12549. var indices = this._renderingMesh.getIndices();
  12550. var extend;
  12551. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12552. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12553. }
  12554. else {
  12555. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12556. }
  12557. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12558. };
  12559. SubMesh.prototype._checkCollision = function (collider) {
  12560. return this._boundingInfo._checkCollision(collider);
  12561. };
  12562. SubMesh.prototype.updateBoundingInfo = function (world) {
  12563. if (!this._boundingInfo) {
  12564. this.refreshBoundingInfo();
  12565. }
  12566. this._boundingInfo._update(world);
  12567. };
  12568. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12569. return this._boundingInfo.isInFrustum(frustumPlanes);
  12570. };
  12571. SubMesh.prototype.render = function () {
  12572. this._renderingMesh.render(this);
  12573. };
  12574. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12575. if (!this._linesIndexBuffer) {
  12576. var linesIndices = [];
  12577. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12578. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12579. }
  12580. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12581. this.linesIndexCount = linesIndices.length;
  12582. }
  12583. return this._linesIndexBuffer;
  12584. };
  12585. SubMesh.prototype.canIntersects = function (ray) {
  12586. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12587. };
  12588. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12589. var intersectInfo = null;
  12590. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12591. var p0 = positions[indices[index]];
  12592. var p1 = positions[indices[index + 1]];
  12593. var p2 = positions[indices[index + 2]];
  12594. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12595. if (currentIntersectInfo) {
  12596. if (currentIntersectInfo.distance < 0) {
  12597. continue;
  12598. }
  12599. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12600. intersectInfo = currentIntersectInfo;
  12601. intersectInfo.faceId = index / 3;
  12602. if (fastCheck) {
  12603. break;
  12604. }
  12605. }
  12606. }
  12607. }
  12608. return intersectInfo;
  12609. };
  12610. // Clone
  12611. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12612. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12613. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12614. return result;
  12615. };
  12616. // Dispose
  12617. SubMesh.prototype.dispose = function () {
  12618. if (this._linesIndexBuffer) {
  12619. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12620. this._linesIndexBuffer = null;
  12621. }
  12622. // Remove from mesh
  12623. var index = this._mesh.subMeshes.indexOf(this);
  12624. this._mesh.subMeshes.splice(index, 1);
  12625. };
  12626. // Statics
  12627. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12628. var minVertexIndex = Number.MAX_VALUE;
  12629. var maxVertexIndex = -Number.MAX_VALUE;
  12630. renderingMesh = renderingMesh || mesh;
  12631. var indices = renderingMesh.getIndices();
  12632. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12633. var vertexIndex = indices[index];
  12634. if (vertexIndex < minVertexIndex)
  12635. minVertexIndex = vertexIndex;
  12636. if (vertexIndex > maxVertexIndex)
  12637. maxVertexIndex = vertexIndex;
  12638. }
  12639. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12640. };
  12641. return SubMesh;
  12642. })();
  12643. BABYLON.SubMesh = SubMesh;
  12644. })(BABYLON || (BABYLON = {}));
  12645. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12646. (function (BABYLON) {
  12647. var BaseTexture = (function () {
  12648. function BaseTexture(scene) {
  12649. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12650. this.hasAlpha = false;
  12651. this.getAlphaFromRGB = false;
  12652. this.level = 1;
  12653. this.isCube = false;
  12654. this.isRenderTarget = false;
  12655. this.animations = new Array();
  12656. this.coordinatesIndex = 0;
  12657. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12658. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12659. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12660. this.anisotropicFilteringLevel = 4;
  12661. this._scene = scene;
  12662. this._scene.textures.push(this);
  12663. }
  12664. BaseTexture.prototype.getScene = function () {
  12665. return this._scene;
  12666. };
  12667. BaseTexture.prototype.getTextureMatrix = function () {
  12668. return null;
  12669. };
  12670. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12671. return null;
  12672. };
  12673. BaseTexture.prototype.getInternalTexture = function () {
  12674. return this._texture;
  12675. };
  12676. BaseTexture.prototype.isReady = function () {
  12677. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12678. return true;
  12679. }
  12680. if (this._texture) {
  12681. return this._texture.isReady;
  12682. }
  12683. return false;
  12684. };
  12685. BaseTexture.prototype.getSize = function () {
  12686. if (this._texture._width) {
  12687. return { width: this._texture._width, height: this._texture._height };
  12688. }
  12689. if (this._texture._size) {
  12690. return { width: this._texture._size, height: this._texture._size };
  12691. }
  12692. return { width: 0, height: 0 };
  12693. };
  12694. BaseTexture.prototype.getBaseSize = function () {
  12695. if (!this.isReady())
  12696. return { width: 0, height: 0 };
  12697. if (this._texture._size) {
  12698. return { width: this._texture._size, height: this._texture._size };
  12699. }
  12700. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12701. };
  12702. BaseTexture.prototype.scale = function (ratio) {
  12703. };
  12704. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12705. get: function () {
  12706. return false;
  12707. },
  12708. enumerable: true,
  12709. configurable: true
  12710. });
  12711. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12712. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12713. for (var index = 0; index < texturesCache.length; index++) {
  12714. var texturesCacheEntry = texturesCache[index];
  12715. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12716. texturesCache.splice(index, 1);
  12717. return;
  12718. }
  12719. }
  12720. };
  12721. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12722. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12723. for (var index = 0; index < texturesCache.length; index++) {
  12724. var texturesCacheEntry = texturesCache[index];
  12725. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12726. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12727. texturesCacheEntry.references++;
  12728. return texturesCacheEntry;
  12729. }
  12730. }
  12731. }
  12732. return null;
  12733. };
  12734. BaseTexture.prototype.delayLoad = function () {
  12735. };
  12736. BaseTexture.prototype.releaseInternalTexture = function () {
  12737. if (!this._texture) {
  12738. return;
  12739. }
  12740. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12741. this._texture.references--;
  12742. // Final reference ?
  12743. if (this._texture.references === 0) {
  12744. var index = texturesCache.indexOf(this._texture);
  12745. texturesCache.splice(index, 1);
  12746. this._scene.getEngine()._releaseTexture(this._texture);
  12747. delete this._texture;
  12748. }
  12749. };
  12750. BaseTexture.prototype.clone = function () {
  12751. return null;
  12752. };
  12753. BaseTexture.prototype.dispose = function () {
  12754. // Remove from scene
  12755. var index = this._scene.textures.indexOf(this);
  12756. if (index >= 0) {
  12757. this._scene.textures.splice(index, 1);
  12758. }
  12759. if (this._texture === undefined) {
  12760. return;
  12761. }
  12762. this.releaseInternalTexture();
  12763. // Callback
  12764. if (this.onDispose) {
  12765. this.onDispose();
  12766. }
  12767. };
  12768. return BaseTexture;
  12769. })();
  12770. BABYLON.BaseTexture = BaseTexture;
  12771. })(BABYLON || (BABYLON = {}));
  12772. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12773. (function (BABYLON) {
  12774. var RenderingGroup = (function () {
  12775. function RenderingGroup(index, scene) {
  12776. this.index = index;
  12777. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12778. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12779. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12780. this._scene = scene;
  12781. }
  12782. RenderingGroup.prototype.render = function (customRenderFunction) {
  12783. if (customRenderFunction) {
  12784. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12785. return true;
  12786. }
  12787. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12788. return false;
  12789. }
  12790. var engine = this._scene.getEngine();
  12791. // Opaque
  12792. var subIndex;
  12793. var submesh;
  12794. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12795. submesh = this._opaqueSubMeshes.data[subIndex];
  12796. submesh.render();
  12797. }
  12798. // Alpha test
  12799. engine.setAlphaTesting(true);
  12800. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12801. submesh = this._alphaTestSubMeshes.data[subIndex];
  12802. submesh.render();
  12803. }
  12804. engine.setAlphaTesting(false);
  12805. // Transparent
  12806. if (this._transparentSubMeshes.length) {
  12807. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12808. submesh = this._transparentSubMeshes.data[subIndex];
  12809. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12810. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12811. }
  12812. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12813. sortedArray.sort(function (a, b) {
  12814. // Alpha index first
  12815. if (a._alphaIndex > b._alphaIndex) {
  12816. return 1;
  12817. }
  12818. if (a._alphaIndex < b._alphaIndex) {
  12819. return -1;
  12820. }
  12821. // Then distance to camera
  12822. if (a._distanceToCamera < b._distanceToCamera) {
  12823. return 1;
  12824. }
  12825. if (a._distanceToCamera > b._distanceToCamera) {
  12826. return -1;
  12827. }
  12828. return 0;
  12829. });
  12830. // Rendering
  12831. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12832. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12833. submesh = sortedArray[subIndex];
  12834. submesh.render();
  12835. }
  12836. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12837. }
  12838. return true;
  12839. };
  12840. RenderingGroup.prototype.prepare = function () {
  12841. this._opaqueSubMeshes.reset();
  12842. this._transparentSubMeshes.reset();
  12843. this._alphaTestSubMeshes.reset();
  12844. };
  12845. RenderingGroup.prototype.dispatch = function (subMesh) {
  12846. var material = subMesh.getMaterial();
  12847. var mesh = subMesh.getMesh();
  12848. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12849. this._transparentSubMeshes.push(subMesh);
  12850. }
  12851. else if (material.needAlphaTesting()) {
  12852. this._alphaTestSubMeshes.push(subMesh);
  12853. }
  12854. else {
  12855. this._opaqueSubMeshes.push(subMesh); // Opaque
  12856. }
  12857. };
  12858. return RenderingGroup;
  12859. })();
  12860. BABYLON.RenderingGroup = RenderingGroup;
  12861. })(BABYLON || (BABYLON = {}));
  12862. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12863. (function (BABYLON) {
  12864. var RenderingManager = (function () {
  12865. function RenderingManager(scene) {
  12866. this._renderingGroups = new Array();
  12867. this._scene = scene;
  12868. }
  12869. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12870. if (this._scene._activeParticleSystems.length === 0) {
  12871. return;
  12872. }
  12873. // Particles
  12874. var beforeParticlesDate = BABYLON.Tools.Now;
  12875. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12876. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12877. if (particleSystem.renderingGroupId !== index) {
  12878. continue;
  12879. }
  12880. this._clearDepthBuffer();
  12881. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12882. this._scene._activeParticles += particleSystem.render();
  12883. }
  12884. }
  12885. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12886. };
  12887. RenderingManager.prototype._renderSprites = function (index) {
  12888. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12889. return;
  12890. }
  12891. // Sprites
  12892. var beforeSpritessDate = BABYLON.Tools.Now;
  12893. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12894. var spriteManager = this._scene.spriteManagers[id];
  12895. if (spriteManager.renderingGroupId === index) {
  12896. this._clearDepthBuffer();
  12897. spriteManager.render();
  12898. }
  12899. }
  12900. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12901. };
  12902. RenderingManager.prototype._clearDepthBuffer = function () {
  12903. if (this._depthBufferAlreadyCleaned) {
  12904. return;
  12905. }
  12906. this._scene.getEngine().clear(0, false, true);
  12907. this._depthBufferAlreadyCleaned = true;
  12908. };
  12909. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12910. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12911. this._depthBufferAlreadyCleaned = false;
  12912. var renderingGroup = this._renderingGroups[index];
  12913. var needToStepBack = false;
  12914. if (renderingGroup) {
  12915. this._clearDepthBuffer();
  12916. if (!renderingGroup.render(customRenderFunction)) {
  12917. this._renderingGroups.splice(index, 1);
  12918. needToStepBack = true;
  12919. }
  12920. }
  12921. if (renderSprites) {
  12922. this._renderSprites(index);
  12923. }
  12924. if (renderParticles) {
  12925. this._renderParticles(index, activeMeshes);
  12926. }
  12927. if (needToStepBack) {
  12928. index--;
  12929. }
  12930. }
  12931. };
  12932. RenderingManager.prototype.reset = function () {
  12933. for (var index in this._renderingGroups) {
  12934. var renderingGroup = this._renderingGroups[index];
  12935. renderingGroup.prepare();
  12936. }
  12937. };
  12938. RenderingManager.prototype.dispatch = function (subMesh) {
  12939. var mesh = subMesh.getMesh();
  12940. var renderingGroupId = mesh.renderingGroupId || 0;
  12941. if (!this._renderingGroups[renderingGroupId]) {
  12942. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12943. }
  12944. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12945. };
  12946. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12947. return RenderingManager;
  12948. })();
  12949. BABYLON.RenderingManager = RenderingManager;
  12950. })(BABYLON || (BABYLON = {}));
  12951. //# sourceMappingURL=babylon.renderingManager.js.map
  12952. var BABYLON;
  12953. (function (BABYLON) {
  12954. var Texture = (function (_super) {
  12955. __extends(Texture, _super);
  12956. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12957. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12958. if (onLoad === void 0) { onLoad = null; }
  12959. if (onError === void 0) { onError = null; }
  12960. if (buffer === void 0) { buffer = null; }
  12961. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12962. _super.call(this, scene);
  12963. this.uOffset = 0;
  12964. this.vOffset = 0;
  12965. this.uScale = 1.0;
  12966. this.vScale = 1.0;
  12967. this.uAng = 0;
  12968. this.vAng = 0;
  12969. this.wAng = 0;
  12970. this.name = url;
  12971. this.url = url;
  12972. this._noMipmap = noMipmap;
  12973. this._invertY = invertY;
  12974. this._samplingMode = samplingMode;
  12975. this._buffer = buffer;
  12976. this._deleteBuffer = deleteBuffer;
  12977. if (!url) {
  12978. return;
  12979. }
  12980. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12981. if (!this._texture) {
  12982. if (!scene.useDelayedTextureLoading) {
  12983. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12984. if (deleteBuffer) {
  12985. delete this._buffer;
  12986. }
  12987. }
  12988. else {
  12989. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12990. }
  12991. }
  12992. }
  12993. Texture.prototype.delayLoad = function () {
  12994. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12995. return;
  12996. }
  12997. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12998. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12999. if (!this._texture) {
  13000. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  13001. if (this._deleteBuffer) {
  13002. delete this._buffer;
  13003. }
  13004. }
  13005. };
  13006. Texture.prototype.updateSamplingMode = function (samplingMode) {
  13007. if (!this._texture) {
  13008. return;
  13009. }
  13010. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  13011. };
  13012. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  13013. x -= this.uOffset + 0.5;
  13014. y -= this.vOffset + 0.5;
  13015. z -= 0.5;
  13016. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  13017. t.x *= this.uScale;
  13018. t.y *= this.vScale;
  13019. t.x += 0.5;
  13020. t.y += 0.5;
  13021. t.z += 0.5;
  13022. };
  13023. Texture.prototype.getTextureMatrix = function () {
  13024. 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) {
  13025. return this._cachedTextureMatrix;
  13026. }
  13027. this._cachedUOffset = this.uOffset;
  13028. this._cachedVOffset = this.vOffset;
  13029. this._cachedUScale = this.uScale;
  13030. this._cachedVScale = this.vScale;
  13031. this._cachedUAng = this.uAng;
  13032. this._cachedVAng = this.vAng;
  13033. this._cachedWAng = this.wAng;
  13034. if (!this._cachedTextureMatrix) {
  13035. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13036. this._rowGenerationMatrix = new BABYLON.Matrix();
  13037. this._t0 = BABYLON.Vector3.Zero();
  13038. this._t1 = BABYLON.Vector3.Zero();
  13039. this._t2 = BABYLON.Vector3.Zero();
  13040. }
  13041. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  13042. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  13043. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  13044. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  13045. this._t1.subtractInPlace(this._t0);
  13046. this._t2.subtractInPlace(this._t0);
  13047. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13048. this._cachedTextureMatrix.m[0] = this._t1.x;
  13049. this._cachedTextureMatrix.m[1] = this._t1.y;
  13050. this._cachedTextureMatrix.m[2] = this._t1.z;
  13051. this._cachedTextureMatrix.m[4] = this._t2.x;
  13052. this._cachedTextureMatrix.m[5] = this._t2.y;
  13053. this._cachedTextureMatrix.m[6] = this._t2.z;
  13054. this._cachedTextureMatrix.m[8] = this._t0.x;
  13055. this._cachedTextureMatrix.m[9] = this._t0.y;
  13056. this._cachedTextureMatrix.m[10] = this._t0.z;
  13057. return this._cachedTextureMatrix;
  13058. };
  13059. Texture.prototype.getReflectionTextureMatrix = function () {
  13060. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  13061. return this._cachedTextureMatrix;
  13062. }
  13063. if (!this._cachedTextureMatrix) {
  13064. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13065. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  13066. }
  13067. this._cachedCoordinatesMode = this.coordinatesMode;
  13068. switch (this.coordinatesMode) {
  13069. case Texture.SPHERICAL_MODE:
  13070. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13071. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  13072. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  13073. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  13074. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  13075. break;
  13076. case Texture.PLANAR_MODE:
  13077. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13078. this._cachedTextureMatrix[0] = this.uScale;
  13079. this._cachedTextureMatrix[5] = this.vScale;
  13080. this._cachedTextureMatrix[12] = this.uOffset;
  13081. this._cachedTextureMatrix[13] = this.vOffset;
  13082. break;
  13083. case Texture.PROJECTION_MODE:
  13084. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  13085. this._projectionModeMatrix.m[0] = 0.5;
  13086. this._projectionModeMatrix.m[5] = -0.5;
  13087. this._projectionModeMatrix.m[10] = 0.0;
  13088. this._projectionModeMatrix.m[12] = 0.5;
  13089. this._projectionModeMatrix.m[13] = 0.5;
  13090. this._projectionModeMatrix.m[14] = 1.0;
  13091. this._projectionModeMatrix.m[15] = 1.0;
  13092. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  13093. break;
  13094. default:
  13095. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13096. break;
  13097. }
  13098. return this._cachedTextureMatrix;
  13099. };
  13100. Texture.prototype.clone = function () {
  13101. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  13102. // Base texture
  13103. newTexture.hasAlpha = this.hasAlpha;
  13104. newTexture.level = this.level;
  13105. newTexture.wrapU = this.wrapU;
  13106. newTexture.wrapV = this.wrapV;
  13107. newTexture.coordinatesIndex = this.coordinatesIndex;
  13108. newTexture.coordinatesMode = this.coordinatesMode;
  13109. // Texture
  13110. newTexture.uOffset = this.uOffset;
  13111. newTexture.vOffset = this.vOffset;
  13112. newTexture.uScale = this.uScale;
  13113. newTexture.vScale = this.vScale;
  13114. newTexture.uAng = this.uAng;
  13115. newTexture.vAng = this.vAng;
  13116. newTexture.wAng = this.wAng;
  13117. return newTexture;
  13118. };
  13119. // Statics
  13120. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  13121. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  13122. if (onLoad === void 0) { onLoad = null; }
  13123. if (onError === void 0) { onError = null; }
  13124. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  13125. };
  13126. // Constants
  13127. Texture.NEAREST_SAMPLINGMODE = 1;
  13128. Texture.BILINEAR_SAMPLINGMODE = 2;
  13129. Texture.TRILINEAR_SAMPLINGMODE = 3;
  13130. Texture.EXPLICIT_MODE = 0;
  13131. Texture.SPHERICAL_MODE = 1;
  13132. Texture.PLANAR_MODE = 2;
  13133. Texture.CUBIC_MODE = 3;
  13134. Texture.PROJECTION_MODE = 4;
  13135. Texture.SKYBOX_MODE = 5;
  13136. Texture.CLAMP_ADDRESSMODE = 0;
  13137. Texture.WRAP_ADDRESSMODE = 1;
  13138. Texture.MIRROR_ADDRESSMODE = 2;
  13139. return Texture;
  13140. })(BABYLON.BaseTexture);
  13141. BABYLON.Texture = Texture;
  13142. })(BABYLON || (BABYLON = {}));
  13143. //# sourceMappingURL=babylon.texture.js.map
  13144. var BABYLON;
  13145. (function (BABYLON) {
  13146. var CubeTexture = (function (_super) {
  13147. __extends(CubeTexture, _super);
  13148. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  13149. _super.call(this, scene);
  13150. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  13151. this.name = rootUrl;
  13152. this.url = rootUrl;
  13153. this._noMipmap = noMipmap;
  13154. this.hasAlpha = false;
  13155. this._texture = this._getFromCache(rootUrl, noMipmap);
  13156. if (!extensions) {
  13157. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  13158. }
  13159. this._extensions = extensions;
  13160. if (!this._texture) {
  13161. if (!scene.useDelayedTextureLoading) {
  13162. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  13163. }
  13164. else {
  13165. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13166. }
  13167. }
  13168. this.isCube = true;
  13169. this._textureMatrix = BABYLON.Matrix.Identity();
  13170. }
  13171. CubeTexture.prototype.clone = function () {
  13172. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  13173. // Base texture
  13174. newTexture.level = this.level;
  13175. newTexture.wrapU = this.wrapU;
  13176. newTexture.wrapV = this.wrapV;
  13177. newTexture.coordinatesIndex = this.coordinatesIndex;
  13178. newTexture.coordinatesMode = this.coordinatesMode;
  13179. return newTexture;
  13180. };
  13181. // Methods
  13182. CubeTexture.prototype.delayLoad = function () {
  13183. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13184. return;
  13185. }
  13186. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13187. this._texture = this._getFromCache(this.url, this._noMipmap);
  13188. if (!this._texture) {
  13189. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  13190. }
  13191. };
  13192. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  13193. return this._textureMatrix;
  13194. };
  13195. return CubeTexture;
  13196. })(BABYLON.BaseTexture);
  13197. BABYLON.CubeTexture = CubeTexture;
  13198. })(BABYLON || (BABYLON = {}));
  13199. //# sourceMappingURL=babylon.cubeTexture.js.map
  13200. var BABYLON;
  13201. (function (BABYLON) {
  13202. var RenderTargetTexture = (function (_super) {
  13203. __extends(RenderTargetTexture, _super);
  13204. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  13205. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  13206. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  13207. _super.call(this, null, scene, !generateMipMaps);
  13208. this.renderList = new Array();
  13209. this.renderParticles = true;
  13210. this.renderSprites = false;
  13211. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  13212. this._currentRefreshId = -1;
  13213. this._refreshRate = 1;
  13214. this.name = name;
  13215. this.isRenderTarget = true;
  13216. this._size = size;
  13217. this._generateMipMaps = generateMipMaps;
  13218. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  13219. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  13220. // Rendering groups
  13221. this._renderingManager = new BABYLON.RenderingManager(scene);
  13222. }
  13223. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  13224. this._currentRefreshId = -1;
  13225. };
  13226. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  13227. get: function () {
  13228. return this._refreshRate;
  13229. },
  13230. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13231. set: function (value) {
  13232. this._refreshRate = value;
  13233. this.resetRefreshCounter();
  13234. },
  13235. enumerable: true,
  13236. configurable: true
  13237. });
  13238. RenderTargetTexture.prototype._shouldRender = function () {
  13239. if (this._currentRefreshId === -1) {
  13240. this._currentRefreshId = 1;
  13241. return true;
  13242. }
  13243. if (this.refreshRate === this._currentRefreshId) {
  13244. this._currentRefreshId = 1;
  13245. return true;
  13246. }
  13247. this._currentRefreshId++;
  13248. return false;
  13249. };
  13250. RenderTargetTexture.prototype.isReady = function () {
  13251. if (!this.getScene().renderTargetsEnabled) {
  13252. return false;
  13253. }
  13254. return _super.prototype.isReady.call(this);
  13255. };
  13256. RenderTargetTexture.prototype.getRenderSize = function () {
  13257. return this._size;
  13258. };
  13259. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  13260. get: function () {
  13261. return true;
  13262. },
  13263. enumerable: true,
  13264. configurable: true
  13265. });
  13266. RenderTargetTexture.prototype.scale = function (ratio) {
  13267. var newSize = this._size * ratio;
  13268. this.resize(newSize, this._generateMipMaps);
  13269. };
  13270. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  13271. this.releaseInternalTexture();
  13272. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13273. };
  13274. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  13275. var scene = this.getScene();
  13276. var engine = scene.getEngine();
  13277. if (this._waitingRenderList) {
  13278. this.renderList = [];
  13279. for (var index = 0; index < this._waitingRenderList.length; index++) {
  13280. var id = this._waitingRenderList[index];
  13281. this.renderList.push(scene.getMeshByID(id));
  13282. }
  13283. delete this._waitingRenderList;
  13284. }
  13285. if (this.renderList && this.renderList.length === 0) {
  13286. return;
  13287. }
  13288. // Bind
  13289. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  13290. engine.bindFramebuffer(this._texture);
  13291. }
  13292. this._renderingManager.reset();
  13293. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  13294. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  13295. var mesh = currentRenderList[meshIndex];
  13296. if (mesh) {
  13297. if (!mesh.isReady()) {
  13298. // Reset _currentRefreshId
  13299. this.resetRefreshCounter();
  13300. continue;
  13301. }
  13302. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  13303. mesh._activate(scene.getRenderId());
  13304. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13305. var subMesh = mesh.subMeshes[subIndex];
  13306. scene._activeVertices += subMesh.indexCount;
  13307. this._renderingManager.dispatch(subMesh);
  13308. }
  13309. }
  13310. }
  13311. }
  13312. if (this.onBeforeRender) {
  13313. this.onBeforeRender();
  13314. }
  13315. // Clear
  13316. if (this.onClear) {
  13317. this.onClear(engine);
  13318. }
  13319. else {
  13320. engine.clear(scene.clearColor, true, true);
  13321. }
  13322. if (!this._doNotChangeAspectRatio) {
  13323. scene.updateTransformMatrix(true);
  13324. }
  13325. // Render
  13326. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  13327. if (useCameraPostProcess) {
  13328. scene.postProcessManager._finalizeFrame(false, this._texture);
  13329. }
  13330. if (!this._doNotChangeAspectRatio) {
  13331. scene.updateTransformMatrix(true);
  13332. }
  13333. if (this.onAfterRender) {
  13334. this.onAfterRender();
  13335. }
  13336. // Dump ?
  13337. if (dumpForDebug) {
  13338. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  13339. }
  13340. // Unbind
  13341. engine.unBindFramebuffer(this._texture);
  13342. if (this.onAfterUnbind) {
  13343. this.onAfterUnbind();
  13344. }
  13345. };
  13346. RenderTargetTexture.prototype.clone = function () {
  13347. var textureSize = this.getSize();
  13348. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13349. // Base texture
  13350. newTexture.hasAlpha = this.hasAlpha;
  13351. newTexture.level = this.level;
  13352. // RenderTarget Texture
  13353. newTexture.coordinatesMode = this.coordinatesMode;
  13354. newTexture.renderList = this.renderList.slice(0);
  13355. return newTexture;
  13356. };
  13357. return RenderTargetTexture;
  13358. })(BABYLON.Texture);
  13359. BABYLON.RenderTargetTexture = RenderTargetTexture;
  13360. })(BABYLON || (BABYLON = {}));
  13361. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  13362. var BABYLON;
  13363. (function (BABYLON) {
  13364. var ProceduralTexture = (function (_super) {
  13365. __extends(ProceduralTexture, _super);
  13366. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  13367. if (generateMipMaps === void 0) { generateMipMaps = true; }
  13368. _super.call(this, null, scene, !generateMipMaps);
  13369. this._currentRefreshId = -1;
  13370. this._refreshRate = 1;
  13371. this._vertexDeclaration = [2];
  13372. this._vertexStrideSize = 2 * 4;
  13373. this._uniforms = new Array();
  13374. this._samplers = new Array();
  13375. this._textures = new Array();
  13376. this._floats = new Array();
  13377. this._floatsArrays = {};
  13378. this._colors3 = new Array();
  13379. this._colors4 = new Array();
  13380. this._vectors2 = new Array();
  13381. this._vectors3 = new Array();
  13382. this._matrices = new Array();
  13383. this._fallbackTextureUsed = false;
  13384. scene._proceduralTextures.push(this);
  13385. this.name = name;
  13386. this.isRenderTarget = true;
  13387. this._size = size;
  13388. this._generateMipMaps = generateMipMaps;
  13389. this.setFragment(fragment);
  13390. this._fallbackTexture = fallbackTexture;
  13391. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  13392. // VBO
  13393. var vertices = [];
  13394. vertices.push(1, 1);
  13395. vertices.push(-1, 1);
  13396. vertices.push(-1, -1);
  13397. vertices.push(1, -1);
  13398. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13399. // Indices
  13400. var indices = [];
  13401. indices.push(0);
  13402. indices.push(1);
  13403. indices.push(2);
  13404. indices.push(0);
  13405. indices.push(2);
  13406. indices.push(3);
  13407. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13408. }
  13409. ProceduralTexture.prototype.reset = function () {
  13410. if (this._effect === undefined) {
  13411. return;
  13412. }
  13413. var engine = this.getScene().getEngine();
  13414. engine._releaseEffect(this._effect);
  13415. };
  13416. ProceduralTexture.prototype.isReady = function () {
  13417. var _this = this;
  13418. var engine = this.getScene().getEngine();
  13419. var shaders;
  13420. if (!this._fragment) {
  13421. return false;
  13422. }
  13423. if (this._fallbackTextureUsed) {
  13424. return true;
  13425. }
  13426. if (this._fragment.fragmentElement !== undefined) {
  13427. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  13428. }
  13429. else {
  13430. shaders = { vertex: "procedural", fragment: this._fragment };
  13431. }
  13432. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  13433. _this.releaseInternalTexture();
  13434. if (_this._fallbackTexture) {
  13435. _this._texture = _this._fallbackTexture._texture;
  13436. _this._texture.references++;
  13437. }
  13438. _this._fallbackTextureUsed = true;
  13439. });
  13440. return this._effect.isReady();
  13441. };
  13442. ProceduralTexture.prototype.resetRefreshCounter = function () {
  13443. this._currentRefreshId = -1;
  13444. };
  13445. ProceduralTexture.prototype.setFragment = function (fragment) {
  13446. this._fragment = fragment;
  13447. };
  13448. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  13449. get: function () {
  13450. return this._refreshRate;
  13451. },
  13452. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13453. set: function (value) {
  13454. this._refreshRate = value;
  13455. this.resetRefreshCounter();
  13456. },
  13457. enumerable: true,
  13458. configurable: true
  13459. });
  13460. ProceduralTexture.prototype._shouldRender = function () {
  13461. if (!this.isReady() || !this._texture) {
  13462. return false;
  13463. }
  13464. if (this._fallbackTextureUsed) {
  13465. return false;
  13466. }
  13467. if (this._currentRefreshId === -1) {
  13468. this._currentRefreshId = 1;
  13469. return true;
  13470. }
  13471. if (this.refreshRate === this._currentRefreshId) {
  13472. this._currentRefreshId = 1;
  13473. return true;
  13474. }
  13475. this._currentRefreshId++;
  13476. return false;
  13477. };
  13478. ProceduralTexture.prototype.getRenderSize = function () {
  13479. return this._size;
  13480. };
  13481. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13482. if (this._fallbackTextureUsed) {
  13483. return;
  13484. }
  13485. this.releaseInternalTexture();
  13486. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13487. };
  13488. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13489. if (this._uniforms.indexOf(uniformName) === -1) {
  13490. this._uniforms.push(uniformName);
  13491. }
  13492. };
  13493. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13494. if (this._samplers.indexOf(name) === -1) {
  13495. this._samplers.push(name);
  13496. }
  13497. this._textures[name] = texture;
  13498. return this;
  13499. };
  13500. ProceduralTexture.prototype.setFloat = function (name, value) {
  13501. this._checkUniform(name);
  13502. this._floats[name] = value;
  13503. return this;
  13504. };
  13505. ProceduralTexture.prototype.setFloats = function (name, value) {
  13506. this._checkUniform(name);
  13507. this._floatsArrays[name] = value;
  13508. return this;
  13509. };
  13510. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13511. this._checkUniform(name);
  13512. this._colors3[name] = value;
  13513. return this;
  13514. };
  13515. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13516. this._checkUniform(name);
  13517. this._colors4[name] = value;
  13518. return this;
  13519. };
  13520. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13521. this._checkUniform(name);
  13522. this._vectors2[name] = value;
  13523. return this;
  13524. };
  13525. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13526. this._checkUniform(name);
  13527. this._vectors3[name] = value;
  13528. return this;
  13529. };
  13530. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13531. this._checkUniform(name);
  13532. this._matrices[name] = value;
  13533. return this;
  13534. };
  13535. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13536. var scene = this.getScene();
  13537. var engine = scene.getEngine();
  13538. engine.bindFramebuffer(this._texture);
  13539. // Clear
  13540. engine.clear(scene.clearColor, true, true);
  13541. // Render
  13542. engine.enableEffect(this._effect);
  13543. engine.setState(false);
  13544. for (var name in this._textures) {
  13545. this._effect.setTexture(name, this._textures[name]);
  13546. }
  13547. for (name in this._floats) {
  13548. this._effect.setFloat(name, this._floats[name]);
  13549. }
  13550. for (name in this._floatsArrays) {
  13551. this._effect.setArray(name, this._floatsArrays[name]);
  13552. }
  13553. for (name in this._colors3) {
  13554. this._effect.setColor3(name, this._colors3[name]);
  13555. }
  13556. for (name in this._colors4) {
  13557. var color = this._colors4[name];
  13558. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13559. }
  13560. for (name in this._vectors2) {
  13561. this._effect.setVector2(name, this._vectors2[name]);
  13562. }
  13563. for (name in this._vectors3) {
  13564. this._effect.setVector3(name, this._vectors3[name]);
  13565. }
  13566. for (name in this._matrices) {
  13567. this._effect.setMatrix(name, this._matrices[name]);
  13568. }
  13569. // VBOs
  13570. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13571. // Draw order
  13572. engine.draw(true, 0, 6);
  13573. // Unbind
  13574. engine.unBindFramebuffer(this._texture);
  13575. };
  13576. ProceduralTexture.prototype.clone = function () {
  13577. var textureSize = this.getSize();
  13578. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13579. // Base texture
  13580. newTexture.hasAlpha = this.hasAlpha;
  13581. newTexture.level = this.level;
  13582. // RenderTarget Texture
  13583. newTexture.coordinatesMode = this.coordinatesMode;
  13584. return newTexture;
  13585. };
  13586. ProceduralTexture.prototype.dispose = function () {
  13587. var index = this.getScene()._proceduralTextures.indexOf(this);
  13588. if (index >= 0) {
  13589. this.getScene()._proceduralTextures.splice(index, 1);
  13590. }
  13591. _super.prototype.dispose.call(this);
  13592. };
  13593. return ProceduralTexture;
  13594. })(BABYLON.Texture);
  13595. BABYLON.ProceduralTexture = ProceduralTexture;
  13596. })(BABYLON || (BABYLON = {}));
  13597. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13598. var BABYLON;
  13599. (function (BABYLON) {
  13600. var WoodProceduralTexture = (function (_super) {
  13601. __extends(WoodProceduralTexture, _super);
  13602. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13603. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13604. this._ampScale = 100.0;
  13605. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13606. this.updateShaderUniforms();
  13607. this.refreshRate = 0;
  13608. }
  13609. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13610. this.setFloat("ampScale", this._ampScale);
  13611. this.setColor3("woodColor", this._woodColor);
  13612. };
  13613. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13614. get: function () {
  13615. return this._ampScale;
  13616. },
  13617. set: function (value) {
  13618. this._ampScale = value;
  13619. this.updateShaderUniforms();
  13620. },
  13621. enumerable: true,
  13622. configurable: true
  13623. });
  13624. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13625. get: function () {
  13626. return this._woodColor;
  13627. },
  13628. set: function (value) {
  13629. this._woodColor = value;
  13630. this.updateShaderUniforms();
  13631. },
  13632. enumerable: true,
  13633. configurable: true
  13634. });
  13635. return WoodProceduralTexture;
  13636. })(BABYLON.ProceduralTexture);
  13637. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13638. var FireProceduralTexture = (function (_super) {
  13639. __extends(FireProceduralTexture, _super);
  13640. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13641. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13642. this._time = 0.0;
  13643. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13644. this._autoGenerateTime = true;
  13645. this._alphaThreshold = 0.5;
  13646. this._fireColors = FireProceduralTexture.RedFireColors;
  13647. this.updateShaderUniforms();
  13648. this.refreshRate = 1;
  13649. }
  13650. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13651. this.setFloat("time", this._time);
  13652. this.setVector2("speed", this._speed);
  13653. this.setColor3("c1", this._fireColors[0]);
  13654. this.setColor3("c2", this._fireColors[1]);
  13655. this.setColor3("c3", this._fireColors[2]);
  13656. this.setColor3("c4", this._fireColors[3]);
  13657. this.setColor3("c5", this._fireColors[4]);
  13658. this.setColor3("c6", this._fireColors[5]);
  13659. this.setFloat("alphaThreshold", this._alphaThreshold);
  13660. };
  13661. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13662. if (this._autoGenerateTime) {
  13663. this._time += this.getScene().getAnimationRatio() * 0.03;
  13664. this.updateShaderUniforms();
  13665. }
  13666. _super.prototype.render.call(this, useCameraPostProcess);
  13667. };
  13668. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13669. get: function () {
  13670. return [
  13671. new BABYLON.Color3(0.5, 0.0, 1.0),
  13672. new BABYLON.Color3(0.9, 0.0, 1.0),
  13673. new BABYLON.Color3(0.2, 0.0, 1.0),
  13674. new BABYLON.Color3(1.0, 0.9, 1.0),
  13675. new BABYLON.Color3(0.1, 0.1, 1.0),
  13676. new BABYLON.Color3(0.9, 0.9, 1.0)
  13677. ];
  13678. },
  13679. enumerable: true,
  13680. configurable: true
  13681. });
  13682. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13683. get: function () {
  13684. return [
  13685. new BABYLON.Color3(0.5, 1.0, 0.0),
  13686. new BABYLON.Color3(0.5, 1.0, 0.0),
  13687. new BABYLON.Color3(0.3, 0.4, 0.0),
  13688. new BABYLON.Color3(0.5, 1.0, 0.0),
  13689. new BABYLON.Color3(0.2, 0.0, 0.0),
  13690. new BABYLON.Color3(0.5, 1.0, 0.0)
  13691. ];
  13692. },
  13693. enumerable: true,
  13694. configurable: true
  13695. });
  13696. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13697. get: function () {
  13698. return [
  13699. new BABYLON.Color3(0.5, 0.0, 0.1),
  13700. new BABYLON.Color3(0.9, 0.0, 0.0),
  13701. new BABYLON.Color3(0.2, 0.0, 0.0),
  13702. new BABYLON.Color3(1.0, 0.9, 0.0),
  13703. new BABYLON.Color3(0.1, 0.1, 0.1),
  13704. new BABYLON.Color3(0.9, 0.9, 0.9)
  13705. ];
  13706. },
  13707. enumerable: true,
  13708. configurable: true
  13709. });
  13710. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13711. get: function () {
  13712. return [
  13713. new BABYLON.Color3(0.1, 0.0, 0.5),
  13714. new BABYLON.Color3(0.0, 0.0, 0.5),
  13715. new BABYLON.Color3(0.1, 0.0, 0.2),
  13716. new BABYLON.Color3(0.0, 0.0, 1.0),
  13717. new BABYLON.Color3(0.1, 0.2, 0.3),
  13718. new BABYLON.Color3(0.0, 0.2, 0.9)
  13719. ];
  13720. },
  13721. enumerable: true,
  13722. configurable: true
  13723. });
  13724. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13725. get: function () {
  13726. return this._fireColors;
  13727. },
  13728. set: function (value) {
  13729. this._fireColors = value;
  13730. this.updateShaderUniforms();
  13731. },
  13732. enumerable: true,
  13733. configurable: true
  13734. });
  13735. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13736. get: function () {
  13737. return this._time;
  13738. },
  13739. set: function (value) {
  13740. this._time = value;
  13741. this.updateShaderUniforms();
  13742. },
  13743. enumerable: true,
  13744. configurable: true
  13745. });
  13746. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13747. get: function () {
  13748. return this._speed;
  13749. },
  13750. set: function (value) {
  13751. this._speed = value;
  13752. this.updateShaderUniforms();
  13753. },
  13754. enumerable: true,
  13755. configurable: true
  13756. });
  13757. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13758. get: function () {
  13759. return this._alphaThreshold;
  13760. },
  13761. set: function (value) {
  13762. this._alphaThreshold = value;
  13763. this.updateShaderUniforms();
  13764. },
  13765. enumerable: true,
  13766. configurable: true
  13767. });
  13768. return FireProceduralTexture;
  13769. })(BABYLON.ProceduralTexture);
  13770. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13771. var CloudProceduralTexture = (function (_super) {
  13772. __extends(CloudProceduralTexture, _super);
  13773. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13774. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13775. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13776. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13777. this.updateShaderUniforms();
  13778. this.refreshRate = 0;
  13779. }
  13780. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13781. this.setColor3("skyColor", this._skyColor);
  13782. this.setColor3("cloudColor", this._cloudColor);
  13783. };
  13784. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13785. get: function () {
  13786. return this._skyColor;
  13787. },
  13788. set: function (value) {
  13789. this._skyColor = value;
  13790. this.updateShaderUniforms();
  13791. },
  13792. enumerable: true,
  13793. configurable: true
  13794. });
  13795. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13796. get: function () {
  13797. return this._cloudColor;
  13798. },
  13799. set: function (value) {
  13800. this._cloudColor = value;
  13801. this.updateShaderUniforms();
  13802. },
  13803. enumerable: true,
  13804. configurable: true
  13805. });
  13806. return CloudProceduralTexture;
  13807. })(BABYLON.ProceduralTexture);
  13808. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13809. var GrassProceduralTexture = (function (_super) {
  13810. __extends(GrassProceduralTexture, _super);
  13811. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13812. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13813. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13814. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13815. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13816. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13817. this._grassColors = [
  13818. new BABYLON.Color3(0.29, 0.38, 0.02),
  13819. new BABYLON.Color3(0.36, 0.49, 0.09),
  13820. new BABYLON.Color3(0.51, 0.6, 0.28)
  13821. ];
  13822. this.updateShaderUniforms();
  13823. this.refreshRate = 0;
  13824. }
  13825. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13826. this.setColor3("herb1Color", this._grassColors[0]);
  13827. this.setColor3("herb2Color", this._grassColors[1]);
  13828. this.setColor3("herb3Color", this._grassColors[2]);
  13829. this.setColor3("groundColor", this._groundColor);
  13830. };
  13831. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13832. get: function () {
  13833. return this._grassColors;
  13834. },
  13835. set: function (value) {
  13836. this._grassColors = value;
  13837. this.updateShaderUniforms();
  13838. },
  13839. enumerable: true,
  13840. configurable: true
  13841. });
  13842. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13843. get: function () {
  13844. return this._groundColor;
  13845. },
  13846. set: function (value) {
  13847. this.groundColor = value;
  13848. this.updateShaderUniforms();
  13849. },
  13850. enumerable: true,
  13851. configurable: true
  13852. });
  13853. return GrassProceduralTexture;
  13854. })(BABYLON.ProceduralTexture);
  13855. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13856. var RoadProceduralTexture = (function (_super) {
  13857. __extends(RoadProceduralTexture, _super);
  13858. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13859. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13860. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13861. this.updateShaderUniforms();
  13862. this.refreshRate = 0;
  13863. }
  13864. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13865. this.setColor3("roadColor", this._roadColor);
  13866. };
  13867. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13868. get: function () {
  13869. return this._roadColor;
  13870. },
  13871. set: function (value) {
  13872. this._roadColor = value;
  13873. this.updateShaderUniforms();
  13874. },
  13875. enumerable: true,
  13876. configurable: true
  13877. });
  13878. return RoadProceduralTexture;
  13879. })(BABYLON.ProceduralTexture);
  13880. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13881. var BrickProceduralTexture = (function (_super) {
  13882. __extends(BrickProceduralTexture, _super);
  13883. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13884. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13885. this._numberOfBricksHeight = 15;
  13886. this._numberOfBricksWidth = 5;
  13887. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13888. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13889. this.updateShaderUniforms();
  13890. this.refreshRate = 0;
  13891. }
  13892. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13893. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13894. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13895. this.setColor3("brickColor", this._brickColor);
  13896. this.setColor3("jointColor", this._jointColor);
  13897. };
  13898. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13899. get: function () {
  13900. return this._numberOfBricksHeight;
  13901. },
  13902. set: function (value) {
  13903. this._numberOfBricksHeight = value;
  13904. this.updateShaderUniforms();
  13905. },
  13906. enumerable: true,
  13907. configurable: true
  13908. });
  13909. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13910. get: function () {
  13911. return this._numberOfBricksWidth;
  13912. },
  13913. set: function (value) {
  13914. this._numberOfBricksHeight = value;
  13915. this.updateShaderUniforms();
  13916. },
  13917. enumerable: true,
  13918. configurable: true
  13919. });
  13920. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13921. get: function () {
  13922. return this._jointColor;
  13923. },
  13924. set: function (value) {
  13925. this._jointColor = value;
  13926. this.updateShaderUniforms();
  13927. },
  13928. enumerable: true,
  13929. configurable: true
  13930. });
  13931. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13932. get: function () {
  13933. return this._brickColor;
  13934. },
  13935. set: function (value) {
  13936. this._brickColor = value;
  13937. this.updateShaderUniforms();
  13938. },
  13939. enumerable: true,
  13940. configurable: true
  13941. });
  13942. return BrickProceduralTexture;
  13943. })(BABYLON.ProceduralTexture);
  13944. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13945. var MarbleProceduralTexture = (function (_super) {
  13946. __extends(MarbleProceduralTexture, _super);
  13947. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13948. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13949. this._numberOfTilesHeight = 3;
  13950. this._numberOfTilesWidth = 3;
  13951. this._amplitude = 9.0;
  13952. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13953. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13954. this.updateShaderUniforms();
  13955. this.refreshRate = 0;
  13956. }
  13957. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13958. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13959. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13960. this.setFloat("amplitude", this._amplitude);
  13961. this.setColor3("marbleColor", this._marbleColor);
  13962. this.setColor3("jointColor", this._jointColor);
  13963. };
  13964. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13965. get: function () {
  13966. return this._numberOfTilesHeight;
  13967. },
  13968. set: function (value) {
  13969. this._numberOfTilesHeight = value;
  13970. this.updateShaderUniforms();
  13971. },
  13972. enumerable: true,
  13973. configurable: true
  13974. });
  13975. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13976. get: function () {
  13977. return this._numberOfTilesWidth;
  13978. },
  13979. set: function (value) {
  13980. this._numberOfTilesWidth = value;
  13981. this.updateShaderUniforms();
  13982. },
  13983. enumerable: true,
  13984. configurable: true
  13985. });
  13986. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13987. get: function () {
  13988. return this._jointColor;
  13989. },
  13990. set: function (value) {
  13991. this._jointColor = value;
  13992. this.updateShaderUniforms();
  13993. },
  13994. enumerable: true,
  13995. configurable: true
  13996. });
  13997. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13998. get: function () {
  13999. return this._marbleColor;
  14000. },
  14001. set: function (value) {
  14002. this._marbleColor = value;
  14003. this.updateShaderUniforms();
  14004. },
  14005. enumerable: true,
  14006. configurable: true
  14007. });
  14008. return MarbleProceduralTexture;
  14009. })(BABYLON.ProceduralTexture);
  14010. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  14011. })(BABYLON || (BABYLON = {}));
  14012. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  14013. var BABYLON;
  14014. (function (BABYLON) {
  14015. var CustomProceduralTexture = (function (_super) {
  14016. __extends(CustomProceduralTexture, _super);
  14017. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  14018. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  14019. this._animate = true;
  14020. this._time = 0;
  14021. this._texturePath = texturePath;
  14022. //Try to load json
  14023. this.loadJson(texturePath);
  14024. this.refreshRate = 1;
  14025. }
  14026. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  14027. var _this = this;
  14028. var that = this;
  14029. function noConfigFile() {
  14030. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  14031. try {
  14032. that.setFragment(that._texturePath);
  14033. }
  14034. catch (ex) {
  14035. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  14036. }
  14037. }
  14038. var configFileUrl = jsonUrl + "/config.json";
  14039. var xhr = new XMLHttpRequest();
  14040. xhr.open("GET", configFileUrl, true);
  14041. xhr.addEventListener("load", function () {
  14042. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14043. try {
  14044. _this._config = JSON.parse(xhr.response);
  14045. _this.updateShaderUniforms();
  14046. _this.updateTextures();
  14047. _this.setFragment(_this._texturePath + "/custom");
  14048. _this._animate = _this._config.animate;
  14049. _this.refreshRate = _this._config.refreshrate;
  14050. }
  14051. catch (ex) {
  14052. noConfigFile();
  14053. }
  14054. }
  14055. else {
  14056. noConfigFile();
  14057. }
  14058. }, false);
  14059. xhr.addEventListener("error", function () {
  14060. noConfigFile();
  14061. }, false);
  14062. try {
  14063. xhr.send();
  14064. }
  14065. catch (ex) {
  14066. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  14067. }
  14068. };
  14069. CustomProceduralTexture.prototype.isReady = function () {
  14070. if (!_super.prototype.isReady.call(this)) {
  14071. return false;
  14072. }
  14073. for (var name in this._textures) {
  14074. var texture = this._textures[name];
  14075. if (!texture.isReady()) {
  14076. return false;
  14077. }
  14078. }
  14079. return true;
  14080. };
  14081. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  14082. if (this._animate) {
  14083. this._time += this.getScene().getAnimationRatio() * 0.03;
  14084. this.updateShaderUniforms();
  14085. }
  14086. _super.prototype.render.call(this, useCameraPostProcess);
  14087. };
  14088. CustomProceduralTexture.prototype.updateTextures = function () {
  14089. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  14090. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  14091. }
  14092. };
  14093. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  14094. if (this._config) {
  14095. for (var j = 0; j < this._config.uniforms.length; j++) {
  14096. var uniform = this._config.uniforms[j];
  14097. switch (uniform.type) {
  14098. case "float":
  14099. this.setFloat(uniform.name, uniform.value);
  14100. break;
  14101. case "color3":
  14102. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  14103. break;
  14104. case "color4":
  14105. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  14106. break;
  14107. case "vector2":
  14108. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  14109. break;
  14110. case "vector3":
  14111. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  14112. break;
  14113. }
  14114. }
  14115. }
  14116. this.setFloat("time", this._time);
  14117. };
  14118. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  14119. get: function () {
  14120. return this._animate;
  14121. },
  14122. set: function (value) {
  14123. this._animate = value;
  14124. },
  14125. enumerable: true,
  14126. configurable: true
  14127. });
  14128. return CustomProceduralTexture;
  14129. })(BABYLON.ProceduralTexture);
  14130. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  14131. })(BABYLON || (BABYLON = {}));
  14132. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  14133. var BABYLON;
  14134. (function (BABYLON) {
  14135. var MirrorTexture = (function (_super) {
  14136. __extends(MirrorTexture, _super);
  14137. function MirrorTexture(name, size, scene, generateMipMaps) {
  14138. var _this = this;
  14139. _super.call(this, name, size, scene, generateMipMaps, true);
  14140. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  14141. this._transformMatrix = BABYLON.Matrix.Zero();
  14142. this._mirrorMatrix = BABYLON.Matrix.Zero();
  14143. this.onBeforeRender = function () {
  14144. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  14145. _this._savedViewMatrix = scene.getViewMatrix();
  14146. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  14147. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  14148. scene.clipPlane = _this.mirrorPlane;
  14149. scene.getEngine().cullBackFaces = false;
  14150. };
  14151. this.onAfterRender = function () {
  14152. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  14153. scene.getEngine().cullBackFaces = true;
  14154. delete scene.clipPlane;
  14155. };
  14156. }
  14157. MirrorTexture.prototype.clone = function () {
  14158. var textureSize = this.getSize();
  14159. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14160. // Base texture
  14161. newTexture.hasAlpha = this.hasAlpha;
  14162. newTexture.level = this.level;
  14163. // Mirror Texture
  14164. newTexture.mirrorPlane = this.mirrorPlane.clone();
  14165. newTexture.renderList = this.renderList.slice(0);
  14166. return newTexture;
  14167. };
  14168. return MirrorTexture;
  14169. })(BABYLON.RenderTargetTexture);
  14170. BABYLON.MirrorTexture = MirrorTexture;
  14171. })(BABYLON || (BABYLON = {}));
  14172. //# sourceMappingURL=babylon.mirrorTexture.js.map
  14173. var BABYLON;
  14174. (function (BABYLON) {
  14175. var DynamicTexture = (function (_super) {
  14176. __extends(DynamicTexture, _super);
  14177. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  14178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14179. _super.call(this, null, scene, !generateMipMaps);
  14180. this.name = name;
  14181. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14182. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14183. this._generateMipMaps = generateMipMaps;
  14184. if (options.getContext) {
  14185. this._canvas = options;
  14186. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14187. }
  14188. else {
  14189. this._canvas = document.createElement("canvas");
  14190. if (options.width) {
  14191. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14192. }
  14193. else {
  14194. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  14195. }
  14196. }
  14197. var textureSize = this.getSize();
  14198. this._canvas.width = textureSize.width;
  14199. this._canvas.height = textureSize.height;
  14200. this._context = this._canvas.getContext("2d");
  14201. }
  14202. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  14203. get: function () {
  14204. return true;
  14205. },
  14206. enumerable: true,
  14207. configurable: true
  14208. });
  14209. DynamicTexture.prototype.scale = function (ratio) {
  14210. var textureSize = this.getSize();
  14211. textureSize.width *= ratio;
  14212. textureSize.height *= ratio;
  14213. this._canvas.width = textureSize.width;
  14214. this._canvas.height = textureSize.height;
  14215. this.releaseInternalTexture();
  14216. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  14217. };
  14218. DynamicTexture.prototype.getContext = function () {
  14219. return this._context;
  14220. };
  14221. DynamicTexture.prototype.clear = function () {
  14222. var size = this.getSize();
  14223. this._context.fillRect(0, 0, size.width, size.height);
  14224. };
  14225. DynamicTexture.prototype.update = function (invertY) {
  14226. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  14227. };
  14228. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  14229. if (update === void 0) { update = true; }
  14230. var size = this.getSize();
  14231. if (clearColor) {
  14232. this._context.fillStyle = clearColor;
  14233. this._context.fillRect(0, 0, size.width, size.height);
  14234. }
  14235. this._context.font = font;
  14236. if (x === null) {
  14237. var textSize = this._context.measureText(text);
  14238. x = (size.width - textSize.width) / 2;
  14239. }
  14240. this._context.fillStyle = color;
  14241. this._context.fillText(text, x, y);
  14242. if (update) {
  14243. this.update(invertY);
  14244. }
  14245. };
  14246. DynamicTexture.prototype.clone = function () {
  14247. var textureSize = this.getSize();
  14248. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14249. // Base texture
  14250. newTexture.hasAlpha = this.hasAlpha;
  14251. newTexture.level = this.level;
  14252. // Dynamic Texture
  14253. newTexture.wrapU = this.wrapU;
  14254. newTexture.wrapV = this.wrapV;
  14255. return newTexture;
  14256. };
  14257. return DynamicTexture;
  14258. })(BABYLON.Texture);
  14259. BABYLON.DynamicTexture = DynamicTexture;
  14260. })(BABYLON || (BABYLON = {}));
  14261. //# sourceMappingURL=babylon.dynamicTexture.js.map
  14262. var BABYLON;
  14263. (function (BABYLON) {
  14264. var VideoTexture = (function (_super) {
  14265. __extends(VideoTexture, _super);
  14266. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  14267. var _this = this;
  14268. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14269. _super.call(this, null, scene, !generateMipMaps, invertY);
  14270. this._autoLaunch = true;
  14271. this.name = name;
  14272. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14273. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14274. var requiredWidth = size.width || size;
  14275. var requiredHeight = size.height || size;
  14276. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  14277. var textureSize = this.getSize();
  14278. this.video = document.createElement("video");
  14279. this.video.width = textureSize.width;
  14280. this.video.height = textureSize.height;
  14281. this.video.autoplay = false;
  14282. this.video.loop = true;
  14283. this.video.addEventListener("canplaythrough", function () {
  14284. if (_this._texture) {
  14285. _this._texture.isReady = true;
  14286. }
  14287. });
  14288. urls.forEach(function (url) {
  14289. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  14290. var source = document.createElement("source");
  14291. source.src = url;
  14292. _this.video.appendChild(source);
  14293. });
  14294. this._lastUpdate = BABYLON.Tools.Now;
  14295. }
  14296. VideoTexture.prototype.update = function () {
  14297. if (this._autoLaunch) {
  14298. this._autoLaunch = false;
  14299. this.video.play();
  14300. }
  14301. var now = BABYLON.Tools.Now;
  14302. if (now - this._lastUpdate < 15) {
  14303. return false;
  14304. }
  14305. this._lastUpdate = now;
  14306. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  14307. return true;
  14308. };
  14309. return VideoTexture;
  14310. })(BABYLON.Texture);
  14311. BABYLON.VideoTexture = VideoTexture;
  14312. })(BABYLON || (BABYLON = {}));
  14313. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  14314. (function (BABYLON) {
  14315. var EffectFallbacks = (function () {
  14316. function EffectFallbacks() {
  14317. this._defines = {};
  14318. this._currentRank = 32;
  14319. this._maxRank = -1;
  14320. }
  14321. EffectFallbacks.prototype.addFallback = function (rank, define) {
  14322. if (!this._defines[rank]) {
  14323. if (rank < this._currentRank) {
  14324. this._currentRank = rank;
  14325. }
  14326. if (rank > this._maxRank) {
  14327. this._maxRank = rank;
  14328. }
  14329. this._defines[rank] = new Array();
  14330. }
  14331. this._defines[rank].push(define);
  14332. };
  14333. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  14334. get: function () {
  14335. return this._currentRank <= this._maxRank;
  14336. },
  14337. enumerable: true,
  14338. configurable: true
  14339. });
  14340. EffectFallbacks.prototype.reduce = function (currentDefines) {
  14341. var currentFallbacks = this._defines[this._currentRank];
  14342. for (var index = 0; index < currentFallbacks.length; index++) {
  14343. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  14344. }
  14345. this._currentRank++;
  14346. return currentDefines;
  14347. };
  14348. return EffectFallbacks;
  14349. })();
  14350. BABYLON.EffectFallbacks = EffectFallbacks;
  14351. var Effect = (function () {
  14352. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  14353. var _this = this;
  14354. this._isReady = false;
  14355. this._compilationError = "";
  14356. this._valueCache = [];
  14357. this._engine = engine;
  14358. this.name = baseName;
  14359. this.defines = defines;
  14360. this._uniformsNames = uniformsNames.concat(samplers);
  14361. this._samplers = samplers;
  14362. this._attributesNames = attributesNames;
  14363. this.onError = onError;
  14364. this.onCompiled = onCompiled;
  14365. var vertexSource;
  14366. var fragmentSource;
  14367. if (baseName.vertexElement) {
  14368. vertexSource = document.getElementById(baseName.vertexElement);
  14369. if (!vertexSource) {
  14370. vertexSource = baseName.vertexElement;
  14371. }
  14372. }
  14373. else {
  14374. vertexSource = baseName.vertex || baseName;
  14375. }
  14376. if (baseName.fragmentElement) {
  14377. fragmentSource = document.getElementById(baseName.fragmentElement);
  14378. if (!fragmentSource) {
  14379. fragmentSource = baseName.fragmentElement;
  14380. }
  14381. }
  14382. else {
  14383. fragmentSource = baseName.fragment || baseName;
  14384. }
  14385. this._loadVertexShader(vertexSource, function (vertexCode) {
  14386. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  14387. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  14388. });
  14389. });
  14390. }
  14391. // Properties
  14392. Effect.prototype.isReady = function () {
  14393. return this._isReady;
  14394. };
  14395. Effect.prototype.getProgram = function () {
  14396. return this._program;
  14397. };
  14398. Effect.prototype.getAttributesNames = function () {
  14399. return this._attributesNames;
  14400. };
  14401. Effect.prototype.getAttributeLocation = function (index) {
  14402. return this._attributes[index];
  14403. };
  14404. Effect.prototype.getAttributeLocationByName = function (name) {
  14405. var index = this._attributesNames.indexOf(name);
  14406. return this._attributes[index];
  14407. };
  14408. Effect.prototype.getAttributesCount = function () {
  14409. return this._attributes.length;
  14410. };
  14411. Effect.prototype.getUniformIndex = function (uniformName) {
  14412. return this._uniformsNames.indexOf(uniformName);
  14413. };
  14414. Effect.prototype.getUniform = function (uniformName) {
  14415. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  14416. };
  14417. Effect.prototype.getSamplers = function () {
  14418. return this._samplers;
  14419. };
  14420. Effect.prototype.getCompilationError = function () {
  14421. return this._compilationError;
  14422. };
  14423. // Methods
  14424. Effect.prototype._loadVertexShader = function (vertex, callback) {
  14425. // DOM element ?
  14426. if (vertex instanceof HTMLElement) {
  14427. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  14428. callback(vertexCode);
  14429. return;
  14430. }
  14431. // Is in local store ?
  14432. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  14433. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  14434. return;
  14435. }
  14436. var vertexShaderUrl;
  14437. if (vertex[0] === ".") {
  14438. vertexShaderUrl = vertex;
  14439. }
  14440. else {
  14441. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  14442. }
  14443. // Vertex shader
  14444. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  14445. };
  14446. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  14447. // DOM element ?
  14448. if (fragment instanceof HTMLElement) {
  14449. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  14450. callback(fragmentCode);
  14451. return;
  14452. }
  14453. // Is in local store ?
  14454. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  14455. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  14456. return;
  14457. }
  14458. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  14459. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  14460. return;
  14461. }
  14462. var fragmentShaderUrl;
  14463. if (fragment[0] === ".") {
  14464. fragmentShaderUrl = fragment;
  14465. }
  14466. else {
  14467. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14468. }
  14469. // Fragment shader
  14470. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14471. };
  14472. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14473. try {
  14474. var engine = this._engine;
  14475. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14476. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14477. this._attributes = engine.getAttributes(this._program, attributesNames);
  14478. for (var index = 0; index < this._samplers.length; index++) {
  14479. var sampler = this.getUniform(this._samplers[index]);
  14480. if (sampler == null) {
  14481. this._samplers.splice(index, 1);
  14482. index--;
  14483. }
  14484. }
  14485. engine.bindSamplers(this);
  14486. this._isReady = true;
  14487. if (this.onCompiled) {
  14488. this.onCompiled(this);
  14489. }
  14490. }
  14491. catch (e) {
  14492. // Is it a problem with precision?
  14493. if (e.message.indexOf("highp") !== -1) {
  14494. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14495. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14496. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14497. return;
  14498. }
  14499. // Let's go through fallbacks then
  14500. if (fallbacks && fallbacks.isMoreFallbacks) {
  14501. defines = fallbacks.reduce(defines);
  14502. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14503. }
  14504. else {
  14505. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14506. BABYLON.Tools.Error("Defines: " + defines);
  14507. BABYLON.Tools.Error("Error: " + e.message);
  14508. this._compilationError = e.message;
  14509. if (this.onError) {
  14510. this.onError(this, this._compilationError);
  14511. }
  14512. }
  14513. }
  14514. };
  14515. Effect.prototype._bindTexture = function (channel, texture) {
  14516. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14517. };
  14518. Effect.prototype.setTexture = function (channel, texture) {
  14519. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14520. };
  14521. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14522. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14523. };
  14524. //public _cacheMatrix(uniformName, matrix) {
  14525. // if (!this._valueCache[uniformName]) {
  14526. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14527. // }
  14528. // for (var index = 0; index < 16; index++) {
  14529. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14530. // }
  14531. //};
  14532. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14533. if (!this._valueCache[uniformName]) {
  14534. this._valueCache[uniformName] = [x, y];
  14535. return;
  14536. }
  14537. this._valueCache[uniformName][0] = x;
  14538. this._valueCache[uniformName][1] = y;
  14539. };
  14540. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14541. if (!this._valueCache[uniformName]) {
  14542. this._valueCache[uniformName] = [x, y, z];
  14543. return;
  14544. }
  14545. this._valueCache[uniformName][0] = x;
  14546. this._valueCache[uniformName][1] = y;
  14547. this._valueCache[uniformName][2] = z;
  14548. };
  14549. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14550. if (!this._valueCache[uniformName]) {
  14551. this._valueCache[uniformName] = [x, y, z, w];
  14552. return;
  14553. }
  14554. this._valueCache[uniformName][0] = x;
  14555. this._valueCache[uniformName][1] = y;
  14556. this._valueCache[uniformName][2] = z;
  14557. this._valueCache[uniformName][3] = w;
  14558. };
  14559. Effect.prototype.setArray = function (uniformName, array) {
  14560. this._engine.setArray(this.getUniform(uniformName), array);
  14561. return this;
  14562. };
  14563. Effect.prototype.setArray2 = function (uniformName, array) {
  14564. this._engine.setArray2(this.getUniform(uniformName), array);
  14565. return this;
  14566. };
  14567. Effect.prototype.setArray3 = function (uniformName, array) {
  14568. this._engine.setArray3(this.getUniform(uniformName), array);
  14569. return this;
  14570. };
  14571. Effect.prototype.setArray4 = function (uniformName, array) {
  14572. this._engine.setArray4(this.getUniform(uniformName), array);
  14573. return this;
  14574. };
  14575. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14576. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14577. return this;
  14578. };
  14579. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14580. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14581. // return;
  14582. //this._cacheMatrix(uniformName, matrix);
  14583. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14584. return this;
  14585. };
  14586. Effect.prototype.setFloat = function (uniformName, value) {
  14587. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14588. return this;
  14589. this._valueCache[uniformName] = value;
  14590. this._engine.setFloat(this.getUniform(uniformName), value);
  14591. return this;
  14592. };
  14593. Effect.prototype.setBool = function (uniformName, bool) {
  14594. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14595. return this;
  14596. this._valueCache[uniformName] = bool;
  14597. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14598. return this;
  14599. };
  14600. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14601. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14602. return this;
  14603. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14604. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14605. return this;
  14606. };
  14607. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14608. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14609. return this;
  14610. this._cacheFloat2(uniformName, x, y);
  14611. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14612. return this;
  14613. };
  14614. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14615. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14616. return this;
  14617. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14618. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14619. return this;
  14620. };
  14621. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14622. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14623. return this;
  14624. this._cacheFloat3(uniformName, x, y, z);
  14625. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14626. return this;
  14627. };
  14628. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14629. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14630. return this;
  14631. this._cacheFloat4(uniformName, x, y, z, w);
  14632. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14633. return this;
  14634. };
  14635. Effect.prototype.setColor3 = function (uniformName, color3) {
  14636. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14637. return this;
  14638. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14639. this._engine.setColor3(this.getUniform(uniformName), color3);
  14640. return this;
  14641. };
  14642. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14643. 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)
  14644. return this;
  14645. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14646. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14647. return this;
  14648. };
  14649. // Statics
  14650. 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}",
  14651. 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}",
  14652. 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}",
  14653. 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}",
  14654. 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}",
  14655. 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}",
  14656. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\ngl_FragColor = color;\n}",
  14657. colorVertexShader:"precision highp float;\n\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\ngl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  14658. 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}",
  14659. 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}",
  14660. 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}",
  14661. 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}",
  14662. 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}",
  14663. 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}",
  14664. 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}",
  14665. 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}",
  14666. 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}",
  14667. 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}",
  14668. 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}",
  14669. 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}",
  14670. 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}",
  14671. 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}",
  14672. 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}",
  14673. 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}",
  14674. 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}",
  14675. 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}",
  14676. 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}",
  14677. 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}",
  14678. 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}",
  14679. 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}",
  14680. 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}",
  14681. 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}",
  14682. 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}",
  14683. 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}",
  14684. 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}",
  14685. 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}",
  14686. 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}",
  14687. 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}",
  14688. 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}",
  14689. 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}",
  14690. 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}",
  14691. 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}",
  14692. 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}",
  14693. 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}",
  14694. 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}",
  14695. 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}",
  14696. 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}",
  14697. 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}",
  14698. };
  14699. return Effect;
  14700. })();
  14701. BABYLON.Effect = Effect;
  14702. })(BABYLON || (BABYLON = {}));
  14703. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14704. (function (BABYLON) {
  14705. var Material = (function () {
  14706. function Material(name, scene, doNotAdd) {
  14707. this.name = name;
  14708. this.checkReadyOnEveryCall = true;
  14709. this.checkReadyOnlyOnce = false;
  14710. this.state = "";
  14711. this.alpha = 1.0;
  14712. this.backFaceCulling = true;
  14713. this._wasPreviouslyReady = false;
  14714. this._fillMode = Material.TriangleFillMode;
  14715. this.pointSize = 1.0;
  14716. this.zOffset = 0;
  14717. this.id = name;
  14718. this._scene = scene;
  14719. if (!doNotAdd) {
  14720. scene.materials.push(this);
  14721. }
  14722. }
  14723. Object.defineProperty(Material, "TriangleFillMode", {
  14724. get: function () {
  14725. return Material._TriangleFillMode;
  14726. },
  14727. enumerable: true,
  14728. configurable: true
  14729. });
  14730. Object.defineProperty(Material, "WireFrameFillMode", {
  14731. get: function () {
  14732. return Material._WireFrameFillMode;
  14733. },
  14734. enumerable: true,
  14735. configurable: true
  14736. });
  14737. Object.defineProperty(Material, "PointFillMode", {
  14738. get: function () {
  14739. return Material._PointFillMode;
  14740. },
  14741. enumerable: true,
  14742. configurable: true
  14743. });
  14744. Object.defineProperty(Material.prototype, "wireframe", {
  14745. get: function () {
  14746. return this._fillMode === Material.WireFrameFillMode;
  14747. },
  14748. set: function (value) {
  14749. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14750. },
  14751. enumerable: true,
  14752. configurable: true
  14753. });
  14754. Object.defineProperty(Material.prototype, "pointsCloud", {
  14755. get: function () {
  14756. return this._fillMode === Material.PointFillMode;
  14757. },
  14758. set: function (value) {
  14759. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14760. },
  14761. enumerable: true,
  14762. configurable: true
  14763. });
  14764. Object.defineProperty(Material.prototype, "fillMode", {
  14765. get: function () {
  14766. return this._fillMode;
  14767. },
  14768. set: function (value) {
  14769. this._fillMode = value;
  14770. },
  14771. enumerable: true,
  14772. configurable: true
  14773. });
  14774. Material.prototype.isReady = function (mesh, useInstances) {
  14775. return true;
  14776. };
  14777. Material.prototype.getEffect = function () {
  14778. return this._effect;
  14779. };
  14780. Material.prototype.getScene = function () {
  14781. return this._scene;
  14782. };
  14783. Material.prototype.needAlphaBlending = function () {
  14784. return (this.alpha < 1.0);
  14785. };
  14786. Material.prototype.needAlphaTesting = function () {
  14787. return false;
  14788. };
  14789. Material.prototype.getAlphaTestTexture = function () {
  14790. return null;
  14791. };
  14792. Material.prototype.trackCreation = function (onCompiled, onError) {
  14793. };
  14794. Material.prototype._preBind = function () {
  14795. var engine = this._scene.getEngine();
  14796. engine.enableEffect(this._effect);
  14797. engine.setState(this.backFaceCulling, this.zOffset);
  14798. };
  14799. Material.prototype.bind = function (world, mesh) {
  14800. this._scene._cachedMaterial = this;
  14801. if (this.onBind) {
  14802. this.onBind(this, mesh);
  14803. }
  14804. };
  14805. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14806. };
  14807. Material.prototype.unbind = function () {
  14808. };
  14809. Material.prototype.dispose = function (forceDisposeEffect) {
  14810. // Remove from scene
  14811. var index = this._scene.materials.indexOf(this);
  14812. this._scene.materials.splice(index, 1);
  14813. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14814. if (forceDisposeEffect && this._effect) {
  14815. this._scene.getEngine()._releaseEffect(this._effect);
  14816. this._effect = null;
  14817. }
  14818. // Callback
  14819. if (this.onDispose) {
  14820. this.onDispose();
  14821. }
  14822. };
  14823. Material._TriangleFillMode = 0;
  14824. Material._WireFrameFillMode = 1;
  14825. Material._PointFillMode = 2;
  14826. return Material;
  14827. })();
  14828. BABYLON.Material = Material;
  14829. })(BABYLON || (BABYLON = {}));
  14830. //# sourceMappingURL=babylon.material.js.map
  14831. var BABYLON;
  14832. (function (BABYLON) {
  14833. var maxSimultaneousLights = 4;
  14834. var FresnelParameters = (function () {
  14835. function FresnelParameters() {
  14836. this.isEnabled = true;
  14837. this.leftColor = BABYLON.Color3.White();
  14838. this.rightColor = BABYLON.Color3.Black();
  14839. this.bias = 0;
  14840. this.power = 1;
  14841. }
  14842. return FresnelParameters;
  14843. })();
  14844. BABYLON.FresnelParameters = FresnelParameters;
  14845. var StandardMaterial = (function (_super) {
  14846. __extends(StandardMaterial, _super);
  14847. function StandardMaterial(name, scene) {
  14848. var _this = this;
  14849. _super.call(this, name, scene);
  14850. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14851. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14852. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14853. this.specularPower = 64;
  14854. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14855. this.useAlphaFromDiffuseTexture = false;
  14856. this.useSpecularOverAlpha = true;
  14857. this.fogEnabled = true;
  14858. this._cachedDefines = null;
  14859. this._renderTargets = new BABYLON.SmartArray(16);
  14860. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14861. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14862. this._scaledDiffuse = new BABYLON.Color3();
  14863. this._scaledSpecular = new BABYLON.Color3();
  14864. this.getRenderTargetTextures = function () {
  14865. _this._renderTargets.reset();
  14866. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14867. _this._renderTargets.push(_this.reflectionTexture);
  14868. }
  14869. return _this._renderTargets;
  14870. };
  14871. }
  14872. StandardMaterial.prototype.needAlphaBlending = function () {
  14873. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14874. };
  14875. StandardMaterial.prototype.needAlphaTesting = function () {
  14876. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14877. };
  14878. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14879. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14880. };
  14881. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14882. return this.diffuseTexture;
  14883. };
  14884. // Methods
  14885. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14886. if (this.checkReadyOnlyOnce) {
  14887. if (this._wasPreviouslyReady) {
  14888. }
  14889. }
  14890. var scene = this.getScene();
  14891. if (!this.checkReadyOnEveryCall) {
  14892. if (this._renderId === scene.getRenderId()) {
  14893. }
  14894. }
  14895. var engine = scene.getEngine();
  14896. var defines = [];
  14897. var fallbacks = new BABYLON.EffectFallbacks();
  14898. var needNormals = false;
  14899. var needUVs = false;
  14900. // Textures
  14901. if (scene.texturesEnabled) {
  14902. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14903. if (!this.diffuseTexture.isReady()) {
  14904. return false;
  14905. }
  14906. else {
  14907. needUVs = true;
  14908. defines.push("#define DIFFUSE");
  14909. }
  14910. }
  14911. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14912. if (!this.ambientTexture.isReady()) {
  14913. return false;
  14914. }
  14915. else {
  14916. needUVs = true;
  14917. defines.push("#define AMBIENT");
  14918. }
  14919. }
  14920. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14921. if (!this.opacityTexture.isReady()) {
  14922. return false;
  14923. }
  14924. else {
  14925. needUVs = true;
  14926. defines.push("#define OPACITY");
  14927. if (this.opacityTexture.getAlphaFromRGB) {
  14928. defines.push("#define OPACITYRGB");
  14929. }
  14930. }
  14931. }
  14932. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14933. if (!this.reflectionTexture.isReady()) {
  14934. return false;
  14935. }
  14936. else {
  14937. needNormals = true;
  14938. needUVs = true;
  14939. defines.push("#define REFLECTION");
  14940. fallbacks.addFallback(0, "REFLECTION");
  14941. }
  14942. }
  14943. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14944. if (!this.emissiveTexture.isReady()) {
  14945. return false;
  14946. }
  14947. else {
  14948. needUVs = true;
  14949. defines.push("#define EMISSIVE");
  14950. }
  14951. }
  14952. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14953. if (!this.specularTexture.isReady()) {
  14954. return false;
  14955. }
  14956. else {
  14957. needUVs = true;
  14958. defines.push("#define SPECULAR");
  14959. fallbacks.addFallback(0, "SPECULAR");
  14960. }
  14961. }
  14962. }
  14963. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14964. if (!this.bumpTexture.isReady()) {
  14965. return false;
  14966. }
  14967. else {
  14968. needUVs = true;
  14969. defines.push("#define BUMP");
  14970. fallbacks.addFallback(0, "BUMP");
  14971. }
  14972. }
  14973. // Effect
  14974. if (this.useSpecularOverAlpha) {
  14975. defines.push("#define SPECULAROVERALPHA");
  14976. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14977. }
  14978. if (scene.clipPlane) {
  14979. defines.push("#define CLIPPLANE");
  14980. }
  14981. if (engine.getAlphaTesting()) {
  14982. defines.push("#define ALPHATEST");
  14983. }
  14984. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14985. defines.push("#define ALPHAFROMDIFFUSE");
  14986. }
  14987. // Point size
  14988. if (this.pointsCloud || scene.forcePointsCloud) {
  14989. defines.push("#define POINTSIZE");
  14990. }
  14991. // Fog
  14992. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14993. defines.push("#define FOG");
  14994. fallbacks.addFallback(1, "FOG");
  14995. }
  14996. var shadowsActivated = false;
  14997. var lightIndex = 0;
  14998. if (scene.lightsEnabled) {
  14999. for (var index = 0; index < scene.lights.length; index++) {
  15000. var light = scene.lights[index];
  15001. if (!light.isEnabled()) {
  15002. continue;
  15003. }
  15004. // Excluded check
  15005. if (light._excludedMeshesIds.length > 0) {
  15006. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  15007. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  15008. if (excludedMesh) {
  15009. light.excludedMeshes.push(excludedMesh);
  15010. }
  15011. }
  15012. light._excludedMeshesIds = [];
  15013. }
  15014. // Included check
  15015. if (light._includedOnlyMeshesIds.length > 0) {
  15016. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  15017. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  15018. if (includedOnlyMesh) {
  15019. light.includedOnlyMeshes.push(includedOnlyMesh);
  15020. }
  15021. }
  15022. light._includedOnlyMeshesIds = [];
  15023. }
  15024. if (!light.canAffectMesh(mesh)) {
  15025. continue;
  15026. }
  15027. needNormals = true;
  15028. defines.push("#define LIGHT" + lightIndex);
  15029. if (lightIndex > 0) {
  15030. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  15031. }
  15032. var type;
  15033. if (light instanceof BABYLON.SpotLight) {
  15034. type = "#define SPOTLIGHT" + lightIndex;
  15035. }
  15036. else if (light instanceof BABYLON.HemisphericLight) {
  15037. type = "#define HEMILIGHT" + lightIndex;
  15038. }
  15039. else {
  15040. type = "#define POINTDIRLIGHT" + lightIndex;
  15041. }
  15042. defines.push(type);
  15043. if (lightIndex > 0) {
  15044. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  15045. }
  15046. // Shadows
  15047. if (scene.shadowsEnabled) {
  15048. var shadowGenerator = light.getShadowGenerator();
  15049. if (mesh && mesh.receiveShadows && shadowGenerator) {
  15050. defines.push("#define SHADOW" + lightIndex);
  15051. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  15052. if (!shadowsActivated) {
  15053. defines.push("#define SHADOWS");
  15054. shadowsActivated = true;
  15055. }
  15056. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  15057. defines.push("#define SHADOWVSM" + lightIndex);
  15058. if (lightIndex > 0) {
  15059. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  15060. }
  15061. }
  15062. if (shadowGenerator.usePoissonSampling) {
  15063. defines.push("#define SHADOWPCF" + lightIndex);
  15064. if (lightIndex > 0) {
  15065. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  15066. }
  15067. }
  15068. }
  15069. }
  15070. lightIndex++;
  15071. if (lightIndex === maxSimultaneousLights)
  15072. break;
  15073. }
  15074. }
  15075. if (StandardMaterial.FresnelEnabled) {
  15076. // Fresnel
  15077. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15078. var fresnelRank = 1;
  15079. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15080. defines.push("#define DIFFUSEFRESNEL");
  15081. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  15082. fresnelRank++;
  15083. }
  15084. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15085. defines.push("#define OPACITYFRESNEL");
  15086. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  15087. fresnelRank++;
  15088. }
  15089. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15090. defines.push("#define REFLECTIONFRESNEL");
  15091. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  15092. fresnelRank++;
  15093. }
  15094. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15095. defines.push("#define EMISSIVEFRESNEL");
  15096. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  15097. fresnelRank++;
  15098. }
  15099. needNormals = true;
  15100. defines.push("#define FRESNEL");
  15101. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  15102. }
  15103. }
  15104. // Attribs
  15105. var attribs = [BABYLON.VertexBuffer.PositionKind];
  15106. if (mesh) {
  15107. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15108. attribs.push(BABYLON.VertexBuffer.NormalKind);
  15109. defines.push("#define NORMAL");
  15110. }
  15111. if (needUVs) {
  15112. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15113. attribs.push(BABYLON.VertexBuffer.UVKind);
  15114. defines.push("#define UV1");
  15115. }
  15116. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15117. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  15118. defines.push("#define UV2");
  15119. }
  15120. }
  15121. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15122. attribs.push(BABYLON.VertexBuffer.ColorKind);
  15123. defines.push("#define VERTEXCOLOR");
  15124. if (mesh.hasVertexAlpha) {
  15125. defines.push("#define VERTEXALPHA");
  15126. }
  15127. }
  15128. if (mesh.useBones) {
  15129. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15130. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15131. defines.push("#define BONES");
  15132. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  15133. defines.push("#define BONES4");
  15134. fallbacks.addFallback(0, "BONES4");
  15135. }
  15136. // Instances
  15137. if (useInstances) {
  15138. defines.push("#define INSTANCES");
  15139. attribs.push("world0");
  15140. attribs.push("world1");
  15141. attribs.push("world2");
  15142. attribs.push("world3");
  15143. }
  15144. }
  15145. // Get correct effect
  15146. var join = defines.join("\n");
  15147. if (this._cachedDefines !== join) {
  15148. this._cachedDefines = join;
  15149. scene.resetCachedMaterial();
  15150. // Legacy browser patch
  15151. var shaderName = "default";
  15152. if (!scene.getEngine().getCaps().standardDerivatives) {
  15153. shaderName = "legacydefault";
  15154. }
  15155. 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);
  15156. }
  15157. if (!this._effect.isReady()) {
  15158. return false;
  15159. }
  15160. this._renderId = scene.getRenderId();
  15161. this._wasPreviouslyReady = true;
  15162. return true;
  15163. };
  15164. StandardMaterial.prototype.unbind = function () {
  15165. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  15166. this._effect.setTexture("reflection2DSampler", null);
  15167. }
  15168. };
  15169. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  15170. this._effect.setMatrix("world", world);
  15171. };
  15172. StandardMaterial.prototype.bind = function (world, mesh) {
  15173. var scene = this.getScene();
  15174. // Matrices
  15175. this.bindOnlyWorldMatrix(world);
  15176. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  15177. // Bones
  15178. if (mesh && mesh.useBones) {
  15179. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  15180. }
  15181. if (scene.getCachedMaterial() !== this) {
  15182. if (StandardMaterial.FresnelEnabled) {
  15183. // Fresnel
  15184. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15185. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  15186. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  15187. }
  15188. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15189. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  15190. }
  15191. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15192. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  15193. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  15194. }
  15195. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15196. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  15197. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  15198. }
  15199. }
  15200. // Textures
  15201. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  15202. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  15203. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  15204. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  15205. }
  15206. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  15207. this._effect.setTexture("ambientSampler", this.ambientTexture);
  15208. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  15209. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  15210. }
  15211. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  15212. this._effect.setTexture("opacitySampler", this.opacityTexture);
  15213. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  15214. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  15215. }
  15216. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15217. if (this.reflectionTexture.isCube) {
  15218. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  15219. }
  15220. else {
  15221. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  15222. }
  15223. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  15224. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  15225. }
  15226. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15227. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  15228. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  15229. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  15230. }
  15231. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15232. this._effect.setTexture("specularSampler", this.specularTexture);
  15233. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  15234. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  15235. }
  15236. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  15237. this._effect.setTexture("bumpSampler", this.bumpTexture);
  15238. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  15239. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  15240. }
  15241. // Clip plane
  15242. if (scene.clipPlane) {
  15243. var clipPlane = scene.clipPlane;
  15244. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15245. }
  15246. // Point size
  15247. if (this.pointsCloud) {
  15248. this._effect.setFloat("pointSize", this.pointSize);
  15249. }
  15250. // Colors
  15251. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  15252. // Scaling down color according to emissive
  15253. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15254. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15255. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15256. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  15257. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  15258. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  15259. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  15260. }
  15261. // Scaling down color according to emissive
  15262. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15263. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15264. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15265. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  15266. if (scene.lightsEnabled) {
  15267. var lightIndex = 0;
  15268. for (var index = 0; index < scene.lights.length; index++) {
  15269. var light = scene.lights[index];
  15270. if (!light.isEnabled()) {
  15271. continue;
  15272. }
  15273. if (!light.canAffectMesh(mesh)) {
  15274. continue;
  15275. }
  15276. if (light instanceof BABYLON.PointLight) {
  15277. // Point Light
  15278. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15279. }
  15280. else if (light instanceof BABYLON.DirectionalLight) {
  15281. // Directional Light
  15282. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15283. }
  15284. else if (light instanceof BABYLON.SpotLight) {
  15285. // Spot Light
  15286. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  15287. }
  15288. else if (light instanceof BABYLON.HemisphericLight) {
  15289. // Hemispheric Light
  15290. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  15291. }
  15292. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  15293. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  15294. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  15295. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  15296. // Shadows
  15297. if (scene.shadowsEnabled) {
  15298. var shadowGenerator = light.getShadowGenerator();
  15299. if (mesh.receiveShadows && shadowGenerator) {
  15300. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  15301. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  15302. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  15303. }
  15304. }
  15305. lightIndex++;
  15306. if (lightIndex === maxSimultaneousLights)
  15307. break;
  15308. }
  15309. }
  15310. // View
  15311. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  15312. this._effect.setMatrix("view", scene.getViewMatrix());
  15313. }
  15314. // Fog
  15315. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  15316. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  15317. this._effect.setColor3("vFogColor", scene.fogColor);
  15318. }
  15319. _super.prototype.bind.call(this, world, mesh);
  15320. };
  15321. StandardMaterial.prototype.getAnimatables = function () {
  15322. var results = [];
  15323. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  15324. results.push(this.diffuseTexture);
  15325. }
  15326. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  15327. results.push(this.ambientTexture);
  15328. }
  15329. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  15330. results.push(this.opacityTexture);
  15331. }
  15332. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  15333. results.push(this.reflectionTexture);
  15334. }
  15335. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  15336. results.push(this.emissiveTexture);
  15337. }
  15338. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  15339. results.push(this.specularTexture);
  15340. }
  15341. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  15342. results.push(this.bumpTexture);
  15343. }
  15344. return results;
  15345. };
  15346. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  15347. if (this.diffuseTexture) {
  15348. this.diffuseTexture.dispose();
  15349. }
  15350. if (this.ambientTexture) {
  15351. this.ambientTexture.dispose();
  15352. }
  15353. if (this.opacityTexture) {
  15354. this.opacityTexture.dispose();
  15355. }
  15356. if (this.reflectionTexture) {
  15357. this.reflectionTexture.dispose();
  15358. }
  15359. if (this.emissiveTexture) {
  15360. this.emissiveTexture.dispose();
  15361. }
  15362. if (this.specularTexture) {
  15363. this.specularTexture.dispose();
  15364. }
  15365. if (this.bumpTexture) {
  15366. this.bumpTexture.dispose();
  15367. }
  15368. _super.prototype.dispose.call(this, forceDisposeEffect);
  15369. };
  15370. StandardMaterial.prototype.clone = function (name) {
  15371. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  15372. // Base material
  15373. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  15374. newStandardMaterial.alpha = this.alpha;
  15375. newStandardMaterial.fillMode = this.fillMode;
  15376. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  15377. // Standard material
  15378. if (this.diffuseTexture && this.diffuseTexture.clone) {
  15379. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  15380. }
  15381. if (this.ambientTexture && this.ambientTexture.clone) {
  15382. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  15383. }
  15384. if (this.opacityTexture && this.opacityTexture.clone) {
  15385. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  15386. }
  15387. if (this.reflectionTexture && this.reflectionTexture.clone) {
  15388. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  15389. }
  15390. if (this.emissiveTexture && this.emissiveTexture.clone) {
  15391. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  15392. }
  15393. if (this.specularTexture && this.specularTexture.clone) {
  15394. newStandardMaterial.specularTexture = this.specularTexture.clone();
  15395. }
  15396. if (this.bumpTexture && this.bumpTexture.clone) {
  15397. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  15398. }
  15399. newStandardMaterial.ambientColor = this.ambientColor.clone();
  15400. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  15401. newStandardMaterial.specularColor = this.specularColor.clone();
  15402. newStandardMaterial.specularPower = this.specularPower;
  15403. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  15404. return newStandardMaterial;
  15405. };
  15406. // Statics
  15407. // Flags used to enable or disable a type of texture for all Standard Materials
  15408. StandardMaterial.DiffuseTextureEnabled = true;
  15409. StandardMaterial.AmbientTextureEnabled = true;
  15410. StandardMaterial.OpacityTextureEnabled = true;
  15411. StandardMaterial.ReflectionTextureEnabled = true;
  15412. StandardMaterial.EmissiveTextureEnabled = true;
  15413. StandardMaterial.SpecularTextureEnabled = true;
  15414. StandardMaterial.BumpTextureEnabled = true;
  15415. StandardMaterial.FresnelEnabled = true;
  15416. return StandardMaterial;
  15417. })(BABYLON.Material);
  15418. BABYLON.StandardMaterial = StandardMaterial;
  15419. })(BABYLON || (BABYLON = {}));
  15420. //# sourceMappingURL=babylon.standardMaterial.js.map
  15421. var BABYLON;
  15422. (function (BABYLON) {
  15423. var MultiMaterial = (function (_super) {
  15424. __extends(MultiMaterial, _super);
  15425. function MultiMaterial(name, scene) {
  15426. _super.call(this, name, scene, true);
  15427. this.subMaterials = new Array();
  15428. scene.multiMaterials.push(this);
  15429. }
  15430. // Properties
  15431. MultiMaterial.prototype.getSubMaterial = function (index) {
  15432. if (index < 0 || index >= this.subMaterials.length) {
  15433. return this.getScene().defaultMaterial;
  15434. }
  15435. return this.subMaterials[index];
  15436. };
  15437. // Methods
  15438. MultiMaterial.prototype.isReady = function (mesh) {
  15439. for (var index = 0; index < this.subMaterials.length; index++) {
  15440. var subMaterial = this.subMaterials[index];
  15441. if (subMaterial) {
  15442. if (!this.subMaterials[index].isReady(mesh)) {
  15443. return false;
  15444. }
  15445. }
  15446. }
  15447. return true;
  15448. };
  15449. return MultiMaterial;
  15450. })(BABYLON.Material);
  15451. BABYLON.MultiMaterial = MultiMaterial;
  15452. })(BABYLON || (BABYLON = {}));
  15453. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  15454. (function (BABYLON) {
  15455. var Database = (function () {
  15456. function Database(urlToScene, callbackManifestChecked) {
  15457. // Handling various flavors of prefixed version of IndexedDB
  15458. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  15459. this.callbackManifestChecked = callbackManifestChecked;
  15460. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  15461. this.db = null;
  15462. this.enableSceneOffline = false;
  15463. this.enableTexturesOffline = false;
  15464. this.manifestVersionFound = 0;
  15465. this.mustUpdateRessources = false;
  15466. this.hasReachedQuota = false;
  15467. this.checkManifestFile();
  15468. }
  15469. Database.prototype.checkManifestFile = function () {
  15470. var _this = this;
  15471. function noManifestFile() {
  15472. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15473. that.enableSceneOffline = false;
  15474. that.enableTexturesOffline = false;
  15475. that.callbackManifestChecked(false);
  15476. }
  15477. var that = this;
  15478. var manifestURL = this.currentSceneUrl + ".manifest";
  15479. var xhr = new XMLHttpRequest();
  15480. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15481. xhr.open("GET", manifestURLTimeStamped, true);
  15482. xhr.addEventListener("load", function () {
  15483. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15484. try {
  15485. var manifestFile = JSON.parse(xhr.response);
  15486. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15487. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15488. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15489. _this.manifestVersionFound = manifestFile.version;
  15490. }
  15491. if (_this.callbackManifestChecked) {
  15492. _this.callbackManifestChecked(true);
  15493. }
  15494. }
  15495. catch (ex) {
  15496. noManifestFile();
  15497. }
  15498. }
  15499. else {
  15500. noManifestFile();
  15501. }
  15502. }, false);
  15503. xhr.addEventListener("error", function (event) {
  15504. noManifestFile();
  15505. }, false);
  15506. try {
  15507. xhr.send();
  15508. }
  15509. catch (ex) {
  15510. BABYLON.Tools.Error("Error on XHR send request.");
  15511. that.callbackManifestChecked(false);
  15512. }
  15513. };
  15514. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15515. var _this = this;
  15516. function handleError() {
  15517. that.isSupported = false;
  15518. if (errorCallback)
  15519. errorCallback();
  15520. }
  15521. var that = this;
  15522. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15523. // Your browser doesn't support IndexedDB
  15524. this.isSupported = false;
  15525. if (errorCallback)
  15526. errorCallback();
  15527. }
  15528. else {
  15529. // If the DB hasn't been opened or created yet
  15530. if (!this.db) {
  15531. this.hasReachedQuota = false;
  15532. this.isSupported = true;
  15533. var request = this.idbFactory.open("babylonjs", 1);
  15534. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15535. request.onerror = function (event) {
  15536. handleError();
  15537. };
  15538. // executes when a version change transaction cannot complete due to other active transactions
  15539. request.onblocked = function (event) {
  15540. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15541. handleError();
  15542. };
  15543. // DB has been opened successfully
  15544. request.onsuccess = function (event) {
  15545. _this.db = request.result;
  15546. successCallback();
  15547. };
  15548. // Initialization of the DB. Creating Scenes & Textures stores
  15549. request.onupgradeneeded = function (event) {
  15550. _this.db = (event.target).result;
  15551. try {
  15552. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15553. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15554. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15555. }
  15556. catch (ex) {
  15557. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15558. handleError();
  15559. }
  15560. };
  15561. }
  15562. else {
  15563. if (successCallback)
  15564. successCallback();
  15565. }
  15566. }
  15567. };
  15568. Database.prototype.loadImageFromDB = function (url, image) {
  15569. var _this = this;
  15570. var completeURL = Database.ReturnFullUrlLocation(url);
  15571. var saveAndLoadImage = function () {
  15572. if (!_this.hasReachedQuota && _this.db !== null) {
  15573. // the texture is not yet in the DB, let's try to save it
  15574. _this._saveImageIntoDBAsync(completeURL, image);
  15575. }
  15576. else {
  15577. image.src = url;
  15578. }
  15579. };
  15580. if (!this.mustUpdateRessources) {
  15581. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15582. }
  15583. else {
  15584. saveAndLoadImage();
  15585. }
  15586. };
  15587. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15588. if (this.isSupported && this.db !== null) {
  15589. var texture;
  15590. var transaction = this.db.transaction(["textures"]);
  15591. transaction.onabort = function (event) {
  15592. image.src = url;
  15593. };
  15594. transaction.oncomplete = function (event) {
  15595. var blobTextureURL;
  15596. if (texture) {
  15597. var URL = window.URL || window.webkitURL;
  15598. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15599. image.onerror = function () {
  15600. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15601. image.src = url;
  15602. };
  15603. image.src = blobTextureURL;
  15604. }
  15605. else {
  15606. notInDBCallback();
  15607. }
  15608. };
  15609. var getRequest = transaction.objectStore("textures").get(url);
  15610. getRequest.onsuccess = function (event) {
  15611. texture = (event.target).result;
  15612. };
  15613. getRequest.onerror = function (event) {
  15614. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15615. image.src = url;
  15616. };
  15617. }
  15618. else {
  15619. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15620. image.src = url;
  15621. }
  15622. };
  15623. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15624. var _this = this;
  15625. if (this.isSupported) {
  15626. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15627. var generateBlobUrl = function () {
  15628. var blobTextureURL;
  15629. if (blob) {
  15630. var URL = window.URL || window.webkitURL;
  15631. try {
  15632. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15633. }
  15634. catch (ex) {
  15635. blobTextureURL = URL.createObjectURL(blob);
  15636. }
  15637. }
  15638. image.src = blobTextureURL;
  15639. };
  15640. if (Database.isUASupportingBlobStorage) {
  15641. var xhr = new XMLHttpRequest(), blob;
  15642. xhr.open("GET", url, true);
  15643. xhr.responseType = "blob";
  15644. xhr.addEventListener("load", function () {
  15645. if (xhr.status === 200) {
  15646. // Blob as response (XHR2)
  15647. blob = xhr.response;
  15648. var transaction = _this.db.transaction(["textures"], "readwrite");
  15649. // the transaction could abort because of a QuotaExceededError error
  15650. transaction.onabort = function (event) {
  15651. try {
  15652. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15653. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15654. this.hasReachedQuota = true;
  15655. }
  15656. }
  15657. catch (ex) {
  15658. }
  15659. generateBlobUrl();
  15660. };
  15661. transaction.oncomplete = function (event) {
  15662. generateBlobUrl();
  15663. };
  15664. var newTexture = { textureUrl: url, data: blob };
  15665. try {
  15666. // Put the blob into the dabase
  15667. var addRequest = transaction.objectStore("textures").put(newTexture);
  15668. addRequest.onsuccess = function (event) {
  15669. };
  15670. addRequest.onerror = function (event) {
  15671. generateBlobUrl();
  15672. };
  15673. }
  15674. catch (ex) {
  15675. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15676. if (ex.code === 25) {
  15677. Database.isUASupportingBlobStorage = false;
  15678. }
  15679. image.src = url;
  15680. }
  15681. }
  15682. else {
  15683. image.src = url;
  15684. }
  15685. }, false);
  15686. xhr.addEventListener("error", function (event) {
  15687. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15688. image.src = url;
  15689. }, false);
  15690. xhr.send();
  15691. }
  15692. else {
  15693. image.src = url;
  15694. }
  15695. }
  15696. else {
  15697. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15698. image.src = url;
  15699. }
  15700. };
  15701. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15702. var _this = this;
  15703. var updateVersion = function (event) {
  15704. // the version is not yet in the DB or we need to update it
  15705. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15706. };
  15707. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15708. };
  15709. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15710. var _this = this;
  15711. if (this.isSupported) {
  15712. var version;
  15713. try {
  15714. var transaction = this.db.transaction(["versions"]);
  15715. transaction.oncomplete = function (event) {
  15716. if (version) {
  15717. // If the version in the JSON file is > than the version in DB
  15718. if (_this.manifestVersionFound > version.data) {
  15719. _this.mustUpdateRessources = true;
  15720. updateInDBCallback();
  15721. }
  15722. else {
  15723. callback(version.data);
  15724. }
  15725. }
  15726. else {
  15727. _this.mustUpdateRessources = true;
  15728. updateInDBCallback();
  15729. }
  15730. };
  15731. transaction.onabort = function (event) {
  15732. callback(-1);
  15733. };
  15734. var getRequest = transaction.objectStore("versions").get(url);
  15735. getRequest.onsuccess = function (event) {
  15736. version = (event.target).result;
  15737. };
  15738. getRequest.onerror = function (event) {
  15739. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15740. callback(-1);
  15741. };
  15742. }
  15743. catch (ex) {
  15744. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15745. callback(-1);
  15746. }
  15747. }
  15748. else {
  15749. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15750. callback(-1);
  15751. }
  15752. };
  15753. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15754. var _this = this;
  15755. if (this.isSupported && !this.hasReachedQuota) {
  15756. try {
  15757. // Open a transaction to the database
  15758. var transaction = this.db.transaction(["versions"], "readwrite");
  15759. // the transaction could abort because of a QuotaExceededError error
  15760. transaction.onabort = function (event) {
  15761. try {
  15762. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15763. _this.hasReachedQuota = true;
  15764. }
  15765. }
  15766. catch (ex) {
  15767. }
  15768. callback(-1);
  15769. };
  15770. transaction.oncomplete = function (event) {
  15771. callback(_this.manifestVersionFound);
  15772. };
  15773. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15774. // Put the scene into the database
  15775. var addRequest = transaction.objectStore("versions").put(newVersion);
  15776. addRequest.onsuccess = function (event) {
  15777. };
  15778. addRequest.onerror = function (event) {
  15779. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15780. };
  15781. }
  15782. catch (ex) {
  15783. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15784. callback(-1);
  15785. }
  15786. }
  15787. else {
  15788. callback(-1);
  15789. }
  15790. };
  15791. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15792. var _this = this;
  15793. var completeUrl = Database.ReturnFullUrlLocation(url);
  15794. var saveAndLoadFile = function (event) {
  15795. // the scene is not yet in the DB, let's try to save it
  15796. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15797. };
  15798. this._checkVersionFromDB(completeUrl, function (version) {
  15799. if (version !== -1) {
  15800. if (!_this.mustUpdateRessources) {
  15801. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15802. }
  15803. else {
  15804. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15805. }
  15806. }
  15807. else {
  15808. errorCallback();
  15809. }
  15810. });
  15811. };
  15812. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15813. if (this.isSupported) {
  15814. var targetStore;
  15815. if (url.indexOf(".babylon") !== -1) {
  15816. targetStore = "scenes";
  15817. }
  15818. else {
  15819. targetStore = "textures";
  15820. }
  15821. var file;
  15822. var transaction = this.db.transaction([targetStore]);
  15823. transaction.oncomplete = function (event) {
  15824. if (file) {
  15825. callback(file.data);
  15826. }
  15827. else {
  15828. notInDBCallback();
  15829. }
  15830. };
  15831. transaction.onabort = function (event) {
  15832. notInDBCallback();
  15833. };
  15834. var getRequest = transaction.objectStore(targetStore).get(url);
  15835. getRequest.onsuccess = function (event) {
  15836. file = (event.target).result;
  15837. };
  15838. getRequest.onerror = function (event) {
  15839. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15840. notInDBCallback();
  15841. };
  15842. }
  15843. else {
  15844. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15845. callback();
  15846. }
  15847. };
  15848. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15849. var _this = this;
  15850. if (this.isSupported) {
  15851. var targetStore;
  15852. if (url.indexOf(".babylon") !== -1) {
  15853. targetStore = "scenes";
  15854. }
  15855. else {
  15856. targetStore = "textures";
  15857. }
  15858. // Create XHR
  15859. var xhr = new XMLHttpRequest(), fileData;
  15860. xhr.open("GET", url, true);
  15861. if (useArrayBuffer) {
  15862. xhr.responseType = "arraybuffer";
  15863. }
  15864. xhr.onprogress = progressCallback;
  15865. xhr.addEventListener("load", function () {
  15866. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15867. // Blob as response (XHR2)
  15868. //fileData = xhr.responseText;
  15869. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15870. if (!_this.hasReachedQuota) {
  15871. // Open a transaction to the database
  15872. var transaction = _this.db.transaction([targetStore], "readwrite");
  15873. // the transaction could abort because of a QuotaExceededError error
  15874. transaction.onabort = function (event) {
  15875. try {
  15876. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15877. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15878. this.hasReachedQuota = true;
  15879. }
  15880. }
  15881. catch (ex) {
  15882. }
  15883. callback(fileData);
  15884. };
  15885. transaction.oncomplete = function (event) {
  15886. callback(fileData);
  15887. };
  15888. var newFile;
  15889. if (targetStore === "scenes") {
  15890. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15891. }
  15892. else {
  15893. newFile = { textureUrl: url, data: fileData };
  15894. }
  15895. try {
  15896. // Put the scene into the database
  15897. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15898. addRequest.onsuccess = function (event) {
  15899. };
  15900. addRequest.onerror = function (event) {
  15901. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15902. };
  15903. }
  15904. catch (ex) {
  15905. callback(fileData);
  15906. }
  15907. }
  15908. else {
  15909. callback(fileData);
  15910. }
  15911. }
  15912. else {
  15913. callback();
  15914. }
  15915. }, false);
  15916. xhr.addEventListener("error", function (event) {
  15917. BABYLON.Tools.Error("error on XHR request.");
  15918. callback();
  15919. }, false);
  15920. xhr.send();
  15921. }
  15922. else {
  15923. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15924. callback();
  15925. }
  15926. };
  15927. Database.isUASupportingBlobStorage = true;
  15928. Database.parseURL = function (url) {
  15929. var a = document.createElement('a');
  15930. a.href = url;
  15931. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15932. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15933. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15934. return absLocation;
  15935. };
  15936. Database.ReturnFullUrlLocation = function (url) {
  15937. if (url.indexOf("http:/") === -1) {
  15938. return (BABYLON.Database.parseURL(window.location.href) + url);
  15939. }
  15940. else {
  15941. return url;
  15942. }
  15943. };
  15944. return Database;
  15945. })();
  15946. BABYLON.Database = Database;
  15947. })(BABYLON || (BABYLON = {}));
  15948. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15949. (function (BABYLON) {
  15950. var SpriteManager = (function () {
  15951. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15952. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15953. this.name = name;
  15954. this.cellSize = cellSize;
  15955. this.sprites = new Array();
  15956. this.renderingGroupId = 0;
  15957. this.fogEnabled = true;
  15958. this._vertexDeclaration = [4, 4, 4, 4];
  15959. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15960. this._capacity = capacity;
  15961. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15962. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15963. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15964. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15965. this._scene = scene;
  15966. this._scene.spriteManagers.push(this);
  15967. // VBO
  15968. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15969. var indices = [];
  15970. var index = 0;
  15971. for (var count = 0; count < capacity; count++) {
  15972. indices.push(index);
  15973. indices.push(index + 1);
  15974. indices.push(index + 2);
  15975. indices.push(index);
  15976. indices.push(index + 2);
  15977. indices.push(index + 3);
  15978. index += 4;
  15979. }
  15980. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15981. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15982. // Effects
  15983. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15984. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15985. }
  15986. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15987. var arrayOffset = index * 16;
  15988. if (offsetX === 0)
  15989. offsetX = this._epsilon;
  15990. else if (offsetX === 1)
  15991. offsetX = 1 - this._epsilon;
  15992. if (offsetY === 0)
  15993. offsetY = this._epsilon;
  15994. else if (offsetY === 1)
  15995. offsetY = 1 - this._epsilon;
  15996. this._vertices[arrayOffset] = sprite.position.x;
  15997. this._vertices[arrayOffset + 1] = sprite.position.y;
  15998. this._vertices[arrayOffset + 2] = sprite.position.z;
  15999. this._vertices[arrayOffset + 3] = sprite.angle;
  16000. this._vertices[arrayOffset + 4] = sprite.width;
  16001. this._vertices[arrayOffset + 5] = sprite.height;
  16002. this._vertices[arrayOffset + 6] = offsetX;
  16003. this._vertices[arrayOffset + 7] = offsetY;
  16004. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  16005. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  16006. var offset = (sprite.cellIndex / rowSize) >> 0;
  16007. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  16008. this._vertices[arrayOffset + 11] = offset;
  16009. // Color
  16010. this._vertices[arrayOffset + 12] = sprite.color.r;
  16011. this._vertices[arrayOffset + 13] = sprite.color.g;
  16012. this._vertices[arrayOffset + 14] = sprite.color.b;
  16013. this._vertices[arrayOffset + 15] = sprite.color.a;
  16014. };
  16015. SpriteManager.prototype.render = function () {
  16016. // Check
  16017. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  16018. return;
  16019. var engine = this._scene.getEngine();
  16020. var baseSize = this._spriteTexture.getBaseSize();
  16021. // Sprites
  16022. var deltaTime = engine.getDeltaTime();
  16023. var max = Math.min(this._capacity, this.sprites.length);
  16024. var rowSize = baseSize.width / this.cellSize;
  16025. var offset = 0;
  16026. for (var index = 0; index < max; index++) {
  16027. var sprite = this.sprites[index];
  16028. if (!sprite) {
  16029. continue;
  16030. }
  16031. sprite._animate(deltaTime);
  16032. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  16033. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  16034. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  16035. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  16036. }
  16037. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16038. // Render
  16039. var effect = this._effectBase;
  16040. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16041. effect = this._effectFog;
  16042. }
  16043. engine.enableEffect(effect);
  16044. var viewMatrix = this._scene.getViewMatrix();
  16045. effect.setTexture("diffuseSampler", this._spriteTexture);
  16046. effect.setMatrix("view", viewMatrix);
  16047. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16048. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  16049. // Fog
  16050. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16051. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  16052. effect.setColor3("vFogColor", this._scene.fogColor);
  16053. }
  16054. // VBOs
  16055. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16056. // Draw order
  16057. effect.setBool("alphaTest", true);
  16058. engine.setColorWrite(false);
  16059. engine.draw(true, 0, max * 6);
  16060. engine.setColorWrite(true);
  16061. effect.setBool("alphaTest", false);
  16062. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16063. engine.draw(true, 0, max * 6);
  16064. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16065. };
  16066. SpriteManager.prototype.dispose = function () {
  16067. if (this._vertexBuffer) {
  16068. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16069. this._vertexBuffer = null;
  16070. }
  16071. if (this._indexBuffer) {
  16072. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16073. this._indexBuffer = null;
  16074. }
  16075. if (this._spriteTexture) {
  16076. this._spriteTexture.dispose();
  16077. this._spriteTexture = null;
  16078. }
  16079. // Remove from scene
  16080. var index = this._scene.spriteManagers.indexOf(this);
  16081. this._scene.spriteManagers.splice(index, 1);
  16082. // Callback
  16083. if (this.onDispose) {
  16084. this.onDispose();
  16085. }
  16086. };
  16087. return SpriteManager;
  16088. })();
  16089. BABYLON.SpriteManager = SpriteManager;
  16090. })(BABYLON || (BABYLON = {}));
  16091. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  16092. (function (BABYLON) {
  16093. var Sprite = (function () {
  16094. function Sprite(name, manager) {
  16095. this.name = name;
  16096. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16097. this.width = 1.0;
  16098. this.height = 1.0;
  16099. this.angle = 0;
  16100. this.cellIndex = 0;
  16101. this.invertU = 0;
  16102. this.invertV = 0;
  16103. this.animations = new Array();
  16104. this._animationStarted = false;
  16105. this._loopAnimation = false;
  16106. this._fromIndex = 0;
  16107. this._toIndex = 0;
  16108. this._delay = 0;
  16109. this._direction = 1;
  16110. this._frameCount = 0;
  16111. this._time = 0;
  16112. this._manager = manager;
  16113. this._manager.sprites.push(this);
  16114. this.position = BABYLON.Vector3.Zero();
  16115. }
  16116. Object.defineProperty(Sprite.prototype, "size", {
  16117. get: function () {
  16118. return this.width;
  16119. },
  16120. set: function (value) {
  16121. this.width = value;
  16122. this.height = value;
  16123. },
  16124. enumerable: true,
  16125. configurable: true
  16126. });
  16127. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  16128. this._fromIndex = from;
  16129. this._toIndex = to;
  16130. this._loopAnimation = loop;
  16131. this._delay = delay;
  16132. this._animationStarted = true;
  16133. this._direction = from < to ? 1 : -1;
  16134. this.cellIndex = from;
  16135. this._time = 0;
  16136. };
  16137. Sprite.prototype.stopAnimation = function () {
  16138. this._animationStarted = false;
  16139. };
  16140. Sprite.prototype._animate = function (deltaTime) {
  16141. if (!this._animationStarted)
  16142. return;
  16143. this._time += deltaTime;
  16144. if (this._time > this._delay) {
  16145. this._time = this._time % this._delay;
  16146. this.cellIndex += this._direction;
  16147. if (this.cellIndex == this._toIndex) {
  16148. if (this._loopAnimation) {
  16149. this.cellIndex = this._fromIndex;
  16150. }
  16151. else {
  16152. this._animationStarted = false;
  16153. if (this.disposeWhenFinishedAnimating) {
  16154. this.dispose();
  16155. }
  16156. }
  16157. }
  16158. }
  16159. };
  16160. Sprite.prototype.dispose = function () {
  16161. for (var i = 0; i < this._manager.sprites.length; i++) {
  16162. if (this._manager.sprites[i] == this) {
  16163. this._manager.sprites.splice(i, 1);
  16164. }
  16165. }
  16166. };
  16167. return Sprite;
  16168. })();
  16169. BABYLON.Sprite = Sprite;
  16170. })(BABYLON || (BABYLON = {}));
  16171. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  16172. (function (BABYLON) {
  16173. var Layer = (function () {
  16174. function Layer(name, imgUrl, scene, isBackground, color) {
  16175. this.name = name;
  16176. this._vertexDeclaration = [2];
  16177. this._vertexStrideSize = 2 * 4;
  16178. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  16179. this.isBackground = isBackground === undefined ? true : isBackground;
  16180. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  16181. this._scene = scene;
  16182. this._scene.layers.push(this);
  16183. // VBO
  16184. var vertices = [];
  16185. vertices.push(1, 1);
  16186. vertices.push(-1, 1);
  16187. vertices.push(-1, -1);
  16188. vertices.push(1, -1);
  16189. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16190. // Indices
  16191. var indices = [];
  16192. indices.push(0);
  16193. indices.push(1);
  16194. indices.push(2);
  16195. indices.push(0);
  16196. indices.push(2);
  16197. indices.push(3);
  16198. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16199. // Effects
  16200. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  16201. }
  16202. Layer.prototype.render = function () {
  16203. // Check
  16204. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  16205. return;
  16206. var engine = this._scene.getEngine();
  16207. // Render
  16208. engine.enableEffect(this._effect);
  16209. engine.setState(false);
  16210. // Texture
  16211. this._effect.setTexture("textureSampler", this.texture);
  16212. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  16213. // Color
  16214. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  16215. // VBOs
  16216. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16217. // Draw order
  16218. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16219. engine.draw(true, 0, 6);
  16220. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16221. };
  16222. Layer.prototype.dispose = function () {
  16223. if (this._vertexBuffer) {
  16224. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16225. this._vertexBuffer = null;
  16226. }
  16227. if (this._indexBuffer) {
  16228. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16229. this._indexBuffer = null;
  16230. }
  16231. if (this.texture) {
  16232. this.texture.dispose();
  16233. this.texture = null;
  16234. }
  16235. // Remove from scene
  16236. var index = this._scene.layers.indexOf(this);
  16237. this._scene.layers.splice(index, 1);
  16238. // Callback
  16239. if (this.onDispose) {
  16240. this.onDispose();
  16241. }
  16242. };
  16243. return Layer;
  16244. })();
  16245. BABYLON.Layer = Layer;
  16246. })(BABYLON || (BABYLON = {}));
  16247. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  16248. (function (BABYLON) {
  16249. var Particle = (function () {
  16250. function Particle() {
  16251. this.position = BABYLON.Vector3.Zero();
  16252. this.direction = BABYLON.Vector3.Zero();
  16253. this.color = new BABYLON.Color4(0, 0, 0, 0);
  16254. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  16255. this.lifeTime = 1.0;
  16256. this.age = 0;
  16257. this.size = 0;
  16258. this.angle = 0;
  16259. this.angularSpeed = 0;
  16260. }
  16261. Particle.prototype.copyTo = function (other) {
  16262. other.position.copyFrom(this.position);
  16263. other.direction.copyFrom(this.direction);
  16264. other.color.copyFrom(this.color);
  16265. other.colorStep.copyFrom(this.colorStep);
  16266. other.lifeTime = this.lifeTime;
  16267. other.age = this.age;
  16268. other.size = this.size;
  16269. other.angle = this.angle;
  16270. other.angularSpeed = this.angularSpeed;
  16271. };
  16272. return Particle;
  16273. })();
  16274. BABYLON.Particle = Particle;
  16275. })(BABYLON || (BABYLON = {}));
  16276. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  16277. (function (BABYLON) {
  16278. var randomNumber = function (min, max) {
  16279. if (min === max) {
  16280. return (min);
  16281. }
  16282. var random = Math.random();
  16283. return ((random * (max - min)) + min);
  16284. };
  16285. var ParticleSystem = (function () {
  16286. function ParticleSystem(name, capacity, scene, customEffect) {
  16287. var _this = this;
  16288. this.name = name;
  16289. this.renderingGroupId = 0;
  16290. this.emitter = null;
  16291. this.emitRate = 10;
  16292. this.manualEmitCount = -1;
  16293. this.updateSpeed = 0.01;
  16294. this.targetStopDuration = 0;
  16295. this.disposeOnStop = false;
  16296. this.minEmitPower = 1;
  16297. this.maxEmitPower = 1;
  16298. this.minLifeTime = 1;
  16299. this.maxLifeTime = 1;
  16300. this.minSize = 1;
  16301. this.maxSize = 1;
  16302. this.minAngularSpeed = 0;
  16303. this.maxAngularSpeed = 0;
  16304. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  16305. this.forceDepthWrite = false;
  16306. this.gravity = BABYLON.Vector3.Zero();
  16307. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  16308. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  16309. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  16310. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16311. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16312. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16313. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  16314. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16315. this.particles = new Array();
  16316. this._vertexDeclaration = [3, 4, 4];
  16317. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  16318. this._stockParticles = new Array();
  16319. this._newPartsExcess = 0;
  16320. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  16321. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  16322. this._scaledDirection = BABYLON.Vector3.Zero();
  16323. this._scaledGravity = BABYLON.Vector3.Zero();
  16324. this._currentRenderId = -1;
  16325. this._started = false;
  16326. this._stopped = false;
  16327. this._actualFrame = 0;
  16328. this.id = name;
  16329. this._capacity = capacity;
  16330. this._scene = scene;
  16331. this._customEffect = customEffect;
  16332. scene.particleSystems.push(this);
  16333. // VBO
  16334. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16335. var indices = [];
  16336. var index = 0;
  16337. for (var count = 0; count < capacity; count++) {
  16338. indices.push(index);
  16339. indices.push(index + 1);
  16340. indices.push(index + 2);
  16341. indices.push(index);
  16342. indices.push(index + 2);
  16343. indices.push(index + 3);
  16344. index += 4;
  16345. }
  16346. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16347. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16348. // Default behaviors
  16349. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  16350. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  16351. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  16352. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  16353. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  16354. };
  16355. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  16356. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  16357. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  16358. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  16359. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  16360. };
  16361. this.updateFunction = function (particles) {
  16362. for (var index = 0; index < particles.length; index++) {
  16363. var particle = particles[index];
  16364. particle.age += _this._scaledUpdateSpeed;
  16365. if (particle.age >= particle.lifeTime) {
  16366. _this.recycleParticle(particle);
  16367. index--;
  16368. continue;
  16369. }
  16370. else {
  16371. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  16372. particle.color.addInPlace(_this._scaledColorStep);
  16373. if (particle.color.a < 0)
  16374. particle.color.a = 0;
  16375. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  16376. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  16377. particle.position.addInPlace(_this._scaledDirection);
  16378. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  16379. particle.direction.addInPlace(_this._scaledGravity);
  16380. }
  16381. }
  16382. };
  16383. }
  16384. ParticleSystem.prototype.recycleParticle = function (particle) {
  16385. var lastParticle = this.particles.pop();
  16386. if (lastParticle !== particle) {
  16387. lastParticle.copyTo(particle);
  16388. this._stockParticles.push(lastParticle);
  16389. }
  16390. };
  16391. ParticleSystem.prototype.getCapacity = function () {
  16392. return this._capacity;
  16393. };
  16394. ParticleSystem.prototype.isAlive = function () {
  16395. return this._alive;
  16396. };
  16397. ParticleSystem.prototype.isStarted = function () {
  16398. return this._started;
  16399. };
  16400. ParticleSystem.prototype.start = function () {
  16401. this._started = true;
  16402. this._stopped = false;
  16403. this._actualFrame = 0;
  16404. };
  16405. ParticleSystem.prototype.stop = function () {
  16406. this._stopped = true;
  16407. };
  16408. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  16409. var offset = index * 11;
  16410. this._vertices[offset] = particle.position.x;
  16411. this._vertices[offset + 1] = particle.position.y;
  16412. this._vertices[offset + 2] = particle.position.z;
  16413. this._vertices[offset + 3] = particle.color.r;
  16414. this._vertices[offset + 4] = particle.color.g;
  16415. this._vertices[offset + 5] = particle.color.b;
  16416. this._vertices[offset + 6] = particle.color.a;
  16417. this._vertices[offset + 7] = particle.angle;
  16418. this._vertices[offset + 8] = particle.size;
  16419. this._vertices[offset + 9] = offsetX;
  16420. this._vertices[offset + 10] = offsetY;
  16421. };
  16422. ParticleSystem.prototype._update = function (newParticles) {
  16423. // Update current
  16424. this._alive = this.particles.length > 0;
  16425. this.updateFunction(this.particles);
  16426. // Add new ones
  16427. var worldMatrix;
  16428. if (this.emitter.position) {
  16429. worldMatrix = this.emitter.getWorldMatrix();
  16430. }
  16431. else {
  16432. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  16433. }
  16434. for (var index = 0; index < newParticles; index++) {
  16435. if (this.particles.length === this._capacity) {
  16436. break;
  16437. }
  16438. if (this._stockParticles.length !== 0) {
  16439. var particle = this._stockParticles.pop();
  16440. particle.age = 0;
  16441. }
  16442. else {
  16443. particle = new BABYLON.Particle();
  16444. }
  16445. this.particles.push(particle);
  16446. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  16447. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  16448. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  16449. particle.size = randomNumber(this.minSize, this.maxSize);
  16450. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  16451. this.startPositionFunction(worldMatrix, particle.position);
  16452. var step = randomNumber(0, 1.0);
  16453. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  16454. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  16455. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  16456. }
  16457. };
  16458. ParticleSystem.prototype._getEffect = function () {
  16459. if (this._customEffect) {
  16460. return this._customEffect;
  16461. }
  16462. ;
  16463. var defines = [];
  16464. if (this._scene.clipPlane) {
  16465. defines.push("#define CLIPPLANE");
  16466. }
  16467. // Effect
  16468. var join = defines.join("\n");
  16469. if (this._cachedDefines !== join) {
  16470. this._cachedDefines = join;
  16471. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16472. }
  16473. return this._effect;
  16474. };
  16475. ParticleSystem.prototype.animate = function () {
  16476. if (!this._started)
  16477. return;
  16478. var effect = this._getEffect();
  16479. // Check
  16480. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16481. return;
  16482. if (this._currentRenderId === this._scene.getRenderId()) {
  16483. return;
  16484. }
  16485. this._currentRenderId = this._scene.getRenderId();
  16486. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16487. // determine the number of particles we need to create
  16488. var emitCout;
  16489. if (this.manualEmitCount > -1) {
  16490. emitCout = this.manualEmitCount;
  16491. this.manualEmitCount = 0;
  16492. }
  16493. else {
  16494. emitCout = this.emitRate;
  16495. }
  16496. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16497. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16498. if (this._newPartsExcess > 1.0) {
  16499. newParticles += this._newPartsExcess >> 0;
  16500. this._newPartsExcess -= this._newPartsExcess >> 0;
  16501. }
  16502. this._alive = false;
  16503. if (!this._stopped) {
  16504. this._actualFrame += this._scaledUpdateSpeed;
  16505. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16506. this.stop();
  16507. }
  16508. else {
  16509. newParticles = 0;
  16510. }
  16511. this._update(newParticles);
  16512. // Stopped?
  16513. if (this._stopped) {
  16514. if (!this._alive) {
  16515. this._started = false;
  16516. if (this.disposeOnStop) {
  16517. this._scene._toBeDisposed.push(this);
  16518. }
  16519. }
  16520. }
  16521. // Update VBO
  16522. var offset = 0;
  16523. for (var index = 0; index < this.particles.length; index++) {
  16524. var particle = this.particles[index];
  16525. this._appendParticleVertex(offset++, particle, 0, 0);
  16526. this._appendParticleVertex(offset++, particle, 1, 0);
  16527. this._appendParticleVertex(offset++, particle, 1, 1);
  16528. this._appendParticleVertex(offset++, particle, 0, 1);
  16529. }
  16530. var engine = this._scene.getEngine();
  16531. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16532. };
  16533. ParticleSystem.prototype.render = function () {
  16534. var effect = this._getEffect();
  16535. // Check
  16536. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16537. return 0;
  16538. var engine = this._scene.getEngine();
  16539. // Render
  16540. engine.enableEffect(effect);
  16541. engine.setState(false);
  16542. var viewMatrix = this._scene.getViewMatrix();
  16543. effect.setTexture("diffuseSampler", this.particleTexture);
  16544. effect.setMatrix("view", viewMatrix);
  16545. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16546. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16547. if (this._scene.clipPlane) {
  16548. var clipPlane = this._scene.clipPlane;
  16549. var invView = viewMatrix.clone();
  16550. invView.invert();
  16551. effect.setMatrix("invView", invView);
  16552. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16553. }
  16554. // VBOs
  16555. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16556. // Draw order
  16557. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16558. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16559. }
  16560. else {
  16561. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16562. }
  16563. if (this.forceDepthWrite) {
  16564. engine.setDepthWrite(true);
  16565. }
  16566. engine.draw(true, 0, this.particles.length * 6);
  16567. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16568. return this.particles.length;
  16569. };
  16570. ParticleSystem.prototype.dispose = function () {
  16571. if (this._vertexBuffer) {
  16572. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16573. this._vertexBuffer = null;
  16574. }
  16575. if (this._indexBuffer) {
  16576. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16577. this._indexBuffer = null;
  16578. }
  16579. if (this.particleTexture) {
  16580. this.particleTexture.dispose();
  16581. this.particleTexture = null;
  16582. }
  16583. // Remove from scene
  16584. var index = this._scene.particleSystems.indexOf(this);
  16585. this._scene.particleSystems.splice(index, 1);
  16586. // Callback
  16587. if (this.onDispose) {
  16588. this.onDispose();
  16589. }
  16590. };
  16591. // Clone
  16592. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16593. var result = new ParticleSystem(name, this._capacity, this._scene);
  16594. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16595. if (newEmitter === undefined) {
  16596. newEmitter = this.emitter;
  16597. }
  16598. result.emitter = newEmitter;
  16599. if (this.particleTexture) {
  16600. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16601. }
  16602. result.start();
  16603. return result;
  16604. };
  16605. // Statics
  16606. ParticleSystem.BLENDMODE_ONEONE = 0;
  16607. ParticleSystem.BLENDMODE_STANDARD = 1;
  16608. return ParticleSystem;
  16609. })();
  16610. BABYLON.ParticleSystem = ParticleSystem;
  16611. })(BABYLON || (BABYLON = {}));
  16612. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16613. (function (BABYLON) {
  16614. var Animation = (function () {
  16615. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16616. this.name = name;
  16617. this.targetProperty = targetProperty;
  16618. this.framePerSecond = framePerSecond;
  16619. this.dataType = dataType;
  16620. this.loopMode = loopMode;
  16621. this._offsetsCache = {};
  16622. this._highLimitsCache = {};
  16623. this._stopped = false;
  16624. this.targetPropertyPath = targetProperty.split(".");
  16625. this.dataType = dataType;
  16626. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16627. }
  16628. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16629. var dataType = undefined;
  16630. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16631. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16632. }
  16633. else if (from instanceof BABYLON.Quaternion) {
  16634. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16635. }
  16636. else if (from instanceof BABYLON.Vector3) {
  16637. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16638. }
  16639. else if (from instanceof BABYLON.Vector2) {
  16640. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16641. }
  16642. else if (from instanceof BABYLON.Color3) {
  16643. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16644. }
  16645. if (dataType == undefined) {
  16646. return null;
  16647. }
  16648. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16649. var keys = [];
  16650. keys.push({ frame: 0, value: from });
  16651. keys.push({ frame: totalFrame, value: to });
  16652. animation.setKeys(keys);
  16653. mesh.animations.push(animation);
  16654. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16655. };
  16656. // Methods
  16657. Animation.prototype.isStopped = function () {
  16658. return this._stopped;
  16659. };
  16660. Animation.prototype.getKeys = function () {
  16661. return this._keys;
  16662. };
  16663. Animation.prototype.getEasingFunction = function () {
  16664. return this._easingFunction;
  16665. };
  16666. Animation.prototype.setEasingFunction = function (easingFunction) {
  16667. this._easingFunction = easingFunction;
  16668. };
  16669. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16670. return startValue + (endValue - startValue) * gradient;
  16671. };
  16672. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16673. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16674. };
  16675. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16676. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16677. };
  16678. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16679. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16680. };
  16681. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16682. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16683. };
  16684. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16685. var startScale = new BABYLON.Vector3(0, 0, 0);
  16686. var startRotation = new BABYLON.Quaternion();
  16687. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16688. startValue.decompose(startScale, startRotation, startTranslation);
  16689. var endScale = new BABYLON.Vector3(0, 0, 0);
  16690. var endRotation = new BABYLON.Quaternion();
  16691. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16692. endValue.decompose(endScale, endRotation, endTranslation);
  16693. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16694. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16695. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16696. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16697. return result;
  16698. };
  16699. Animation.prototype.clone = function () {
  16700. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16701. clone.setKeys(this._keys);
  16702. return clone;
  16703. };
  16704. Animation.prototype.setKeys = function (values) {
  16705. this._keys = values.slice(0);
  16706. this._offsetsCache = {};
  16707. this._highLimitsCache = {};
  16708. };
  16709. Animation.prototype._getKeyValue = function (value) {
  16710. if (typeof value === "function") {
  16711. return value();
  16712. }
  16713. return value;
  16714. };
  16715. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16716. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16717. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16718. }
  16719. this.currentFrame = currentFrame;
  16720. // Try to get a hash to find the right key
  16721. 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));
  16722. if (this._keys[startKey].frame >= currentFrame) {
  16723. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16724. startKey--;
  16725. }
  16726. }
  16727. for (var key = startKey; key < this._keys.length; key++) {
  16728. if (this._keys[key + 1].frame >= currentFrame) {
  16729. var startValue = this._getKeyValue(this._keys[key].value);
  16730. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16731. // gradient : percent of currentFrame between the frame inf and the frame sup
  16732. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16733. // check for easingFunction and correction of gradient
  16734. if (this._easingFunction != null) {
  16735. gradient = this._easingFunction.ease(gradient);
  16736. }
  16737. switch (this.dataType) {
  16738. case Animation.ANIMATIONTYPE_FLOAT:
  16739. switch (loopMode) {
  16740. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16741. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16742. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16743. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16744. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16745. }
  16746. break;
  16747. case Animation.ANIMATIONTYPE_QUATERNION:
  16748. var quaternion = null;
  16749. switch (loopMode) {
  16750. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16751. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16752. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16753. break;
  16754. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16755. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16756. break;
  16757. }
  16758. return quaternion;
  16759. case Animation.ANIMATIONTYPE_VECTOR3:
  16760. switch (loopMode) {
  16761. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16762. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16763. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16764. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16765. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16766. }
  16767. case Animation.ANIMATIONTYPE_VECTOR2:
  16768. switch (loopMode) {
  16769. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16770. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16771. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16772. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16773. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16774. }
  16775. case Animation.ANIMATIONTYPE_COLOR3:
  16776. switch (loopMode) {
  16777. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16778. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16779. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16780. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16781. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16782. }
  16783. case Animation.ANIMATIONTYPE_MATRIX:
  16784. switch (loopMode) {
  16785. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16786. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16787. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16788. return startValue;
  16789. }
  16790. default:
  16791. break;
  16792. }
  16793. break;
  16794. }
  16795. }
  16796. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16797. };
  16798. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16799. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16800. this._stopped = true;
  16801. return false;
  16802. }
  16803. var returnValue = true;
  16804. // Adding a start key at frame 0 if missing
  16805. if (this._keys[0].frame !== 0) {
  16806. var newKey = { frame: 0, value: this._keys[0].value };
  16807. this._keys.splice(0, 0, newKey);
  16808. }
  16809. // Check limits
  16810. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16811. from = this._keys[0].frame;
  16812. }
  16813. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16814. to = this._keys[this._keys.length - 1].frame;
  16815. }
  16816. // Compute ratio
  16817. var range = to - from;
  16818. var offsetValue;
  16819. // ratio represents the frame delta between from and to
  16820. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16821. var highLimitValue = 0;
  16822. if (ratio > range && !loop) {
  16823. returnValue = false;
  16824. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16825. }
  16826. else {
  16827. // Get max value if required
  16828. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16829. var keyOffset = to.toString() + from.toString();
  16830. if (!this._offsetsCache[keyOffset]) {
  16831. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16832. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16833. switch (this.dataType) {
  16834. case Animation.ANIMATIONTYPE_FLOAT:
  16835. this._offsetsCache[keyOffset] = toValue - fromValue;
  16836. break;
  16837. case Animation.ANIMATIONTYPE_QUATERNION:
  16838. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16839. break;
  16840. case Animation.ANIMATIONTYPE_VECTOR3:
  16841. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16842. case Animation.ANIMATIONTYPE_VECTOR2:
  16843. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16844. case Animation.ANIMATIONTYPE_COLOR3:
  16845. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16846. default:
  16847. break;
  16848. }
  16849. this._highLimitsCache[keyOffset] = toValue;
  16850. }
  16851. highLimitValue = this._highLimitsCache[keyOffset];
  16852. offsetValue = this._offsetsCache[keyOffset];
  16853. }
  16854. }
  16855. if (offsetValue === undefined) {
  16856. switch (this.dataType) {
  16857. case Animation.ANIMATIONTYPE_FLOAT:
  16858. offsetValue = 0;
  16859. break;
  16860. case Animation.ANIMATIONTYPE_QUATERNION:
  16861. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16862. break;
  16863. case Animation.ANIMATIONTYPE_VECTOR3:
  16864. offsetValue = BABYLON.Vector3.Zero();
  16865. break;
  16866. case Animation.ANIMATIONTYPE_VECTOR2:
  16867. offsetValue = BABYLON.Vector2.Zero();
  16868. break;
  16869. case Animation.ANIMATIONTYPE_COLOR3:
  16870. offsetValue = BABYLON.Color3.Black();
  16871. }
  16872. }
  16873. // Compute value
  16874. var repeatCount = (ratio / range) >> 0;
  16875. var currentFrame = returnValue ? from + ratio % range : to;
  16876. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16877. // Set value
  16878. if (this.targetPropertyPath.length > 1) {
  16879. var property = this._target[this.targetPropertyPath[0]];
  16880. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16881. property = property[this.targetPropertyPath[index]];
  16882. }
  16883. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16884. }
  16885. else {
  16886. this._target[this.targetPropertyPath[0]] = currentValue;
  16887. }
  16888. if (this._target.markAsDirty) {
  16889. this._target.markAsDirty(this.targetProperty);
  16890. }
  16891. if (!returnValue) {
  16892. this._stopped = true;
  16893. }
  16894. return returnValue;
  16895. };
  16896. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16897. get: function () {
  16898. return Animation._ANIMATIONTYPE_FLOAT;
  16899. },
  16900. enumerable: true,
  16901. configurable: true
  16902. });
  16903. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16904. get: function () {
  16905. return Animation._ANIMATIONTYPE_VECTOR3;
  16906. },
  16907. enumerable: true,
  16908. configurable: true
  16909. });
  16910. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16911. get: function () {
  16912. return Animation._ANIMATIONTYPE_VECTOR2;
  16913. },
  16914. enumerable: true,
  16915. configurable: true
  16916. });
  16917. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16918. get: function () {
  16919. return Animation._ANIMATIONTYPE_QUATERNION;
  16920. },
  16921. enumerable: true,
  16922. configurable: true
  16923. });
  16924. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16925. get: function () {
  16926. return Animation._ANIMATIONTYPE_MATRIX;
  16927. },
  16928. enumerable: true,
  16929. configurable: true
  16930. });
  16931. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16932. get: function () {
  16933. return Animation._ANIMATIONTYPE_COLOR3;
  16934. },
  16935. enumerable: true,
  16936. configurable: true
  16937. });
  16938. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16939. get: function () {
  16940. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16941. },
  16942. enumerable: true,
  16943. configurable: true
  16944. });
  16945. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16946. get: function () {
  16947. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16948. },
  16949. enumerable: true,
  16950. configurable: true
  16951. });
  16952. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16953. get: function () {
  16954. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16955. },
  16956. enumerable: true,
  16957. configurable: true
  16958. });
  16959. // Statics
  16960. Animation._ANIMATIONTYPE_FLOAT = 0;
  16961. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16962. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16963. Animation._ANIMATIONTYPE_MATRIX = 3;
  16964. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16965. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16966. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16967. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16968. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16969. return Animation;
  16970. })();
  16971. BABYLON.Animation = Animation;
  16972. })(BABYLON || (BABYLON = {}));
  16973. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16974. (function (BABYLON) {
  16975. var Animatable = (function () {
  16976. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16977. if (fromFrame === void 0) { fromFrame = 0; }
  16978. if (toFrame === void 0) { toFrame = 100; }
  16979. if (loopAnimation === void 0) { loopAnimation = false; }
  16980. if (speedRatio === void 0) { speedRatio = 1.0; }
  16981. this.target = target;
  16982. this.fromFrame = fromFrame;
  16983. this.toFrame = toFrame;
  16984. this.loopAnimation = loopAnimation;
  16985. this.speedRatio = speedRatio;
  16986. this.onAnimationEnd = onAnimationEnd;
  16987. this._animations = new Array();
  16988. this._paused = false;
  16989. this.animationStarted = false;
  16990. if (animations) {
  16991. this.appendAnimations(target, animations);
  16992. }
  16993. this._scene = scene;
  16994. scene._activeAnimatables.push(this);
  16995. }
  16996. // Methods
  16997. Animatable.prototype.appendAnimations = function (target, animations) {
  16998. for (var index = 0; index < animations.length; index++) {
  16999. var animation = animations[index];
  17000. animation._target = target;
  17001. this._animations.push(animation);
  17002. }
  17003. };
  17004. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  17005. var animations = this._animations;
  17006. for (var index = 0; index < animations.length; index++) {
  17007. if (animations[index].targetProperty === property) {
  17008. return animations[index];
  17009. }
  17010. }
  17011. return null;
  17012. };
  17013. Animatable.prototype.pause = function () {
  17014. if (this._paused) {
  17015. return;
  17016. }
  17017. this._paused = true;
  17018. };
  17019. Animatable.prototype.restart = function () {
  17020. this._paused = false;
  17021. };
  17022. Animatable.prototype.stop = function () {
  17023. var index = this._scene._activeAnimatables.indexOf(this);
  17024. if (index > -1) {
  17025. this._scene._activeAnimatables.splice(index, 1);
  17026. }
  17027. if (this.onAnimationEnd) {
  17028. this.onAnimationEnd();
  17029. }
  17030. };
  17031. Animatable.prototype._animate = function (delay) {
  17032. if (this._paused) {
  17033. if (!this._pausedDelay) {
  17034. this._pausedDelay = delay;
  17035. }
  17036. return true;
  17037. }
  17038. if (!this._localDelayOffset) {
  17039. this._localDelayOffset = delay;
  17040. }
  17041. else if (this._pausedDelay) {
  17042. this._localDelayOffset += delay - this._pausedDelay;
  17043. this._pausedDelay = null;
  17044. }
  17045. // Animating
  17046. var running = false;
  17047. var animations = this._animations;
  17048. for (var index = 0; index < animations.length; index++) {
  17049. var animation = animations[index];
  17050. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  17051. running = running || isRunning;
  17052. }
  17053. if (!running) {
  17054. // Remove from active animatables
  17055. index = this._scene._activeAnimatables.indexOf(this);
  17056. this._scene._activeAnimatables.splice(index, 1);
  17057. }
  17058. if (!running && this.onAnimationEnd) {
  17059. this.onAnimationEnd();
  17060. }
  17061. return running;
  17062. };
  17063. return Animatable;
  17064. })();
  17065. BABYLON.Animatable = Animatable;
  17066. })(BABYLON || (BABYLON = {}));
  17067. //# sourceMappingURL=babylon.animatable.js.map
  17068. var BABYLON;
  17069. (function (BABYLON) {
  17070. var EasingFunction = (function () {
  17071. function EasingFunction() {
  17072. // Properties
  17073. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  17074. }
  17075. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  17076. get: function () {
  17077. return EasingFunction._EASINGMODE_EASEIN;
  17078. },
  17079. enumerable: true,
  17080. configurable: true
  17081. });
  17082. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  17083. get: function () {
  17084. return EasingFunction._EASINGMODE_EASEOUT;
  17085. },
  17086. enumerable: true,
  17087. configurable: true
  17088. });
  17089. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  17090. get: function () {
  17091. return EasingFunction._EASINGMODE_EASEINOUT;
  17092. },
  17093. enumerable: true,
  17094. configurable: true
  17095. });
  17096. EasingFunction.prototype.setEasingMode = function (easingMode) {
  17097. var n = Math.min(Math.max(easingMode, 0), 2);
  17098. this._easingMode = n;
  17099. };
  17100. EasingFunction.prototype.getEasingMode = function () {
  17101. return this._easingMode;
  17102. };
  17103. EasingFunction.prototype.easeInCore = function (gradient) {
  17104. throw new Error('You must implement this method');
  17105. };
  17106. EasingFunction.prototype.ease = function (gradient) {
  17107. switch (this._easingMode) {
  17108. case EasingFunction.EASINGMODE_EASEIN:
  17109. return this.easeInCore(gradient);
  17110. case EasingFunction.EASINGMODE_EASEOUT:
  17111. return (1 - this.easeInCore(1 - gradient));
  17112. }
  17113. if (gradient >= 0.5) {
  17114. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  17115. }
  17116. return (this.easeInCore(gradient * 2) * 0.5);
  17117. };
  17118. //Statics
  17119. EasingFunction._EASINGMODE_EASEIN = 0;
  17120. EasingFunction._EASINGMODE_EASEOUT = 1;
  17121. EasingFunction._EASINGMODE_EASEINOUT = 2;
  17122. return EasingFunction;
  17123. })();
  17124. BABYLON.EasingFunction = EasingFunction;
  17125. var CircleEase = (function (_super) {
  17126. __extends(CircleEase, _super);
  17127. function CircleEase() {
  17128. _super.apply(this, arguments);
  17129. }
  17130. CircleEase.prototype.easeInCore = function (gradient) {
  17131. gradient = Math.max(0, Math.min(1, gradient));
  17132. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  17133. };
  17134. return CircleEase;
  17135. })(EasingFunction);
  17136. BABYLON.CircleEase = CircleEase;
  17137. var BackEase = (function (_super) {
  17138. __extends(BackEase, _super);
  17139. function BackEase(amplitude) {
  17140. if (amplitude === void 0) { amplitude = 1; }
  17141. _super.call(this);
  17142. this.amplitude = amplitude;
  17143. }
  17144. BackEase.prototype.easeInCore = function (gradient) {
  17145. var num = Math.max(0, this.amplitude);
  17146. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  17147. };
  17148. return BackEase;
  17149. })(EasingFunction);
  17150. BABYLON.BackEase = BackEase;
  17151. var BounceEase = (function (_super) {
  17152. __extends(BounceEase, _super);
  17153. function BounceEase(bounces, bounciness) {
  17154. if (bounces === void 0) { bounces = 3; }
  17155. if (bounciness === void 0) { bounciness = 2; }
  17156. _super.call(this);
  17157. this.bounces = bounces;
  17158. this.bounciness = bounciness;
  17159. }
  17160. BounceEase.prototype.easeInCore = function (gradient) {
  17161. var y = Math.max(0.0, this.bounces);
  17162. var bounciness = this.bounciness;
  17163. if (bounciness <= 1.0) {
  17164. bounciness = 1.001;
  17165. }
  17166. var num9 = Math.pow(bounciness, y);
  17167. var num5 = 1.0 - bounciness;
  17168. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  17169. var num15 = gradient * num4;
  17170. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  17171. var num3 = Math.floor(num65);
  17172. var num13 = num3 + 1.0;
  17173. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  17174. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  17175. var num7 = (num8 + num12) * 0.5;
  17176. var num6 = gradient - num7;
  17177. var num2 = num7 - num8;
  17178. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  17179. };
  17180. return BounceEase;
  17181. })(EasingFunction);
  17182. BABYLON.BounceEase = BounceEase;
  17183. var CubicEase = (function (_super) {
  17184. __extends(CubicEase, _super);
  17185. function CubicEase() {
  17186. _super.apply(this, arguments);
  17187. }
  17188. CubicEase.prototype.easeInCore = function (gradient) {
  17189. return (gradient * gradient * gradient);
  17190. };
  17191. return CubicEase;
  17192. })(EasingFunction);
  17193. BABYLON.CubicEase = CubicEase;
  17194. var ElasticEase = (function (_super) {
  17195. __extends(ElasticEase, _super);
  17196. function ElasticEase(oscillations, springiness) {
  17197. if (oscillations === void 0) { oscillations = 3; }
  17198. if (springiness === void 0) { springiness = 3; }
  17199. _super.call(this);
  17200. this.oscillations = oscillations;
  17201. this.springiness = springiness;
  17202. }
  17203. ElasticEase.prototype.easeInCore = function (gradient) {
  17204. var num2;
  17205. var num3 = Math.max(0.0, this.oscillations);
  17206. var num = Math.max(0.0, this.springiness);
  17207. if (num == 0) {
  17208. num2 = gradient;
  17209. }
  17210. else {
  17211. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  17212. }
  17213. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  17214. };
  17215. return ElasticEase;
  17216. })(EasingFunction);
  17217. BABYLON.ElasticEase = ElasticEase;
  17218. var ExponentialEase = (function (_super) {
  17219. __extends(ExponentialEase, _super);
  17220. function ExponentialEase(exponent) {
  17221. if (exponent === void 0) { exponent = 2; }
  17222. _super.call(this);
  17223. this.exponent = exponent;
  17224. }
  17225. ExponentialEase.prototype.easeInCore = function (gradient) {
  17226. if (this.exponent <= 0) {
  17227. return gradient;
  17228. }
  17229. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  17230. };
  17231. return ExponentialEase;
  17232. })(EasingFunction);
  17233. BABYLON.ExponentialEase = ExponentialEase;
  17234. var PowerEase = (function (_super) {
  17235. __extends(PowerEase, _super);
  17236. function PowerEase(power) {
  17237. if (power === void 0) { power = 2; }
  17238. _super.call(this);
  17239. this.power = power;
  17240. }
  17241. PowerEase.prototype.easeInCore = function (gradient) {
  17242. var y = Math.max(0.0, this.power);
  17243. return Math.pow(gradient, y);
  17244. };
  17245. return PowerEase;
  17246. })(EasingFunction);
  17247. BABYLON.PowerEase = PowerEase;
  17248. var QuadraticEase = (function (_super) {
  17249. __extends(QuadraticEase, _super);
  17250. function QuadraticEase() {
  17251. _super.apply(this, arguments);
  17252. }
  17253. QuadraticEase.prototype.easeInCore = function (gradient) {
  17254. return (gradient * gradient);
  17255. };
  17256. return QuadraticEase;
  17257. })(EasingFunction);
  17258. BABYLON.QuadraticEase = QuadraticEase;
  17259. var QuarticEase = (function (_super) {
  17260. __extends(QuarticEase, _super);
  17261. function QuarticEase() {
  17262. _super.apply(this, arguments);
  17263. }
  17264. QuarticEase.prototype.easeInCore = function (gradient) {
  17265. return (gradient * gradient * gradient * gradient);
  17266. };
  17267. return QuarticEase;
  17268. })(EasingFunction);
  17269. BABYLON.QuarticEase = QuarticEase;
  17270. var QuinticEase = (function (_super) {
  17271. __extends(QuinticEase, _super);
  17272. function QuinticEase() {
  17273. _super.apply(this, arguments);
  17274. }
  17275. QuinticEase.prototype.easeInCore = function (gradient) {
  17276. return (gradient * gradient * gradient * gradient * gradient);
  17277. };
  17278. return QuinticEase;
  17279. })(EasingFunction);
  17280. BABYLON.QuinticEase = QuinticEase;
  17281. var SineEase = (function (_super) {
  17282. __extends(SineEase, _super);
  17283. function SineEase() {
  17284. _super.apply(this, arguments);
  17285. }
  17286. SineEase.prototype.easeInCore = function (gradient) {
  17287. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  17288. };
  17289. return SineEase;
  17290. })(EasingFunction);
  17291. BABYLON.SineEase = SineEase;
  17292. var BezierCurveEase = (function (_super) {
  17293. __extends(BezierCurveEase, _super);
  17294. function BezierCurveEase(x1, y1, x2, y2) {
  17295. if (x1 === void 0) { x1 = 0; }
  17296. if (y1 === void 0) { y1 = 0; }
  17297. if (x2 === void 0) { x2 = 1; }
  17298. if (y2 === void 0) { y2 = 1; }
  17299. _super.call(this);
  17300. this.x1 = x1;
  17301. this.y1 = y1;
  17302. this.x2 = x2;
  17303. this.y2 = y2;
  17304. }
  17305. BezierCurveEase.prototype.easeInCore = function (gradient) {
  17306. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  17307. };
  17308. return BezierCurveEase;
  17309. })(EasingFunction);
  17310. BABYLON.BezierCurveEase = BezierCurveEase;
  17311. })(BABYLON || (BABYLON = {}));
  17312. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  17313. (function (BABYLON) {
  17314. var Octree = (function () {
  17315. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  17316. if (maxDepth === void 0) { maxDepth = 2; }
  17317. this.maxDepth = maxDepth;
  17318. this.dynamicContent = new Array();
  17319. this._maxBlockCapacity = maxBlockCapacity || 64;
  17320. this._selectionContent = new BABYLON.SmartArray(1024);
  17321. this._creationFunc = creationFunc;
  17322. }
  17323. // Methods
  17324. Octree.prototype.update = function (worldMin, worldMax, entries) {
  17325. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  17326. };
  17327. Octree.prototype.addMesh = function (entry) {
  17328. for (var index = 0; index < this.blocks.length; index++) {
  17329. var block = this.blocks[index];
  17330. block.addEntry(entry);
  17331. }
  17332. };
  17333. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  17334. this._selectionContent.reset();
  17335. for (var index = 0; index < this.blocks.length; index++) {
  17336. var block = this.blocks[index];
  17337. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  17338. }
  17339. if (allowDuplicate) {
  17340. this._selectionContent.concat(this.dynamicContent);
  17341. }
  17342. else {
  17343. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17344. }
  17345. return this._selectionContent;
  17346. };
  17347. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  17348. this._selectionContent.reset();
  17349. for (var index = 0; index < this.blocks.length; index++) {
  17350. var block = this.blocks[index];
  17351. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  17352. }
  17353. if (allowDuplicate) {
  17354. this._selectionContent.concat(this.dynamicContent);
  17355. }
  17356. else {
  17357. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17358. }
  17359. return this._selectionContent;
  17360. };
  17361. Octree.prototype.intersectsRay = function (ray) {
  17362. this._selectionContent.reset();
  17363. for (var index = 0; index < this.blocks.length; index++) {
  17364. var block = this.blocks[index];
  17365. block.intersectsRay(ray, this._selectionContent);
  17366. }
  17367. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17368. return this._selectionContent;
  17369. };
  17370. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  17371. target.blocks = new Array();
  17372. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  17373. for (var x = 0; x < 2; x++) {
  17374. for (var y = 0; y < 2; y++) {
  17375. for (var z = 0; z < 2; z++) {
  17376. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  17377. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  17378. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  17379. block.addEntries(entries);
  17380. target.blocks.push(block);
  17381. }
  17382. }
  17383. }
  17384. };
  17385. Octree.CreationFuncForMeshes = function (entry, block) {
  17386. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17387. block.entries.push(entry);
  17388. }
  17389. };
  17390. Octree.CreationFuncForSubMeshes = function (entry, block) {
  17391. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17392. block.entries.push(entry);
  17393. }
  17394. };
  17395. return Octree;
  17396. })();
  17397. BABYLON.Octree = Octree;
  17398. })(BABYLON || (BABYLON = {}));
  17399. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  17400. (function (BABYLON) {
  17401. var OctreeBlock = (function () {
  17402. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  17403. this.entries = new Array();
  17404. this._boundingVectors = new Array();
  17405. this._capacity = capacity;
  17406. this._depth = depth;
  17407. this._maxDepth = maxDepth;
  17408. this._creationFunc = creationFunc;
  17409. this._minPoint = minPoint;
  17410. this._maxPoint = maxPoint;
  17411. this._boundingVectors.push(minPoint.clone());
  17412. this._boundingVectors.push(maxPoint.clone());
  17413. this._boundingVectors.push(minPoint.clone());
  17414. this._boundingVectors[2].x = maxPoint.x;
  17415. this._boundingVectors.push(minPoint.clone());
  17416. this._boundingVectors[3].y = maxPoint.y;
  17417. this._boundingVectors.push(minPoint.clone());
  17418. this._boundingVectors[4].z = maxPoint.z;
  17419. this._boundingVectors.push(maxPoint.clone());
  17420. this._boundingVectors[5].z = minPoint.z;
  17421. this._boundingVectors.push(maxPoint.clone());
  17422. this._boundingVectors[6].x = minPoint.x;
  17423. this._boundingVectors.push(maxPoint.clone());
  17424. this._boundingVectors[7].y = minPoint.y;
  17425. }
  17426. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  17427. // Property
  17428. get: function () {
  17429. return this._capacity;
  17430. },
  17431. enumerable: true,
  17432. configurable: true
  17433. });
  17434. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  17435. get: function () {
  17436. return this._minPoint;
  17437. },
  17438. enumerable: true,
  17439. configurable: true
  17440. });
  17441. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  17442. get: function () {
  17443. return this._maxPoint;
  17444. },
  17445. enumerable: true,
  17446. configurable: true
  17447. });
  17448. // Methods
  17449. OctreeBlock.prototype.addEntry = function (entry) {
  17450. if (this.blocks) {
  17451. for (var index = 0; index < this.blocks.length; index++) {
  17452. var block = this.blocks[index];
  17453. block.addEntry(entry);
  17454. }
  17455. return;
  17456. }
  17457. this._creationFunc(entry, this);
  17458. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  17459. this.createInnerBlocks();
  17460. }
  17461. };
  17462. OctreeBlock.prototype.addEntries = function (entries) {
  17463. for (var index = 0; index < entries.length; index++) {
  17464. var mesh = entries[index];
  17465. this.addEntry(mesh);
  17466. }
  17467. };
  17468. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  17469. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17470. if (this.blocks) {
  17471. for (var index = 0; index < this.blocks.length; index++) {
  17472. var block = this.blocks[index];
  17473. block.select(frustumPlanes, selection, allowDuplicate);
  17474. }
  17475. return;
  17476. }
  17477. if (allowDuplicate) {
  17478. selection.concat(this.entries);
  17479. }
  17480. else {
  17481. selection.concatWithNoDuplicate(this.entries);
  17482. }
  17483. }
  17484. };
  17485. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17486. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17487. if (this.blocks) {
  17488. for (var index = 0; index < this.blocks.length; index++) {
  17489. var block = this.blocks[index];
  17490. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17491. }
  17492. return;
  17493. }
  17494. if (allowDuplicate) {
  17495. selection.concat(this.entries);
  17496. }
  17497. else {
  17498. selection.concatWithNoDuplicate(this.entries);
  17499. }
  17500. }
  17501. };
  17502. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17503. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17504. if (this.blocks) {
  17505. for (var index = 0; index < this.blocks.length; index++) {
  17506. var block = this.blocks[index];
  17507. block.intersectsRay(ray, selection);
  17508. }
  17509. return;
  17510. }
  17511. selection.concatWithNoDuplicate(this.entries);
  17512. }
  17513. };
  17514. OctreeBlock.prototype.createInnerBlocks = function () {
  17515. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17516. };
  17517. return OctreeBlock;
  17518. })();
  17519. BABYLON.OctreeBlock = OctreeBlock;
  17520. })(BABYLON || (BABYLON = {}));
  17521. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17522. (function (BABYLON) {
  17523. var Bone = (function () {
  17524. function Bone(name, skeleton, parentBone, matrix) {
  17525. this.name = name;
  17526. this.children = new Array();
  17527. this.animations = new Array();
  17528. this._worldTransform = new BABYLON.Matrix();
  17529. this._absoluteTransform = new BABYLON.Matrix();
  17530. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17531. this._skeleton = skeleton;
  17532. this._matrix = matrix;
  17533. this._baseMatrix = matrix;
  17534. skeleton.bones.push(this);
  17535. if (parentBone) {
  17536. this._parent = parentBone;
  17537. parentBone.children.push(this);
  17538. }
  17539. else {
  17540. this._parent = null;
  17541. }
  17542. this._updateDifferenceMatrix();
  17543. }
  17544. // Members
  17545. Bone.prototype.getParent = function () {
  17546. return this._parent;
  17547. };
  17548. Bone.prototype.getLocalMatrix = function () {
  17549. return this._matrix;
  17550. };
  17551. Bone.prototype.getBaseMatrix = function () {
  17552. return this._baseMatrix;
  17553. };
  17554. Bone.prototype.getWorldMatrix = function () {
  17555. return this._worldTransform;
  17556. };
  17557. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17558. return this._invertedAbsoluteTransform;
  17559. };
  17560. Bone.prototype.getAbsoluteMatrix = function () {
  17561. var matrix = this._matrix.clone();
  17562. var parent = this._parent;
  17563. while (parent) {
  17564. matrix = matrix.multiply(parent.getLocalMatrix());
  17565. parent = parent.getParent();
  17566. }
  17567. return matrix;
  17568. };
  17569. // Methods
  17570. Bone.prototype.updateMatrix = function (matrix) {
  17571. this._matrix = matrix;
  17572. this._skeleton._markAsDirty();
  17573. this._updateDifferenceMatrix();
  17574. };
  17575. Bone.prototype._updateDifferenceMatrix = function () {
  17576. if (this._parent) {
  17577. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17578. }
  17579. else {
  17580. this._absoluteTransform.copyFrom(this._matrix);
  17581. }
  17582. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17583. for (var index = 0; index < this.children.length; index++) {
  17584. this.children[index]._updateDifferenceMatrix();
  17585. }
  17586. };
  17587. Bone.prototype.markAsDirty = function () {
  17588. this._skeleton._markAsDirty();
  17589. };
  17590. return Bone;
  17591. })();
  17592. BABYLON.Bone = Bone;
  17593. })(BABYLON || (BABYLON = {}));
  17594. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17595. (function (BABYLON) {
  17596. var Skeleton = (function () {
  17597. function Skeleton(name, id, scene) {
  17598. this.name = name;
  17599. this.id = id;
  17600. this.bones = new Array();
  17601. this._isDirty = true;
  17602. this._identity = BABYLON.Matrix.Identity();
  17603. this.bones = [];
  17604. this._scene = scene;
  17605. scene.skeletons.push(this);
  17606. this.prepare();
  17607. //make sure it will recalculate the matrix next time prepare is called.
  17608. this._isDirty = true;
  17609. }
  17610. // Members
  17611. Skeleton.prototype.getTransformMatrices = function () {
  17612. return this._transformMatrices;
  17613. };
  17614. // Methods
  17615. Skeleton.prototype._markAsDirty = function () {
  17616. this._isDirty = true;
  17617. };
  17618. Skeleton.prototype.prepare = function () {
  17619. if (!this._isDirty) {
  17620. return;
  17621. }
  17622. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17623. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17624. }
  17625. for (var index = 0; index < this.bones.length; index++) {
  17626. var bone = this.bones[index];
  17627. var parentBone = bone.getParent();
  17628. if (parentBone) {
  17629. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17630. }
  17631. else {
  17632. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17633. }
  17634. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17635. }
  17636. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17637. this._isDirty = false;
  17638. this._scene._activeBones += this.bones.length;
  17639. };
  17640. Skeleton.prototype.getAnimatables = function () {
  17641. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17642. this._animatables = [];
  17643. for (var index = 0; index < this.bones.length; index++) {
  17644. this._animatables.push(this.bones[index]);
  17645. }
  17646. }
  17647. return this._animatables;
  17648. };
  17649. Skeleton.prototype.clone = function (name, id) {
  17650. var result = new Skeleton(name, id || name, this._scene);
  17651. for (var index = 0; index < this.bones.length; index++) {
  17652. var source = this.bones[index];
  17653. var parentBone = null;
  17654. if (source.getParent()) {
  17655. var parentIndex = this.bones.indexOf(source.getParent());
  17656. parentBone = result.bones[parentIndex];
  17657. }
  17658. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17659. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17660. }
  17661. return result;
  17662. };
  17663. return Skeleton;
  17664. })();
  17665. BABYLON.Skeleton = Skeleton;
  17666. })(BABYLON || (BABYLON = {}));
  17667. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17668. (function (BABYLON) {
  17669. var PostProcess = (function () {
  17670. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17672. this.name = name;
  17673. this.width = -1;
  17674. this.height = -1;
  17675. this._reusable = false;
  17676. this._textures = new BABYLON.SmartArray(2);
  17677. this._currentRenderTextureInd = 0;
  17678. if (camera != null) {
  17679. this._camera = camera;
  17680. this._scene = camera.getScene();
  17681. camera.attachPostProcess(this);
  17682. this._engine = this._scene.getEngine();
  17683. }
  17684. else {
  17685. this._engine = engine;
  17686. }
  17687. this._renderRatio = ratio;
  17688. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17689. this._reusable = reusable || false;
  17690. samplers = samplers || [];
  17691. samplers.push("textureSampler");
  17692. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17693. }
  17694. PostProcess.prototype.isReusable = function () {
  17695. return this._reusable;
  17696. };
  17697. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17698. camera = camera || this._camera;
  17699. var scene = camera.getScene();
  17700. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17701. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17702. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17703. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17704. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17705. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17706. if (this._textures.length > 0) {
  17707. for (var i = 0; i < this._textures.length; i++) {
  17708. this._engine._releaseTexture(this._textures.data[i]);
  17709. }
  17710. this._textures.reset();
  17711. }
  17712. this.width = desiredWidth;
  17713. this.height = desiredHeight;
  17714. 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 }));
  17715. if (this._reusable) {
  17716. 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 }));
  17717. }
  17718. if (this.onSizeChanged) {
  17719. this.onSizeChanged();
  17720. }
  17721. }
  17722. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17723. if (this.onActivate) {
  17724. this.onActivate(camera);
  17725. }
  17726. // Clear
  17727. if (this.clearColor) {
  17728. this._engine.clear(this.clearColor, true, true);
  17729. }
  17730. else {
  17731. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17732. }
  17733. if (this._reusable) {
  17734. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17735. }
  17736. };
  17737. PostProcess.prototype.apply = function () {
  17738. // Check
  17739. if (!this._effect.isReady())
  17740. return null;
  17741. // States
  17742. this._engine.enableEffect(this._effect);
  17743. this._engine.setState(false);
  17744. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17745. this._engine.setDepthBuffer(false);
  17746. this._engine.setDepthWrite(false);
  17747. // Texture
  17748. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17749. // Parameters
  17750. if (this.onApply) {
  17751. this.onApply(this._effect);
  17752. }
  17753. return this._effect;
  17754. };
  17755. PostProcess.prototype.dispose = function (camera) {
  17756. camera = camera || this._camera;
  17757. if (this._textures.length > 0) {
  17758. for (var i = 0; i < this._textures.length; i++) {
  17759. this._engine._releaseTexture(this._textures.data[i]);
  17760. }
  17761. this._textures.reset();
  17762. }
  17763. if (!camera) {
  17764. return;
  17765. }
  17766. camera.detachPostProcess(this);
  17767. var index = camera._postProcesses.indexOf(this);
  17768. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17769. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17770. }
  17771. };
  17772. return PostProcess;
  17773. })();
  17774. BABYLON.PostProcess = PostProcess;
  17775. })(BABYLON || (BABYLON = {}));
  17776. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17777. (function (BABYLON) {
  17778. var PostProcessManager = (function () {
  17779. function PostProcessManager(scene) {
  17780. this._vertexDeclaration = [2];
  17781. this._vertexStrideSize = 2 * 4;
  17782. this._scene = scene;
  17783. }
  17784. PostProcessManager.prototype._prepareBuffers = function () {
  17785. if (this._vertexBuffer) {
  17786. return;
  17787. }
  17788. // VBO
  17789. var vertices = [];
  17790. vertices.push(1, 1);
  17791. vertices.push(-1, 1);
  17792. vertices.push(-1, -1);
  17793. vertices.push(1, -1);
  17794. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  17795. // Indices
  17796. var indices = [];
  17797. indices.push(0);
  17798. indices.push(1);
  17799. indices.push(2);
  17800. indices.push(0);
  17801. indices.push(2);
  17802. indices.push(3);
  17803. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  17804. };
  17805. // Methods
  17806. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17807. var postProcesses = this._scene.activeCamera._postProcesses;
  17808. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17809. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17810. return false;
  17811. }
  17812. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17813. return true;
  17814. };
  17815. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17816. var engine = this._scene.getEngine();
  17817. for (var index = 0; index < postProcesses.length; index++) {
  17818. if (index < postProcesses.length - 1) {
  17819. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17820. }
  17821. else {
  17822. if (targetTexture) {
  17823. engine.bindFramebuffer(targetTexture);
  17824. }
  17825. else {
  17826. engine.restoreDefaultFramebuffer();
  17827. }
  17828. }
  17829. var pp = postProcesses[index];
  17830. var effect = pp.apply();
  17831. if (effect) {
  17832. if (pp.onBeforeRender) {
  17833. pp.onBeforeRender(effect);
  17834. }
  17835. // VBOs
  17836. this._prepareBuffers();
  17837. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17838. // Draw order
  17839. engine.draw(true, 0, 6);
  17840. }
  17841. }
  17842. // Restore depth buffer
  17843. engine.setDepthBuffer(true);
  17844. engine.setDepthWrite(true);
  17845. };
  17846. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17847. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17848. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17849. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17850. return;
  17851. }
  17852. var engine = this._scene.getEngine();
  17853. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17854. if (index < postProcessesTakenIndices.length - 1) {
  17855. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17856. }
  17857. else {
  17858. if (targetTexture) {
  17859. engine.bindFramebuffer(targetTexture);
  17860. }
  17861. else {
  17862. engine.restoreDefaultFramebuffer();
  17863. }
  17864. }
  17865. if (doNotPresent) {
  17866. break;
  17867. }
  17868. var pp = postProcesses[postProcessesTakenIndices[index]];
  17869. var effect = pp.apply();
  17870. if (effect) {
  17871. if (pp.onBeforeRender) {
  17872. pp.onBeforeRender(effect);
  17873. }
  17874. // VBOs
  17875. this._prepareBuffers();
  17876. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17877. // Draw order
  17878. engine.draw(true, 0, 6);
  17879. }
  17880. }
  17881. // Restore depth buffer
  17882. engine.setDepthBuffer(true);
  17883. engine.setDepthWrite(true);
  17884. };
  17885. PostProcessManager.prototype.dispose = function () {
  17886. if (this._vertexBuffer) {
  17887. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17888. this._vertexBuffer = null;
  17889. }
  17890. if (this._indexBuffer) {
  17891. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17892. this._indexBuffer = null;
  17893. }
  17894. };
  17895. return PostProcessManager;
  17896. })();
  17897. BABYLON.PostProcessManager = PostProcessManager;
  17898. })(BABYLON || (BABYLON = {}));
  17899. //# sourceMappingURL=babylon.postProcessManager.js.map
  17900. var BABYLON;
  17901. (function (BABYLON) {
  17902. var PassPostProcess = (function (_super) {
  17903. __extends(PassPostProcess, _super);
  17904. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17905. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17906. }
  17907. return PassPostProcess;
  17908. })(BABYLON.PostProcess);
  17909. BABYLON.PassPostProcess = PassPostProcess;
  17910. })(BABYLON || (BABYLON = {}));
  17911. //# sourceMappingURL=babylon.passPostProcess.js.map
  17912. var BABYLON;
  17913. (function (BABYLON) {
  17914. var BlurPostProcess = (function (_super) {
  17915. __extends(BlurPostProcess, _super);
  17916. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17917. var _this = this;
  17918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17919. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17920. this.direction = direction;
  17921. this.blurWidth = blurWidth;
  17922. this.onApply = function (effect) {
  17923. effect.setFloat2("screenSize", _this.width, _this.height);
  17924. effect.setVector2("direction", _this.direction);
  17925. effect.setFloat("blurWidth", _this.blurWidth);
  17926. };
  17927. }
  17928. return BlurPostProcess;
  17929. })(BABYLON.PostProcess);
  17930. BABYLON.BlurPostProcess = BlurPostProcess;
  17931. })(BABYLON || (BABYLON = {}));
  17932. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17933. var BABYLON;
  17934. (function (BABYLON) {
  17935. var FilterPostProcess = (function (_super) {
  17936. __extends(FilterPostProcess, _super);
  17937. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17938. var _this = this;
  17939. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17940. this.kernelMatrix = kernelMatrix;
  17941. this.onApply = function (effect) {
  17942. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17943. };
  17944. }
  17945. return FilterPostProcess;
  17946. })(BABYLON.PostProcess);
  17947. BABYLON.FilterPostProcess = FilterPostProcess;
  17948. })(BABYLON || (BABYLON = {}));
  17949. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17950. var BABYLON;
  17951. (function (BABYLON) {
  17952. var RefractionPostProcess = (function (_super) {
  17953. __extends(RefractionPostProcess, _super);
  17954. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17955. var _this = this;
  17956. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17957. this.color = color;
  17958. this.depth = depth;
  17959. this.colorLevel = colorLevel;
  17960. this.onActivate = function (cam) {
  17961. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17962. };
  17963. this.onApply = function (effect) {
  17964. effect.setColor3("baseColor", _this.color);
  17965. effect.setFloat("depth", _this.depth);
  17966. effect.setFloat("colorLevel", _this.colorLevel);
  17967. effect.setTexture("refractionSampler", _this._refRexture);
  17968. };
  17969. }
  17970. // Methods
  17971. RefractionPostProcess.prototype.dispose = function (camera) {
  17972. if (this._refRexture) {
  17973. this._refRexture.dispose();
  17974. }
  17975. _super.prototype.dispose.call(this, camera);
  17976. };
  17977. return RefractionPostProcess;
  17978. })(BABYLON.PostProcess);
  17979. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17980. })(BABYLON || (BABYLON = {}));
  17981. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17982. var BABYLON;
  17983. (function (BABYLON) {
  17984. var BlackAndWhitePostProcess = (function (_super) {
  17985. __extends(BlackAndWhitePostProcess, _super);
  17986. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17987. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17988. }
  17989. return BlackAndWhitePostProcess;
  17990. })(BABYLON.PostProcess);
  17991. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17992. })(BABYLON || (BABYLON = {}));
  17993. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17994. var BABYLON;
  17995. (function (BABYLON) {
  17996. var ConvolutionPostProcess = (function (_super) {
  17997. __extends(ConvolutionPostProcess, _super);
  17998. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17999. var _this = this;
  18000. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  18001. this.kernel = kernel;
  18002. this.onApply = function (effect) {
  18003. effect.setFloat2("screenSize", _this.width, _this.height);
  18004. effect.setArray("kernel", _this.kernel);
  18005. };
  18006. }
  18007. // Statics
  18008. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  18009. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  18010. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  18011. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  18012. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  18013. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  18014. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  18015. return ConvolutionPostProcess;
  18016. })(BABYLON.PostProcess);
  18017. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  18018. })(BABYLON || (BABYLON = {}));
  18019. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  18020. var BABYLON;
  18021. (function (BABYLON) {
  18022. var FxaaPostProcess = (function (_super) {
  18023. __extends(FxaaPostProcess, _super);
  18024. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18025. var _this = this;
  18026. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  18027. this.onSizeChanged = function () {
  18028. _this.texelWidth = 1.0 / _this.width;
  18029. _this.texelHeight = 1.0 / _this.height;
  18030. };
  18031. this.onApply = function (effect) {
  18032. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  18033. };
  18034. }
  18035. return FxaaPostProcess;
  18036. })(BABYLON.PostProcess);
  18037. BABYLON.FxaaPostProcess = FxaaPostProcess;
  18038. })(BABYLON || (BABYLON = {}));
  18039. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  18040. (function (BABYLON) {
  18041. var LensFlare = (function () {
  18042. function LensFlare(size, position, color, imgUrl, system) {
  18043. this.size = size;
  18044. this.position = position;
  18045. this.dispose = function () {
  18046. if (this.texture) {
  18047. this.texture.dispose();
  18048. }
  18049. // Remove from scene
  18050. var index = this._system.lensFlares.indexOf(this);
  18051. this._system.lensFlares.splice(index, 1);
  18052. };
  18053. this.color = color || new BABYLON.Color3(1, 1, 1);
  18054. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  18055. this._system = system;
  18056. system.lensFlares.push(this);
  18057. }
  18058. return LensFlare;
  18059. })();
  18060. BABYLON.LensFlare = LensFlare;
  18061. })(BABYLON || (BABYLON = {}));
  18062. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  18063. (function (BABYLON) {
  18064. var LensFlareSystem = (function () {
  18065. function LensFlareSystem(name, emitter, scene) {
  18066. this.name = name;
  18067. this.lensFlares = new Array();
  18068. this.borderLimit = 300;
  18069. this._vertexDeclaration = [2];
  18070. this._vertexStrideSize = 2 * 4;
  18071. this._isEnabled = true;
  18072. this._scene = scene;
  18073. this._emitter = emitter;
  18074. scene.lensFlareSystems.push(this);
  18075. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  18076. // VBO
  18077. var vertices = [];
  18078. vertices.push(1, 1);
  18079. vertices.push(-1, 1);
  18080. vertices.push(-1, -1);
  18081. vertices.push(1, -1);
  18082. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18083. // Indices
  18084. var indices = [];
  18085. indices.push(0);
  18086. indices.push(1);
  18087. indices.push(2);
  18088. indices.push(0);
  18089. indices.push(2);
  18090. indices.push(3);
  18091. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18092. // Effects
  18093. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  18094. }
  18095. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  18096. get: function () {
  18097. return this._isEnabled;
  18098. },
  18099. set: function (value) {
  18100. this._isEnabled = value;
  18101. },
  18102. enumerable: true,
  18103. configurable: true
  18104. });
  18105. LensFlareSystem.prototype.getScene = function () {
  18106. return this._scene;
  18107. };
  18108. LensFlareSystem.prototype.getEmitter = function () {
  18109. return this._emitter;
  18110. };
  18111. LensFlareSystem.prototype.getEmitterPosition = function () {
  18112. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  18113. };
  18114. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  18115. var position = this.getEmitterPosition();
  18116. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  18117. this._positionX = position.x;
  18118. this._positionY = position.y;
  18119. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  18120. if (position.z > 0) {
  18121. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  18122. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  18123. return true;
  18124. }
  18125. }
  18126. return false;
  18127. };
  18128. LensFlareSystem.prototype._isVisible = function () {
  18129. if (!this._isEnabled) {
  18130. return false;
  18131. }
  18132. var emitterPosition = this.getEmitterPosition();
  18133. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  18134. var distance = direction.length();
  18135. direction.normalize();
  18136. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  18137. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  18138. return !pickInfo.hit || pickInfo.distance > distance;
  18139. };
  18140. LensFlareSystem.prototype.render = function () {
  18141. if (!this._effect.isReady())
  18142. return false;
  18143. var engine = this._scene.getEngine();
  18144. var viewport = this._scene.activeCamera.viewport;
  18145. var globalViewport = viewport.toGlobal(engine);
  18146. // Position
  18147. if (!this.computeEffectivePosition(globalViewport)) {
  18148. return false;
  18149. }
  18150. // Visibility
  18151. if (!this._isVisible()) {
  18152. return false;
  18153. }
  18154. // Intensity
  18155. var awayX;
  18156. var awayY;
  18157. if (this._positionX < this.borderLimit + globalViewport.x) {
  18158. awayX = this.borderLimit + globalViewport.x - this._positionX;
  18159. }
  18160. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  18161. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  18162. }
  18163. else {
  18164. awayX = 0;
  18165. }
  18166. if (this._positionY < this.borderLimit + globalViewport.y) {
  18167. awayY = this.borderLimit + globalViewport.y - this._positionY;
  18168. }
  18169. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  18170. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  18171. }
  18172. else {
  18173. awayY = 0;
  18174. }
  18175. var away = (awayX > awayY) ? awayX : awayY;
  18176. if (away > this.borderLimit) {
  18177. away = this.borderLimit;
  18178. }
  18179. var intensity = 1.0 - (away / this.borderLimit);
  18180. if (intensity < 0) {
  18181. return false;
  18182. }
  18183. if (intensity > 1.0) {
  18184. intensity = 1.0;
  18185. }
  18186. // Position
  18187. var centerX = globalViewport.x + globalViewport.width / 2;
  18188. var centerY = globalViewport.y + globalViewport.height / 2;
  18189. var distX = centerX - this._positionX;
  18190. var distY = centerY - this._positionY;
  18191. // Effects
  18192. engine.enableEffect(this._effect);
  18193. engine.setState(false);
  18194. engine.setDepthBuffer(false);
  18195. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  18196. // VBOs
  18197. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18198. for (var index = 0; index < this.lensFlares.length; index++) {
  18199. var flare = this.lensFlares[index];
  18200. var x = centerX - (distX * flare.position);
  18201. var y = centerY - (distY * flare.position);
  18202. var cw = flare.size;
  18203. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  18204. var cx = 2 * (x / globalViewport.width) - 1.0;
  18205. var cy = 1.0 - 2 * (y / globalViewport.height);
  18206. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  18207. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  18208. // Texture
  18209. this._effect.setTexture("textureSampler", flare.texture);
  18210. // Color
  18211. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  18212. // Draw order
  18213. engine.draw(true, 0, 6);
  18214. }
  18215. engine.setDepthBuffer(true);
  18216. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18217. return true;
  18218. };
  18219. LensFlareSystem.prototype.dispose = function () {
  18220. if (this._vertexBuffer) {
  18221. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18222. this._vertexBuffer = null;
  18223. }
  18224. if (this._indexBuffer) {
  18225. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18226. this._indexBuffer = null;
  18227. }
  18228. while (this.lensFlares.length) {
  18229. this.lensFlares[0].dispose();
  18230. }
  18231. // Remove from scene
  18232. var index = this._scene.lensFlareSystems.indexOf(this);
  18233. this._scene.lensFlareSystems.splice(index, 1);
  18234. };
  18235. return LensFlareSystem;
  18236. })();
  18237. BABYLON.LensFlareSystem = LensFlareSystem;
  18238. })(BABYLON || (BABYLON = {}));
  18239. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  18240. (function (BABYLON) {
  18241. var IntersectionInfo = (function () {
  18242. function IntersectionInfo(bu, bv, distance) {
  18243. this.bu = bu;
  18244. this.bv = bv;
  18245. this.distance = distance;
  18246. this.faceId = 0;
  18247. this.subMeshId = 0;
  18248. }
  18249. return IntersectionInfo;
  18250. })();
  18251. BABYLON.IntersectionInfo = IntersectionInfo;
  18252. var PickingInfo = (function () {
  18253. function PickingInfo() {
  18254. this.hit = false;
  18255. this.distance = 0;
  18256. this.pickedPoint = null;
  18257. this.pickedMesh = null;
  18258. this.bu = 0;
  18259. this.bv = 0;
  18260. this.faceId = -1;
  18261. this.subMeshId = 0;
  18262. }
  18263. // Methods
  18264. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  18265. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  18266. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18267. return null;
  18268. }
  18269. var indices = this.pickedMesh.getIndices();
  18270. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18271. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  18272. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  18273. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  18274. normal0 = normal0.scale(this.bu);
  18275. normal1 = normal1.scale(this.bv);
  18276. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  18277. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  18278. if (useWorldCoordinates) {
  18279. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  18280. }
  18281. return result;
  18282. };
  18283. PickingInfo.prototype.getTextureCoordinates = function () {
  18284. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18285. return null;
  18286. }
  18287. var indices = this.pickedMesh.getIndices();
  18288. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18289. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  18290. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  18291. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  18292. uv0 = uv0.scale(this.bu);
  18293. uv1 = uv1.scale(this.bv);
  18294. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  18295. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  18296. };
  18297. return PickingInfo;
  18298. })();
  18299. BABYLON.PickingInfo = PickingInfo;
  18300. })(BABYLON || (BABYLON = {}));
  18301. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  18302. (function (BABYLON) {
  18303. var FilesInput = (function () {
  18304. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  18305. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  18306. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  18307. this._engine = p_engine;
  18308. this._canvas = p_canvas;
  18309. this._currentScene = p_scene;
  18310. this._sceneLoadedCallback = p_sceneLoadedCallback;
  18311. this._progressCallback = p_progressCallback;
  18312. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  18313. this._textureLoadingCallback = p_textureLoadingCallback;
  18314. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  18315. }
  18316. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  18317. var _this = this;
  18318. if (p_elementToMonitor) {
  18319. this._elementToMonitor = p_elementToMonitor;
  18320. this._elementToMonitor.addEventListener("dragenter", function (e) {
  18321. _this.drag(e);
  18322. }, false);
  18323. this._elementToMonitor.addEventListener("dragover", function (e) {
  18324. _this.drag(e);
  18325. }, false);
  18326. this._elementToMonitor.addEventListener("drop", function (e) {
  18327. _this.drop(e);
  18328. }, false);
  18329. }
  18330. };
  18331. FilesInput.prototype.renderFunction = function () {
  18332. if (this._additionnalRenderLoopLogicCallback) {
  18333. this._additionnalRenderLoopLogicCallback();
  18334. }
  18335. if (this._currentScene) {
  18336. if (this._textureLoadingCallback) {
  18337. var remaining = this._currentScene.getWaitingItemsCount();
  18338. if (remaining > 0) {
  18339. this._textureLoadingCallback(remaining);
  18340. }
  18341. }
  18342. this._currentScene.render();
  18343. }
  18344. };
  18345. FilesInput.prototype.drag = function (e) {
  18346. e.stopPropagation();
  18347. e.preventDefault();
  18348. };
  18349. FilesInput.prototype.drop = function (eventDrop) {
  18350. eventDrop.stopPropagation();
  18351. eventDrop.preventDefault();
  18352. this.loadFiles(eventDrop);
  18353. };
  18354. FilesInput.prototype.loadFiles = function (event) {
  18355. if (this._startingProcessingFilesCallback)
  18356. this._startingProcessingFilesCallback();
  18357. // Handling data transfer via drag'n'drop
  18358. if (event && event.dataTransfer && event.dataTransfer.files) {
  18359. this._filesToLoad = event.dataTransfer.files;
  18360. }
  18361. // Handling files from input files
  18362. if (event && event.target && event.target.files) {
  18363. this._filesToLoad = event.target.files;
  18364. }
  18365. if (this._filesToLoad && this._filesToLoad.length > 0) {
  18366. for (var i = 0; i < this._filesToLoad.length; i++) {
  18367. switch (this._filesToLoad[i].type) {
  18368. case "image/jpeg":
  18369. case "image/png":
  18370. case "image/bmp":
  18371. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  18372. break;
  18373. case "image/targa":
  18374. case "image/vnd.ms-dds":
  18375. case "audio/wav":
  18376. case "audio/x-wav":
  18377. case "audio/mp3":
  18378. case "audio/mpeg":
  18379. case "audio/mpeg3":
  18380. case "audio/x-mpeg-3":
  18381. case "audio/ogg":
  18382. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  18383. break;
  18384. default:
  18385. 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) {
  18386. this._sceneFileToLoad = this._filesToLoad[i];
  18387. }
  18388. break;
  18389. }
  18390. }
  18391. this.reload();
  18392. }
  18393. };
  18394. FilesInput.prototype.reload = function () {
  18395. var _this = this;
  18396. var that = this;
  18397. // If a ".babylon" file has been provided
  18398. if (this._sceneFileToLoad) {
  18399. if (this._currentScene) {
  18400. this._engine.stopRenderLoop();
  18401. this._currentScene.dispose();
  18402. }
  18403. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  18404. that._currentScene = newScene;
  18405. // Wait for textures and shaders to be ready
  18406. that._currentScene.executeWhenReady(function () {
  18407. // Attach camera to canvas inputs
  18408. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  18409. that._currentScene.createDefaultCameraOrLight();
  18410. }
  18411. that._currentScene.activeCamera.attachControl(that._canvas);
  18412. if (that._sceneLoadedCallback) {
  18413. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  18414. }
  18415. that._engine.runRenderLoop(function () {
  18416. that.renderFunction();
  18417. });
  18418. });
  18419. }, function (progress) {
  18420. if (_this._progressCallback) {
  18421. _this._progressCallback(progress);
  18422. }
  18423. });
  18424. }
  18425. else {
  18426. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  18427. }
  18428. };
  18429. FilesInput.FilesTextures = new Array();
  18430. FilesInput.FilesToLoad = new Array();
  18431. return FilesInput;
  18432. })();
  18433. BABYLON.FilesInput = FilesInput;
  18434. })(BABYLON || (BABYLON = {}));
  18435. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  18436. (function (BABYLON) {
  18437. var OimoJSPlugin = (function () {
  18438. function OimoJSPlugin() {
  18439. this._registeredMeshes = [];
  18440. /**
  18441. * Update the body position according to the mesh position
  18442. * @param mesh
  18443. */
  18444. this.updateBodyPosition = function (mesh) {
  18445. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18446. var registeredMesh = this._registeredMeshes[index];
  18447. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18448. var body = registeredMesh.body.body;
  18449. mesh.computeWorldMatrix(true);
  18450. var center = mesh.getBoundingInfo().boundingBox.center;
  18451. body.setPosition(center.x, center.y, center.z);
  18452. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  18453. return;
  18454. }
  18455. // Case where the parent has been updated
  18456. if (registeredMesh.mesh.parent === mesh) {
  18457. mesh.computeWorldMatrix(true);
  18458. registeredMesh.mesh.computeWorldMatrix(true);
  18459. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  18460. var absoluteRotation = mesh.rotation;
  18461. body = registeredMesh.body.body;
  18462. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  18463. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  18464. return;
  18465. }
  18466. }
  18467. };
  18468. }
  18469. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  18470. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18471. };
  18472. OimoJSPlugin.prototype.initialize = function (iterations) {
  18473. this._world = new OIMO.World();
  18474. this._world.clear();
  18475. };
  18476. OimoJSPlugin.prototype.setGravity = function (gravity) {
  18477. this._world.gravity = gravity;
  18478. };
  18479. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18480. var body = null;
  18481. this.unregisterMesh(mesh);
  18482. mesh.computeWorldMatrix(true);
  18483. var initialRotation = null;
  18484. if (mesh.rotationQuaternion) {
  18485. initialRotation = mesh.rotationQuaternion.clone();
  18486. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18487. mesh.computeWorldMatrix(true);
  18488. }
  18489. var bbox = mesh.getBoundingInfo().boundingBox;
  18490. // The delta between the mesh position and the mesh bounding box center
  18491. var deltaPosition = mesh.position.subtract(bbox.center);
  18492. // Transform delta position with the rotation
  18493. if (initialRotation) {
  18494. var m = new BABYLON.Matrix();
  18495. initialRotation.toRotationMatrix(m);
  18496. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18497. }
  18498. switch (impostor) {
  18499. case BABYLON.PhysicsEngine.SphereImpostor:
  18500. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18501. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18502. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18503. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18504. body = new OIMO.Body({
  18505. type: 'sphere',
  18506. size: [size],
  18507. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18508. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18509. move: options.mass != 0,
  18510. config: [options.mass, options.friction, options.restitution],
  18511. world: this._world
  18512. });
  18513. break;
  18514. case BABYLON.PhysicsEngine.PlaneImpostor:
  18515. case BABYLON.PhysicsEngine.CylinderImpostor:
  18516. case BABYLON.PhysicsEngine.BoxImpostor:
  18517. var min = bbox.minimumWorld;
  18518. var max = bbox.maximumWorld;
  18519. var box = max.subtract(min);
  18520. var sizeX = this._checkWithEpsilon(box.x);
  18521. var sizeY = this._checkWithEpsilon(box.y);
  18522. var sizeZ = this._checkWithEpsilon(box.z);
  18523. body = new OIMO.Body({
  18524. type: 'box',
  18525. size: [sizeX, sizeY, sizeZ],
  18526. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18527. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18528. move: options.mass != 0,
  18529. config: [options.mass, options.friction, options.restitution],
  18530. world: this._world
  18531. });
  18532. break;
  18533. }
  18534. //If quaternion was set as the rotation of the object
  18535. if (initialRotation) {
  18536. //We have to access the rigid body's properties to set the quaternion.
  18537. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18538. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18539. //update the internal rotation matrix
  18540. body.body.syncShapes();
  18541. }
  18542. this._registeredMeshes.push({
  18543. mesh: mesh,
  18544. body: body,
  18545. delta: deltaPosition
  18546. });
  18547. return body;
  18548. };
  18549. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18550. var types = [], sizes = [], positions = [], rotations = [];
  18551. var initialMesh = parts[0].mesh;
  18552. for (var index = 0; index < parts.length; index++) {
  18553. var part = parts[index];
  18554. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18555. types.push(bodyParameters.type);
  18556. sizes.push.apply(sizes, bodyParameters.size);
  18557. positions.push.apply(positions, bodyParameters.pos);
  18558. rotations.push.apply(rotations, bodyParameters.rot);
  18559. }
  18560. var body = new OIMO.Body({
  18561. type: types,
  18562. size: sizes,
  18563. pos: positions,
  18564. rot: rotations,
  18565. move: options.mass != 0,
  18566. config: [options.mass, options.friction, options.restitution],
  18567. world: this._world
  18568. });
  18569. this._registeredMeshes.push({
  18570. mesh: initialMesh,
  18571. body: body
  18572. });
  18573. return body;
  18574. };
  18575. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18576. var bodyParameters = null;
  18577. var mesh = part.mesh;
  18578. // We need the bounding box/sphere info to compute the physics body
  18579. mesh.computeWorldMatrix();
  18580. switch (part.impostor) {
  18581. case BABYLON.PhysicsEngine.SphereImpostor:
  18582. var bbox = mesh.getBoundingInfo().boundingBox;
  18583. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18584. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18585. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18586. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18587. bodyParameters = {
  18588. type: 'sphere',
  18589. /* bug with oimo : sphere needs 3 sizes in this case */
  18590. size: [size, -1, -1],
  18591. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18592. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18593. };
  18594. break;
  18595. case BABYLON.PhysicsEngine.PlaneImpostor:
  18596. case BABYLON.PhysicsEngine.BoxImpostor:
  18597. bbox = mesh.getBoundingInfo().boundingBox;
  18598. var min = bbox.minimumWorld;
  18599. var max = bbox.maximumWorld;
  18600. var box = max.subtract(min);
  18601. var sizeX = this._checkWithEpsilon(box.x);
  18602. var sizeY = this._checkWithEpsilon(box.y);
  18603. var sizeZ = this._checkWithEpsilon(box.z);
  18604. var relativePosition = mesh.position;
  18605. bodyParameters = {
  18606. type: 'box',
  18607. size: [sizeX, sizeY, sizeZ],
  18608. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18609. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18610. };
  18611. break;
  18612. }
  18613. return bodyParameters;
  18614. };
  18615. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18616. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18617. var registeredMesh = this._registeredMeshes[index];
  18618. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18619. if (registeredMesh.body) {
  18620. this._world.removeRigidBody(registeredMesh.body.body);
  18621. this._unbindBody(registeredMesh.body);
  18622. }
  18623. this._registeredMeshes.splice(index, 1);
  18624. return;
  18625. }
  18626. }
  18627. };
  18628. OimoJSPlugin.prototype._unbindBody = function (body) {
  18629. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18630. var registeredMesh = this._registeredMeshes[index];
  18631. if (registeredMesh.body === body) {
  18632. registeredMesh.body = null;
  18633. }
  18634. }
  18635. };
  18636. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18637. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18638. var registeredMesh = this._registeredMeshes[index];
  18639. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18640. // Get object mass to have a behaviour similar to cannon.js
  18641. var mass = registeredMesh.body.body.massInfo.mass;
  18642. // The force is scaled with the mass of object
  18643. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18644. return;
  18645. }
  18646. }
  18647. };
  18648. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18649. var body1 = null, body2 = null;
  18650. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18651. var registeredMesh = this._registeredMeshes[index];
  18652. if (registeredMesh.mesh === mesh1) {
  18653. body1 = registeredMesh.body.body;
  18654. }
  18655. else if (registeredMesh.mesh === mesh2) {
  18656. body2 = registeredMesh.body.body;
  18657. }
  18658. }
  18659. if (!body1 || !body2) {
  18660. return false;
  18661. }
  18662. if (!options) {
  18663. options = {};
  18664. }
  18665. new OIMO.Link({
  18666. type: options.type,
  18667. body1: body1,
  18668. body2: body2,
  18669. min: options.min,
  18670. max: options.max,
  18671. axe1: options.axe1,
  18672. axe2: options.axe2,
  18673. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18674. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18675. collision: options.collision,
  18676. spring: options.spring,
  18677. world: this._world
  18678. });
  18679. return true;
  18680. };
  18681. OimoJSPlugin.prototype.dispose = function () {
  18682. this._world.clear();
  18683. while (this._registeredMeshes.length) {
  18684. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18685. }
  18686. };
  18687. OimoJSPlugin.prototype.isSupported = function () {
  18688. return OIMO !== undefined;
  18689. };
  18690. OimoJSPlugin.prototype._getLastShape = function (body) {
  18691. var lastShape = body.shapes;
  18692. while (lastShape.next) {
  18693. lastShape = lastShape.next;
  18694. }
  18695. return lastShape;
  18696. };
  18697. OimoJSPlugin.prototype.runOneStep = function (time) {
  18698. this._world.step();
  18699. // Update the position of all registered meshes
  18700. var i = this._registeredMeshes.length;
  18701. var m;
  18702. while (i--) {
  18703. var body = this._registeredMeshes[i].body.body;
  18704. var mesh = this._registeredMeshes[i].mesh;
  18705. var delta = this._registeredMeshes[i].delta;
  18706. if (!body.sleeping) {
  18707. if (body.shapes.next) {
  18708. var parentShape = this._getLastShape(body);
  18709. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18710. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18711. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18712. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18713. if (!mesh.rotationQuaternion) {
  18714. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18715. }
  18716. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18717. mesh.computeWorldMatrix();
  18718. }
  18719. else {
  18720. m = body.getMatrix();
  18721. mtx = BABYLON.Matrix.FromArray(m);
  18722. // Body position
  18723. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18724. if (!delta) {
  18725. mesh.position.x = bodyX;
  18726. mesh.position.y = bodyY;
  18727. mesh.position.z = bodyZ;
  18728. }
  18729. else {
  18730. mesh.position.x = bodyX + delta.x;
  18731. mesh.position.y = bodyY + delta.y;
  18732. mesh.position.z = bodyZ + delta.z;
  18733. }
  18734. if (!mesh.rotationQuaternion) {
  18735. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18736. }
  18737. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18738. mesh.computeWorldMatrix();
  18739. }
  18740. }
  18741. }
  18742. };
  18743. return OimoJSPlugin;
  18744. })();
  18745. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18746. })(BABYLON || (BABYLON = {}));
  18747. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18748. (function (BABYLON) {
  18749. var PhysicsEngine = (function () {
  18750. function PhysicsEngine(plugin) {
  18751. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18752. }
  18753. PhysicsEngine.prototype._initialize = function (gravity) {
  18754. this._currentPlugin.initialize();
  18755. this._setGravity(gravity);
  18756. };
  18757. PhysicsEngine.prototype._runOneStep = function (delta) {
  18758. if (delta > 0.1) {
  18759. delta = 0.1;
  18760. }
  18761. else if (delta <= 0) {
  18762. delta = 1.0 / 60.0;
  18763. }
  18764. this._currentPlugin.runOneStep(delta);
  18765. };
  18766. PhysicsEngine.prototype._setGravity = function (gravity) {
  18767. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18768. this._currentPlugin.setGravity(this.gravity);
  18769. };
  18770. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18771. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18772. };
  18773. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18774. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18775. };
  18776. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18777. this._currentPlugin.unregisterMesh(mesh);
  18778. };
  18779. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18780. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18781. };
  18782. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18783. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18784. };
  18785. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18786. this._currentPlugin.updateBodyPosition(mesh);
  18787. };
  18788. PhysicsEngine.prototype.dispose = function () {
  18789. this._currentPlugin.dispose();
  18790. };
  18791. PhysicsEngine.prototype.isSupported = function () {
  18792. return this._currentPlugin.isSupported();
  18793. };
  18794. // Statics
  18795. PhysicsEngine.NoImpostor = 0;
  18796. PhysicsEngine.SphereImpostor = 1;
  18797. PhysicsEngine.BoxImpostor = 2;
  18798. PhysicsEngine.PlaneImpostor = 3;
  18799. PhysicsEngine.MeshImpostor = 4;
  18800. PhysicsEngine.CapsuleImpostor = 5;
  18801. PhysicsEngine.ConeImpostor = 6;
  18802. PhysicsEngine.CylinderImpostor = 7;
  18803. PhysicsEngine.ConvexHullImpostor = 8;
  18804. PhysicsEngine.Epsilon = 0.001;
  18805. return PhysicsEngine;
  18806. })();
  18807. BABYLON.PhysicsEngine = PhysicsEngine;
  18808. })(BABYLON || (BABYLON = {}));
  18809. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18810. (function (BABYLON) {
  18811. var serializeLight = function (light) {
  18812. var serializationObject = {};
  18813. serializationObject.name = light.name;
  18814. serializationObject.id = light.id;
  18815. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18816. if (light instanceof BABYLON.PointLight) {
  18817. serializationObject.type = 0;
  18818. serializationObject.position = light.position.asArray();
  18819. }
  18820. else if (light instanceof BABYLON.DirectionalLight) {
  18821. serializationObject.type = 1;
  18822. var directionalLight = light;
  18823. serializationObject.position = directionalLight.position.asArray();
  18824. serializationObject.direction = directionalLight.direction.asArray();
  18825. }
  18826. else if (light instanceof BABYLON.SpotLight) {
  18827. serializationObject.type = 2;
  18828. var spotLight = light;
  18829. serializationObject.position = spotLight.position.asArray();
  18830. serializationObject.direction = spotLight.position.asArray();
  18831. serializationObject.angle = spotLight.angle;
  18832. serializationObject.exponent = spotLight.exponent;
  18833. }
  18834. else if (light instanceof BABYLON.HemisphericLight) {
  18835. serializationObject.type = 3;
  18836. var hemisphericLight = light;
  18837. serializationObject.direction = hemisphericLight.direction.asArray();
  18838. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18839. }
  18840. if (light.intensity) {
  18841. serializationObject.intensity = light.intensity;
  18842. }
  18843. serializationObject.range = light.range;
  18844. serializationObject.diffuse = light.diffuse.asArray();
  18845. serializationObject.specular = light.specular.asArray();
  18846. return serializationObject;
  18847. };
  18848. var serializeFresnelParameter = function (fresnelParameter) {
  18849. var serializationObject = {};
  18850. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18851. serializationObject.leftColor = fresnelParameter.leftColor;
  18852. serializationObject.rightColor = fresnelParameter.rightColor;
  18853. serializationObject.bias = fresnelParameter.bias;
  18854. serializationObject.power = fresnelParameter.power;
  18855. return serializationObject;
  18856. };
  18857. var appendAnimations = function (source, destination) {
  18858. if (source.animations) {
  18859. destination.animations = [];
  18860. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18861. var animation = source.animations[animationIndex];
  18862. destination.animations.push(serializeAnimation(animation));
  18863. }
  18864. }
  18865. };
  18866. var serializeCamera = function (camera) {
  18867. var serializationObject = {};
  18868. serializationObject.name = camera.name;
  18869. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18870. serializationObject.id = camera.id;
  18871. serializationObject.position = camera.position.asArray();
  18872. // Parent
  18873. if (camera.parent) {
  18874. serializationObject.parentId = camera.parent.id;
  18875. }
  18876. serializationObject.fov = camera.fov;
  18877. serializationObject.minZ = camera.minZ;
  18878. serializationObject.maxZ = camera.maxZ;
  18879. serializationObject.inertia = camera.inertia;
  18880. //setting the type
  18881. if (camera instanceof BABYLON.FreeCamera) {
  18882. serializationObject.type = "FreeCamera";
  18883. }
  18884. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18885. serializationObject.type = "ArcRotateCamera";
  18886. }
  18887. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18888. serializationObject.type = "AnaglyphArcRotateCamera";
  18889. }
  18890. else if (camera instanceof BABYLON.GamepadCamera) {
  18891. serializationObject.type = "GamepadCamera";
  18892. }
  18893. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18894. serializationObject.type = "AnaglyphFreeCamera";
  18895. }
  18896. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18897. serializationObject.type = "DeviceOrientationCamera";
  18898. }
  18899. else if (camera instanceof BABYLON.FollowCamera) {
  18900. serializationObject.type = "FollowCamera";
  18901. }
  18902. else if (camera instanceof BABYLON.OculusCamera) {
  18903. serializationObject.type = "OculusCamera";
  18904. }
  18905. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18906. serializationObject.type = "OculusGamepadCamera";
  18907. }
  18908. else if (camera instanceof BABYLON.TouchCamera) {
  18909. serializationObject.type = "TouchCamera";
  18910. }
  18911. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18912. serializationObject.type = "VirtualJoysticksCamera";
  18913. }
  18914. else if (camera instanceof BABYLON.WebVRCamera) {
  18915. serializationObject.type = "WebVRCamera";
  18916. }
  18917. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18918. serializationObject.type = "VRDeviceOrientationCamera";
  18919. }
  18920. //special properties of specific cameras
  18921. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18922. var arcCamera = camera;
  18923. serializationObject.alpha = arcCamera.alpha;
  18924. serializationObject.beta = arcCamera.beta;
  18925. serializationObject.radius = arcCamera.radius;
  18926. if (arcCamera.target && arcCamera.target.id) {
  18927. serializationObject.lockedTargetId = arcCamera.target.id;
  18928. }
  18929. }
  18930. else if (camera instanceof BABYLON.FollowCamera) {
  18931. var followCam = camera;
  18932. serializationObject.radius = followCam.radius;
  18933. serializationObject.heightOffset = followCam.heightOffset;
  18934. serializationObject.rotationOffset = followCam.rotationOffset;
  18935. }
  18936. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18937. //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.
  18938. if (camera['_eyeSpace'] !== undefined) {
  18939. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18940. }
  18941. }
  18942. //general properties that not all cameras have. The [] is due to typescript's type safety
  18943. if (camera['speed'] !== undefined) {
  18944. serializationObject.speed = camera['speed'];
  18945. }
  18946. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18947. serializationObject.target = camera['target'].asArray();
  18948. }
  18949. // Target
  18950. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18951. serializationObject.rotation = camera['rotation'].asArray();
  18952. }
  18953. // Locked target
  18954. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18955. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18956. }
  18957. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18958. serializationObject.applyGravity = camera['applyGravity'] || false;
  18959. if (camera['ellipsoid']) {
  18960. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18961. }
  18962. // Animations
  18963. appendAnimations(camera, serializationObject);
  18964. // Layer mask
  18965. serializationObject.layerMask = camera.layerMask;
  18966. return serializationObject;
  18967. };
  18968. var serializeAnimation = function (animation) {
  18969. var serializationObject = {};
  18970. serializationObject.name = animation.name;
  18971. serializationObject.property = animation.targetProperty;
  18972. serializationObject.framePerSecond = animation.framePerSecond;
  18973. serializationObject.dataType = animation.dataType;
  18974. serializationObject.loopBehavior = animation.loopMode;
  18975. var dataType = animation.dataType;
  18976. serializationObject.keys = [];
  18977. var keys = animation.getKeys();
  18978. for (var index = 0; index < keys.length; index++) {
  18979. var animationKey = keys[index];
  18980. var key = {};
  18981. key.frame = animationKey.frame;
  18982. switch (dataType) {
  18983. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18984. key.values = [animationKey.value];
  18985. break;
  18986. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18987. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18988. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18989. key.values = animationKey.value.asArray();
  18990. break;
  18991. }
  18992. serializationObject.keys.push(key);
  18993. }
  18994. return serializationObject;
  18995. };
  18996. var serializeMultiMaterial = function (material) {
  18997. var serializationObject = {};
  18998. serializationObject.name = material.name;
  18999. serializationObject.id = material.id;
  19000. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19001. serializationObject.materials = [];
  19002. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  19003. var subMat = material.subMaterials[matIndex];
  19004. if (subMat) {
  19005. serializationObject.materials.push(subMat.id);
  19006. }
  19007. else {
  19008. serializationObject.materials.push(null);
  19009. }
  19010. }
  19011. return serializationObject;
  19012. };
  19013. var serializeMaterial = function (material) {
  19014. var serializationObject = {};
  19015. serializationObject.name = material.name;
  19016. serializationObject.ambient = material.ambientColor.asArray();
  19017. serializationObject.diffuse = material.diffuseColor.asArray();
  19018. serializationObject.specular = material.specularColor.asArray();
  19019. serializationObject.specularPower = material.specularPower;
  19020. serializationObject.emissive = material.emissiveColor.asArray();
  19021. serializationObject.alpha = material.alpha;
  19022. serializationObject.id = material.id;
  19023. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19024. serializationObject.backFaceCulling = material.backFaceCulling;
  19025. if (material.diffuseTexture) {
  19026. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  19027. }
  19028. if (material.diffuseFresnelParameters) {
  19029. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  19030. }
  19031. if (material.ambientTexture) {
  19032. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  19033. }
  19034. if (material.opacityTexture) {
  19035. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  19036. }
  19037. if (material.opacityFresnelParameters) {
  19038. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  19039. }
  19040. if (material.reflectionTexture) {
  19041. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  19042. }
  19043. if (material.reflectionFresnelParameters) {
  19044. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  19045. }
  19046. if (material.emissiveTexture) {
  19047. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  19048. }
  19049. if (material.emissiveFresnelParameters) {
  19050. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  19051. }
  19052. if (material.specularTexture) {
  19053. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  19054. }
  19055. if (material.bumpTexture) {
  19056. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  19057. }
  19058. return serializationObject;
  19059. };
  19060. var serializeTexture = function (texture) {
  19061. var serializationObject = {};
  19062. if (!texture.name) {
  19063. return null;
  19064. }
  19065. if (texture instanceof BABYLON.CubeTexture) {
  19066. serializationObject.name = texture.name;
  19067. serializationObject.hasAlpha = texture.hasAlpha;
  19068. serializationObject.level = texture.level;
  19069. serializationObject.coordinatesMode = texture.coordinatesMode;
  19070. return serializationObject;
  19071. }
  19072. if (texture instanceof BABYLON.MirrorTexture) {
  19073. var mirrorTexture = texture;
  19074. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  19075. serializationObject.renderList = [];
  19076. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  19077. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  19078. }
  19079. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  19080. }
  19081. else if (texture instanceof BABYLON.RenderTargetTexture) {
  19082. var renderTargetTexture = texture;
  19083. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  19084. serializationObject.renderList = [];
  19085. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  19086. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  19087. }
  19088. }
  19089. var regularTexture = texture;
  19090. serializationObject.name = texture.name;
  19091. serializationObject.hasAlpha = texture.hasAlpha;
  19092. serializationObject.level = texture.level;
  19093. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  19094. serializationObject.coordinatesMode = texture.coordinatesMode;
  19095. serializationObject.uOffset = regularTexture.uOffset;
  19096. serializationObject.vOffset = regularTexture.vOffset;
  19097. serializationObject.uScale = regularTexture.uScale;
  19098. serializationObject.vScale = regularTexture.vScale;
  19099. serializationObject.uAng = regularTexture.uAng;
  19100. serializationObject.vAng = regularTexture.vAng;
  19101. serializationObject.wAng = regularTexture.wAng;
  19102. serializationObject.wrapU = texture.wrapU;
  19103. serializationObject.wrapV = texture.wrapV;
  19104. // Animations
  19105. appendAnimations(texture, serializationObject);
  19106. return serializationObject;
  19107. };
  19108. var serializeSkeleton = function (skeleton) {
  19109. var serializationObject = {};
  19110. serializationObject.name = skeleton.name;
  19111. serializationObject.id = skeleton.id;
  19112. serializationObject.bones = [];
  19113. for (var index = 0; index < skeleton.bones.length; index++) {
  19114. var bone = skeleton.bones[index];
  19115. var serializedBone = {
  19116. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  19117. name: bone.name,
  19118. matrix: bone.getLocalMatrix().toArray()
  19119. };
  19120. serializationObject.bones.push(serializedBone);
  19121. if (bone.animations && bone.animations.length > 0) {
  19122. serializedBone.animation = serializeAnimation(bone.animations[0]);
  19123. }
  19124. }
  19125. return serializationObject;
  19126. };
  19127. var serializeParticleSystem = function (particleSystem) {
  19128. var serializationObject = {};
  19129. serializationObject.emitterId = particleSystem.emitter.id;
  19130. serializationObject.capacity = particleSystem.getCapacity();
  19131. if (particleSystem.particleTexture) {
  19132. serializationObject.textureName = particleSystem.particleTexture.name;
  19133. }
  19134. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  19135. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  19136. serializationObject.minSize = particleSystem.minSize;
  19137. serializationObject.maxSize = particleSystem.maxSize;
  19138. serializationObject.minLifeTime = particleSystem.minLifeTime;
  19139. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  19140. serializationObject.emitRate = particleSystem.emitRate;
  19141. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  19142. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  19143. serializationObject.gravity = particleSystem.gravity.asArray();
  19144. serializationObject.direction1 = particleSystem.direction1.asArray();
  19145. serializationObject.direction2 = particleSystem.direction2.asArray();
  19146. serializationObject.color1 = particleSystem.color1.asArray();
  19147. serializationObject.color2 = particleSystem.color2.asArray();
  19148. serializationObject.colorDead = particleSystem.colorDead.asArray();
  19149. serializationObject.updateSpeed = particleSystem.updateSpeed;
  19150. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  19151. serializationObject.textureMask = particleSystem.textureMask.asArray();
  19152. serializationObject.blendMode = particleSystem.blendMode;
  19153. return serializationObject;
  19154. };
  19155. var serializeLensFlareSystem = function (lensFlareSystem) {
  19156. var serializationObject = {};
  19157. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  19158. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  19159. serializationObject.flares = [];
  19160. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  19161. var flare = lensFlareSystem.lensFlares[index];
  19162. serializationObject.flares.push({
  19163. size: flare.size,
  19164. position: flare.position,
  19165. color: flare.color.asArray(),
  19166. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  19167. });
  19168. }
  19169. return serializationObject;
  19170. };
  19171. var serializeShadowGenerator = function (light) {
  19172. var serializationObject = {};
  19173. var shadowGenerator = light.getShadowGenerator();
  19174. serializationObject.lightId = light.id;
  19175. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  19176. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  19177. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  19178. serializationObject.renderList = [];
  19179. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  19180. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  19181. serializationObject.renderList.push(mesh.id);
  19182. }
  19183. return serializationObject;
  19184. };
  19185. var serializedGeometries = [];
  19186. var serializeGeometry = function (geometry, serializationGeometries) {
  19187. if (serializedGeometries[geometry.id]) {
  19188. return;
  19189. }
  19190. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  19191. serializationGeometries.boxes.push(serializeBox(geometry));
  19192. }
  19193. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  19194. serializationGeometries.spheres.push(serializeSphere(geometry));
  19195. }
  19196. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  19197. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  19198. }
  19199. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  19200. serializationGeometries.toruses.push(serializeTorus(geometry));
  19201. }
  19202. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  19203. serializationGeometries.grounds.push(serializeGround(geometry));
  19204. }
  19205. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  19206. serializationGeometries.planes.push(serializePlane(geometry));
  19207. }
  19208. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  19209. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  19210. }
  19211. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  19212. throw new Error("Unknow primitive type");
  19213. }
  19214. else {
  19215. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  19216. }
  19217. serializedGeometries[geometry.id] = true;
  19218. };
  19219. var serializeGeometryBase = function (geometry) {
  19220. var serializationObject = {};
  19221. serializationObject.id = geometry.id;
  19222. if (BABYLON.Tags.HasTags(geometry)) {
  19223. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  19224. }
  19225. return serializationObject;
  19226. };
  19227. var serializeVertexData = function (vertexData) {
  19228. var serializationObject = serializeGeometryBase(vertexData);
  19229. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19230. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19231. }
  19232. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19233. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19234. }
  19235. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19236. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19237. }
  19238. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19239. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19240. }
  19241. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19242. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19243. }
  19244. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19245. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19246. serializationObject.matricesIndices._isExpanded = true;
  19247. }
  19248. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19249. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19250. }
  19251. serializationObject.indices = vertexData.getIndices();
  19252. return serializationObject;
  19253. };
  19254. var serializePrimitive = function (primitive) {
  19255. var serializationObject = serializeGeometryBase(primitive);
  19256. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  19257. return serializationObject;
  19258. };
  19259. var serializeBox = function (box) {
  19260. var serializationObject = serializePrimitive(box);
  19261. serializationObject.size = box.size;
  19262. return serializationObject;
  19263. };
  19264. var serializeSphere = function (sphere) {
  19265. var serializationObject = serializePrimitive(sphere);
  19266. serializationObject.segments = sphere.segments;
  19267. serializationObject.diameter = sphere.diameter;
  19268. return serializationObject;
  19269. };
  19270. var serializeCylinder = function (cylinder) {
  19271. var serializationObject = serializePrimitive(cylinder);
  19272. serializationObject.height = cylinder.height;
  19273. serializationObject.diameterTop = cylinder.diameterTop;
  19274. serializationObject.diameterBottom = cylinder.diameterBottom;
  19275. serializationObject.tessellation = cylinder.tessellation;
  19276. return serializationObject;
  19277. };
  19278. var serializeTorus = function (torus) {
  19279. var serializationObject = serializePrimitive(torus);
  19280. serializationObject.diameter = torus.diameter;
  19281. serializationObject.thickness = torus.thickness;
  19282. serializationObject.tessellation = torus.tessellation;
  19283. return serializationObject;
  19284. };
  19285. var serializeGround = function (ground) {
  19286. var serializationObject = serializePrimitive(ground);
  19287. serializationObject.width = ground.width;
  19288. serializationObject.height = ground.height;
  19289. serializationObject.subdivisions = ground.subdivisions;
  19290. return serializationObject;
  19291. };
  19292. var serializePlane = function (plane) {
  19293. var serializationObject = serializePrimitive(plane);
  19294. serializationObject.size = plane.size;
  19295. return serializationObject;
  19296. };
  19297. var serializeTorusKnot = function (torusKnot) {
  19298. var serializationObject = serializePrimitive(torusKnot);
  19299. serializationObject.radius = torusKnot.radius;
  19300. serializationObject.tube = torusKnot.tube;
  19301. serializationObject.radialSegments = torusKnot.radialSegments;
  19302. serializationObject.tubularSegments = torusKnot.tubularSegments;
  19303. serializationObject.p = torusKnot.p;
  19304. serializationObject.q = torusKnot.q;
  19305. return serializationObject;
  19306. };
  19307. var serializeMesh = function (mesh, serializationScene) {
  19308. var serializationObject = {};
  19309. serializationObject.name = mesh.name;
  19310. serializationObject.id = mesh.id;
  19311. if (BABYLON.Tags.HasTags(mesh)) {
  19312. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  19313. }
  19314. serializationObject.position = mesh.position.asArray();
  19315. if (mesh.rotationQuaternion) {
  19316. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  19317. }
  19318. else if (mesh.rotation) {
  19319. serializationObject.rotation = mesh.rotation.asArray();
  19320. }
  19321. serializationObject.scaling = mesh.scaling.asArray();
  19322. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  19323. serializationObject.isEnabled = mesh.isEnabled();
  19324. serializationObject.isVisible = mesh.isVisible;
  19325. serializationObject.infiniteDistance = mesh.infiniteDistance;
  19326. serializationObject.pickable = mesh.isPickable;
  19327. serializationObject.receiveShadows = mesh.receiveShadows;
  19328. serializationObject.billboardMode = mesh.billboardMode;
  19329. serializationObject.visibility = mesh.visibility;
  19330. serializationObject.checkCollisions = mesh.checkCollisions;
  19331. // Parent
  19332. if (mesh.parent) {
  19333. serializationObject.parentId = mesh.parent.id;
  19334. }
  19335. // Geometry
  19336. var geometry = mesh._geometry;
  19337. if (geometry) {
  19338. var geometryId = geometry.id;
  19339. serializationObject.geometryId = geometryId;
  19340. if (!mesh.getScene().getGeometryByID(geometryId)) {
  19341. // 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
  19342. serializeGeometry(geometry, serializationScene.geometries);
  19343. }
  19344. // SubMeshes
  19345. serializationObject.subMeshes = [];
  19346. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19347. var subMesh = mesh.subMeshes[subIndex];
  19348. serializationObject.subMeshes.push({
  19349. materialIndex: subMesh.materialIndex,
  19350. verticesStart: subMesh.verticesStart,
  19351. verticesCount: subMesh.verticesCount,
  19352. indexStart: subMesh.indexStart,
  19353. indexCount: subMesh.indexCount
  19354. });
  19355. }
  19356. }
  19357. // Material
  19358. if (mesh.material) {
  19359. serializationObject.materialId = mesh.material.id;
  19360. }
  19361. else {
  19362. mesh.material = null;
  19363. }
  19364. // Skeleton
  19365. if (mesh.skeleton) {
  19366. serializationObject.skeletonId = mesh.skeleton.id;
  19367. }
  19368. // Physics
  19369. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  19370. serializationObject.physicsMass = mesh.getPhysicsMass();
  19371. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  19372. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  19373. switch (mesh.getPhysicsImpostor()) {
  19374. case BABYLON.PhysicsEngine.BoxImpostor:
  19375. serializationObject.physicsImpostor = 1;
  19376. break;
  19377. case BABYLON.PhysicsEngine.SphereImpostor:
  19378. serializationObject.physicsImpostor = 2;
  19379. break;
  19380. }
  19381. }
  19382. // Instances
  19383. serializationObject.instances = [];
  19384. for (var index = 0; index < mesh.instances.length; index++) {
  19385. var instance = mesh.instances[index];
  19386. var serializationInstance = {
  19387. name: instance.name,
  19388. position: instance.position,
  19389. rotation: instance.rotation,
  19390. rotationQuaternion: instance.rotationQuaternion,
  19391. scaling: instance.scaling
  19392. };
  19393. serializationObject.instances.push(serializationInstance);
  19394. // Animations
  19395. appendAnimations(instance, serializationInstance);
  19396. }
  19397. // Animations
  19398. appendAnimations(mesh, serializationObject);
  19399. // Layer mask
  19400. serializationObject.layerMask = mesh.layerMask;
  19401. return serializationObject;
  19402. };
  19403. var SceneSerializer = (function () {
  19404. function SceneSerializer() {
  19405. }
  19406. SceneSerializer.Serialize = function (scene) {
  19407. var serializationObject = {};
  19408. // Scene
  19409. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  19410. serializationObject.autoClear = scene.autoClear;
  19411. serializationObject.clearColor = scene.clearColor.asArray();
  19412. serializationObject.ambientColor = scene.ambientColor.asArray();
  19413. serializationObject.gravity = scene.gravity.asArray();
  19414. // Fog
  19415. if (scene.fogMode && scene.fogMode !== 0) {
  19416. serializationObject.fogMode = scene.fogMode;
  19417. serializationObject.fogColor = scene.fogColor.asArray();
  19418. serializationObject.fogStart = scene.fogStart;
  19419. serializationObject.fogEnd = scene.fogEnd;
  19420. serializationObject.fogDensity = scene.fogDensity;
  19421. }
  19422. // Lights
  19423. serializationObject.lights = [];
  19424. for (var index = 0; index < scene.lights.length; index++) {
  19425. var light = scene.lights[index];
  19426. serializationObject.lights.push(serializeLight(light));
  19427. }
  19428. // Cameras
  19429. serializationObject.cameras = [];
  19430. for (index = 0; index < scene.cameras.length; index++) {
  19431. var camera = scene.cameras[index];
  19432. serializationObject.cameras.push(serializeCamera(camera));
  19433. }
  19434. if (scene.activeCamera) {
  19435. serializationObject.activeCameraID = scene.activeCamera.id;
  19436. }
  19437. // Materials
  19438. serializationObject.materials = [];
  19439. serializationObject.multiMaterials = [];
  19440. for (index = 0; index < scene.materials.length; index++) {
  19441. var material = scene.materials[index];
  19442. if (material instanceof BABYLON.StandardMaterial) {
  19443. serializationObject.materials.push(serializeMaterial(material));
  19444. }
  19445. else if (material instanceof BABYLON.MultiMaterial) {
  19446. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  19447. }
  19448. }
  19449. // Skeletons
  19450. serializationObject.skeletons = [];
  19451. for (index = 0; index < scene.skeletons.length; index++) {
  19452. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  19453. }
  19454. // Geometries
  19455. serializationObject.geometries = {};
  19456. serializationObject.geometries.boxes = [];
  19457. serializationObject.geometries.spheres = [];
  19458. serializationObject.geometries.cylinders = [];
  19459. serializationObject.geometries.toruses = [];
  19460. serializationObject.geometries.grounds = [];
  19461. serializationObject.geometries.planes = [];
  19462. serializationObject.geometries.torusKnots = [];
  19463. serializationObject.geometries.vertexData = [];
  19464. serializedGeometries = [];
  19465. var geometries = scene.getGeometries();
  19466. for (index = 0; index < geometries.length; index++) {
  19467. var geometry = geometries[index];
  19468. if (geometry.isReady()) {
  19469. serializeGeometry(geometry, serializationObject.geometries);
  19470. }
  19471. }
  19472. // Meshes
  19473. serializationObject.meshes = [];
  19474. for (index = 0; index < scene.meshes.length; index++) {
  19475. var abstractMesh = scene.meshes[index];
  19476. if (abstractMesh instanceof BABYLON.Mesh) {
  19477. var mesh = abstractMesh;
  19478. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  19479. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  19480. }
  19481. }
  19482. }
  19483. // Particles Systems
  19484. serializationObject.particleSystems = [];
  19485. for (index = 0; index < scene.particleSystems.length; index++) {
  19486. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19487. }
  19488. // Lens flares
  19489. serializationObject.lensFlareSystems = [];
  19490. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19491. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19492. }
  19493. // Shadows
  19494. serializationObject.shadowGenerators = [];
  19495. for (index = 0; index < scene.lights.length; index++) {
  19496. light = scene.lights[index];
  19497. if (light.getShadowGenerator()) {
  19498. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19499. }
  19500. }
  19501. return serializationObject;
  19502. };
  19503. return SceneSerializer;
  19504. })();
  19505. BABYLON.SceneSerializer = SceneSerializer;
  19506. })(BABYLON || (BABYLON = {}));
  19507. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19508. (function (BABYLON) {
  19509. var SceneLoader = (function () {
  19510. function SceneLoader() {
  19511. }
  19512. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19513. get: function () {
  19514. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19515. },
  19516. set: function (value) {
  19517. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19518. },
  19519. enumerable: true,
  19520. configurable: true
  19521. });
  19522. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19523. get: function () {
  19524. return SceneLoader._ShowLoadingScreen;
  19525. },
  19526. set: function (value) {
  19527. SceneLoader._ShowLoadingScreen = value;
  19528. },
  19529. enumerable: true,
  19530. configurable: true
  19531. });
  19532. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19533. var dotPosition = sceneFilename.lastIndexOf(".");
  19534. var queryStringPosition = sceneFilename.indexOf("?");
  19535. if (queryStringPosition === -1) {
  19536. queryStringPosition = sceneFilename.length;
  19537. }
  19538. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19539. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19540. var plugin = this._registeredPlugins[index];
  19541. if (plugin.extensions.indexOf(extension) !== -1) {
  19542. return plugin;
  19543. }
  19544. }
  19545. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19546. };
  19547. // Public functions
  19548. SceneLoader.RegisterPlugin = function (plugin) {
  19549. plugin.extensions = plugin.extensions.toLowerCase();
  19550. SceneLoader._registeredPlugins.push(plugin);
  19551. };
  19552. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19553. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19554. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19555. return;
  19556. }
  19557. var manifestChecked = function (success) {
  19558. scene.database = database;
  19559. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19560. var importMeshFromData = function (data) {
  19561. var meshes = [];
  19562. var particleSystems = [];
  19563. var skeletons = [];
  19564. try {
  19565. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19566. if (onerror) {
  19567. onerror(scene, 'unable to load the scene');
  19568. }
  19569. return;
  19570. }
  19571. }
  19572. catch (e) {
  19573. if (onerror) {
  19574. onerror(scene, e);
  19575. }
  19576. return;
  19577. }
  19578. if (onsuccess) {
  19579. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19580. onsuccess(meshes, particleSystems, skeletons);
  19581. }
  19582. };
  19583. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19584. // Direct load
  19585. importMeshFromData(sceneFilename.substr(5));
  19586. return;
  19587. }
  19588. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19589. importMeshFromData(data);
  19590. }, progressCallBack, database);
  19591. };
  19592. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19593. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19594. };
  19595. /**
  19596. * Load a scene
  19597. * @param rootUrl a string that defines the root url for scene and resources
  19598. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19599. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19600. */
  19601. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19602. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19603. };
  19604. /**
  19605. * Append a scene
  19606. * @param rootUrl a string that defines the root url for scene and resources
  19607. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19608. * @param scene is the instance of BABYLON.Scene to append to
  19609. */
  19610. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19611. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19612. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19613. return;
  19614. }
  19615. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19616. var database;
  19617. if (SceneLoader.ShowLoadingScreen) {
  19618. scene.getEngine().displayLoadingUI();
  19619. }
  19620. var loadSceneFromData = function (data) {
  19621. scene.database = database;
  19622. if (!plugin.load(scene, data, rootUrl)) {
  19623. if (onerror) {
  19624. onerror(scene);
  19625. }
  19626. scene.getEngine().hideLoadingUI();
  19627. return;
  19628. }
  19629. if (onsuccess) {
  19630. onsuccess(scene);
  19631. }
  19632. if (SceneLoader.ShowLoadingScreen) {
  19633. scene.executeWhenReady(function () {
  19634. scene.getEngine().hideLoadingUI();
  19635. });
  19636. }
  19637. };
  19638. var manifestChecked = function (success) {
  19639. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19640. };
  19641. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19642. // Direct load
  19643. loadSceneFromData(sceneFilename.substr(5));
  19644. return;
  19645. }
  19646. if (rootUrl.indexOf("file:") === -1) {
  19647. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19648. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19649. }
  19650. else {
  19651. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19652. }
  19653. };
  19654. // Flags
  19655. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19656. SceneLoader._ShowLoadingScreen = true;
  19657. // Members
  19658. SceneLoader._registeredPlugins = new Array();
  19659. return SceneLoader;
  19660. })();
  19661. BABYLON.SceneLoader = SceneLoader;
  19662. ;
  19663. })(BABYLON || (BABYLON = {}));
  19664. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19665. (function (BABYLON) {
  19666. var Internals;
  19667. (function (Internals) {
  19668. var checkColors4 = function (colors, count) {
  19669. // Check if color3 was used
  19670. if (colors.length === count * 3) {
  19671. var colors4 = [];
  19672. for (var index = 0; index < colors.length; index += 3) {
  19673. var newIndex = (index / 3) * 4;
  19674. colors4[newIndex] = colors[index];
  19675. colors4[newIndex + 1] = colors[index + 1];
  19676. colors4[newIndex + 2] = colors[index + 2];
  19677. colors4[newIndex + 3] = 1.0;
  19678. }
  19679. return colors4;
  19680. }
  19681. return colors;
  19682. };
  19683. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19684. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19685. texture.name = parsedTexture.name;
  19686. texture.hasAlpha = parsedTexture.hasAlpha;
  19687. texture.level = parsedTexture.level;
  19688. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19689. return texture;
  19690. };
  19691. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19692. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19693. return null;
  19694. }
  19695. if (parsedTexture.isCube) {
  19696. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19697. }
  19698. var texture;
  19699. if (parsedTexture.mirrorPlane) {
  19700. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19701. texture._waitingRenderList = parsedTexture.renderList;
  19702. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19703. }
  19704. else if (parsedTexture.isRenderTarget) {
  19705. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19706. texture._waitingRenderList = parsedTexture.renderList;
  19707. }
  19708. else {
  19709. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19710. }
  19711. texture.name = parsedTexture.name;
  19712. texture.hasAlpha = parsedTexture.hasAlpha;
  19713. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19714. texture.level = parsedTexture.level;
  19715. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19716. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19717. texture.uOffset = parsedTexture.uOffset;
  19718. texture.vOffset = parsedTexture.vOffset;
  19719. texture.uScale = parsedTexture.uScale;
  19720. texture.vScale = parsedTexture.vScale;
  19721. texture.uAng = parsedTexture.uAng;
  19722. texture.vAng = parsedTexture.vAng;
  19723. texture.wAng = parsedTexture.wAng;
  19724. texture.wrapU = parsedTexture.wrapU;
  19725. texture.wrapV = parsedTexture.wrapV;
  19726. // Animations
  19727. if (parsedTexture.animations) {
  19728. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19729. var parsedAnimation = parsedTexture.animations[animationIndex];
  19730. texture.animations.push(parseAnimation(parsedAnimation));
  19731. }
  19732. }
  19733. return texture;
  19734. };
  19735. var parseSkeleton = function (parsedSkeleton, scene) {
  19736. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19737. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19738. var parsedBone = parsedSkeleton.bones[index];
  19739. var parentBone = null;
  19740. if (parsedBone.parentBoneIndex > -1) {
  19741. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19742. }
  19743. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19744. if (parsedBone.animation) {
  19745. bone.animations.push(parseAnimation(parsedBone.animation));
  19746. }
  19747. }
  19748. return skeleton;
  19749. };
  19750. var parseFresnelParameters = function (parsedFresnelParameters) {
  19751. var fresnelParameters = new BABYLON.FresnelParameters();
  19752. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19753. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19754. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19755. fresnelParameters.bias = parsedFresnelParameters.bias;
  19756. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19757. return fresnelParameters;
  19758. };
  19759. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19760. var material;
  19761. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19762. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19763. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19764. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19765. material.specularPower = parsedMaterial.specularPower;
  19766. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19767. material.alpha = parsedMaterial.alpha;
  19768. material.id = parsedMaterial.id;
  19769. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19770. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19771. material.wireframe = parsedMaterial.wireframe;
  19772. if (parsedMaterial.diffuseTexture) {
  19773. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19774. }
  19775. if (parsedMaterial.diffuseFresnelParameters) {
  19776. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19777. }
  19778. if (parsedMaterial.ambientTexture) {
  19779. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19780. }
  19781. if (parsedMaterial.opacityTexture) {
  19782. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19783. }
  19784. if (parsedMaterial.opacityFresnelParameters) {
  19785. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19786. }
  19787. if (parsedMaterial.reflectionTexture) {
  19788. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19789. }
  19790. if (parsedMaterial.reflectionFresnelParameters) {
  19791. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19792. }
  19793. if (parsedMaterial.emissiveTexture) {
  19794. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19795. }
  19796. if (parsedMaterial.emissiveFresnelParameters) {
  19797. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19798. }
  19799. if (parsedMaterial.specularTexture) {
  19800. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19801. }
  19802. if (parsedMaterial.bumpTexture) {
  19803. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19804. }
  19805. return material;
  19806. };
  19807. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19808. for (var index = 0; index < parsedData.materials.length; index++) {
  19809. var parsedMaterial = parsedData.materials[index];
  19810. if (parsedMaterial.id === id) {
  19811. return parseMaterial(parsedMaterial, scene, rootUrl);
  19812. }
  19813. }
  19814. return null;
  19815. };
  19816. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19817. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19818. multiMaterial.id = parsedMultiMaterial.id;
  19819. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19820. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19821. var subMatId = parsedMultiMaterial.materials[matIndex];
  19822. if (subMatId) {
  19823. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19824. }
  19825. else {
  19826. multiMaterial.subMaterials.push(null);
  19827. }
  19828. }
  19829. return multiMaterial;
  19830. };
  19831. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19832. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19833. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19834. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19835. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19836. var parsedFlare = parsedLensFlareSystem.flares[index];
  19837. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19838. }
  19839. return lensFlareSystem;
  19840. };
  19841. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19842. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19843. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19844. if (parsedParticleSystem.textureName) {
  19845. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19846. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19847. }
  19848. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19849. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19850. particleSystem.minSize = parsedParticleSystem.minSize;
  19851. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19852. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19853. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19854. particleSystem.emitter = emitter;
  19855. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19856. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19857. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19858. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19859. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19860. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19861. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19862. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19863. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19864. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19865. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19866. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19867. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19868. particleSystem.start();
  19869. return particleSystem;
  19870. };
  19871. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19872. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19873. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19874. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19875. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19876. shadowGenerator.getShadowMap().renderList.push(mesh);
  19877. }
  19878. if (parsedShadowGenerator.usePoissonSampling) {
  19879. shadowGenerator.usePoissonSampling = true;
  19880. }
  19881. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19882. shadowGenerator.useVarianceShadowMap = true;
  19883. }
  19884. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19885. shadowGenerator.useBlurVarianceShadowMap = true;
  19886. if (parsedShadowGenerator.blurScale) {
  19887. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19888. }
  19889. if (parsedShadowGenerator.blurBoxOffset) {
  19890. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19891. }
  19892. }
  19893. if (parsedShadowGenerator.bias !== undefined) {
  19894. shadowGenerator.bias = parsedShadowGenerator.bias;
  19895. }
  19896. return shadowGenerator;
  19897. };
  19898. var parseAnimation = function (parsedAnimation) {
  19899. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19900. var dataType = parsedAnimation.dataType;
  19901. var keys = [];
  19902. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19903. var key = parsedAnimation.keys[index];
  19904. var data;
  19905. switch (dataType) {
  19906. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19907. data = key.values[0];
  19908. break;
  19909. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19910. data = BABYLON.Quaternion.FromArray(key.values);
  19911. break;
  19912. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19913. data = BABYLON.Matrix.FromArray(key.values);
  19914. break;
  19915. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19916. default:
  19917. data = BABYLON.Vector3.FromArray(key.values);
  19918. break;
  19919. }
  19920. keys.push({
  19921. frame: key.frame,
  19922. value: data
  19923. });
  19924. }
  19925. animation.setKeys(keys);
  19926. return animation;
  19927. };
  19928. var parseLight = function (parsedLight, scene) {
  19929. var light;
  19930. switch (parsedLight.type) {
  19931. case 0:
  19932. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19933. break;
  19934. case 1:
  19935. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19936. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19937. break;
  19938. case 2:
  19939. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19940. break;
  19941. case 3:
  19942. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19943. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19944. break;
  19945. }
  19946. light.id = parsedLight.id;
  19947. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19948. if (parsedLight.intensity !== undefined) {
  19949. light.intensity = parsedLight.intensity;
  19950. }
  19951. if (parsedLight.range) {
  19952. light.range = parsedLight.range;
  19953. }
  19954. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19955. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19956. if (parsedLight.excludedMeshesIds) {
  19957. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19958. }
  19959. // Parent
  19960. if (parsedLight.parentId) {
  19961. light._waitingParentId = parsedLight.parentId;
  19962. }
  19963. if (parsedLight.includedOnlyMeshesIds) {
  19964. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19965. }
  19966. // Animations
  19967. if (parsedLight.animations) {
  19968. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19969. var parsedAnimation = parsedLight.animations[animationIndex];
  19970. light.animations.push(parseAnimation(parsedAnimation));
  19971. }
  19972. }
  19973. if (parsedLight.autoAnimate) {
  19974. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19975. }
  19976. };
  19977. var parseCamera = function (parsedCamera, scene) {
  19978. var camera;
  19979. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19980. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19981. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19982. var alpha = parsedCamera.alpha;
  19983. var beta = parsedCamera.beta;
  19984. var radius = parsedCamera.radius;
  19985. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19986. var eye_space = parsedCamera.eye_space;
  19987. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19988. }
  19989. else {
  19990. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19991. }
  19992. }
  19993. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19994. eye_space = parsedCamera.eye_space;
  19995. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19996. }
  19997. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19998. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19999. }
  20000. else if (parsedCamera.type === "FollowCamera") {
  20001. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  20002. camera.heightOffset = parsedCamera.heightOffset;
  20003. camera.radius = parsedCamera.radius;
  20004. camera.rotationOffset = parsedCamera.rotationOffset;
  20005. if (lockedTargetMesh)
  20006. camera.target = lockedTargetMesh;
  20007. }
  20008. else if (parsedCamera.type === "GamepadCamera") {
  20009. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  20010. }
  20011. else if (parsedCamera.type === "OculusCamera") {
  20012. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  20013. }
  20014. else if (parsedCamera.type === "OculusGamepadCamera") {
  20015. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  20016. }
  20017. else if (parsedCamera.type === "TouchCamera") {
  20018. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  20019. }
  20020. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  20021. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  20022. }
  20023. else if (parsedCamera.type === "WebVRCamera") {
  20024. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  20025. }
  20026. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  20027. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  20028. }
  20029. else {
  20030. // Free Camera is the default value
  20031. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20032. }
  20033. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20034. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20035. camera.lockedTarget = lockedTargetMesh;
  20036. }
  20037. camera.id = parsedCamera.id;
  20038. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20039. // Parent
  20040. if (parsedCamera.parentId) {
  20041. camera._waitingParentId = parsedCamera.parentId;
  20042. }
  20043. // Target
  20044. if (parsedCamera.target) {
  20045. if (camera.setTarget) {
  20046. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20047. }
  20048. else {
  20049. //For ArcRotate
  20050. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20051. }
  20052. }
  20053. else {
  20054. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20055. }
  20056. camera.fov = parsedCamera.fov;
  20057. camera.minZ = parsedCamera.minZ;
  20058. camera.maxZ = parsedCamera.maxZ;
  20059. camera.speed = parsedCamera.speed;
  20060. camera.inertia = parsedCamera.inertia;
  20061. camera.checkCollisions = parsedCamera.checkCollisions;
  20062. camera.applyGravity = parsedCamera.applyGravity;
  20063. if (parsedCamera.ellipsoid) {
  20064. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20065. }
  20066. // Animations
  20067. if (parsedCamera.animations) {
  20068. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20069. var parsedAnimation = parsedCamera.animations[animationIndex];
  20070. camera.animations.push(parseAnimation(parsedAnimation));
  20071. }
  20072. }
  20073. if (parsedCamera.autoAnimate) {
  20074. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20075. }
  20076. // Layer Mask
  20077. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20078. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20079. }
  20080. else {
  20081. camera.layerMask = 0xFFFFFFFF;
  20082. }
  20083. return camera;
  20084. };
  20085. var parseGeometry = function (parsedGeometry, scene) {
  20086. var id = parsedGeometry.id;
  20087. return scene.getGeometryByID(id);
  20088. };
  20089. var parseBox = function (parsedBox, scene) {
  20090. if (parseGeometry(parsedBox, scene)) {
  20091. return null; // null since geometry could be something else than a box...
  20092. }
  20093. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20094. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20095. scene.pushGeometry(box, true);
  20096. return box;
  20097. };
  20098. var parseSphere = function (parsedSphere, scene) {
  20099. if (parseGeometry(parsedSphere, scene)) {
  20100. return null; // null since geometry could be something else than a sphere...
  20101. }
  20102. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20103. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20104. scene.pushGeometry(sphere, true);
  20105. return sphere;
  20106. };
  20107. var parseCylinder = function (parsedCylinder, scene) {
  20108. if (parseGeometry(parsedCylinder, scene)) {
  20109. return null; // null since geometry could be something else than a cylinder...
  20110. }
  20111. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20112. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20113. scene.pushGeometry(cylinder, true);
  20114. return cylinder;
  20115. };
  20116. var parseTorus = function (parsedTorus, scene) {
  20117. if (parseGeometry(parsedTorus, scene)) {
  20118. return null; // null since geometry could be something else than a torus...
  20119. }
  20120. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20121. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20122. scene.pushGeometry(torus, true);
  20123. return torus;
  20124. };
  20125. var parseGround = function (parsedGround, scene) {
  20126. if (parseGeometry(parsedGround, scene)) {
  20127. return null; // null since geometry could be something else than a ground...
  20128. }
  20129. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20130. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20131. scene.pushGeometry(ground, true);
  20132. return ground;
  20133. };
  20134. var parsePlane = function (parsedPlane, scene) {
  20135. if (parseGeometry(parsedPlane, scene)) {
  20136. return null; // null since geometry could be something else than a plane...
  20137. }
  20138. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20139. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20140. scene.pushGeometry(plane, true);
  20141. return plane;
  20142. };
  20143. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20144. if (parseGeometry(parsedTorusKnot, scene)) {
  20145. return null; // null since geometry could be something else than a torusKnot...
  20146. }
  20147. 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);
  20148. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20149. scene.pushGeometry(torusKnot, true);
  20150. return torusKnot;
  20151. };
  20152. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20153. if (parseGeometry(parsedVertexData, scene)) {
  20154. return null; // null since geometry could be a primitive
  20155. }
  20156. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20157. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20158. if (parsedVertexData.delayLoadingFile) {
  20159. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20160. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20161. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20162. geometry._delayInfo = [];
  20163. if (parsedVertexData.hasUVs) {
  20164. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20165. }
  20166. if (parsedVertexData.hasUVs2) {
  20167. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20168. }
  20169. if (parsedVertexData.hasColors) {
  20170. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20171. }
  20172. if (parsedVertexData.hasMatricesIndices) {
  20173. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20174. }
  20175. if (parsedVertexData.hasMatricesWeights) {
  20176. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20177. }
  20178. geometry._delayLoadingFunction = importVertexData;
  20179. }
  20180. else {
  20181. importVertexData(parsedVertexData, geometry);
  20182. }
  20183. scene.pushGeometry(geometry, true);
  20184. return geometry;
  20185. };
  20186. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20187. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20188. mesh.id = parsedMesh.id;
  20189. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20190. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20191. if (parsedMesh.rotationQuaternion) {
  20192. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20193. }
  20194. else if (parsedMesh.rotation) {
  20195. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20196. }
  20197. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20198. if (parsedMesh.localMatrix) {
  20199. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20200. }
  20201. else if (parsedMesh.pivotMatrix) {
  20202. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20203. }
  20204. mesh.setEnabled(parsedMesh.isEnabled);
  20205. mesh.isVisible = parsedMesh.isVisible;
  20206. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20207. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20208. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20209. if (parsedMesh.applyFog !== undefined) {
  20210. mesh.applyFog = parsedMesh.applyFog;
  20211. }
  20212. if (parsedMesh.pickable !== undefined) {
  20213. mesh.isPickable = parsedMesh.pickable;
  20214. }
  20215. if (parsedMesh.alphaIndex !== undefined) {
  20216. mesh.alphaIndex = parsedMesh.alphaIndex;
  20217. }
  20218. mesh.receiveShadows = parsedMesh.receiveShadows;
  20219. mesh.billboardMode = parsedMesh.billboardMode;
  20220. if (parsedMesh.visibility !== undefined) {
  20221. mesh.visibility = parsedMesh.visibility;
  20222. }
  20223. mesh.checkCollisions = parsedMesh.checkCollisions;
  20224. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20225. // Parent
  20226. if (parsedMesh.parentId) {
  20227. mesh._waitingParentId = parsedMesh.parentId;
  20228. }
  20229. // Actions
  20230. if (parsedMesh.actions !== undefined) {
  20231. mesh._waitingActions = parsedMesh.actions;
  20232. }
  20233. // Geometry
  20234. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20235. if (parsedMesh.delayLoadingFile) {
  20236. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20237. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20238. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20239. if (parsedMesh._binaryInfo) {
  20240. mesh._binaryInfo = parsedMesh._binaryInfo;
  20241. }
  20242. mesh._delayInfo = [];
  20243. if (parsedMesh.hasUVs) {
  20244. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20245. }
  20246. if (parsedMesh.hasUVs2) {
  20247. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20248. }
  20249. if (parsedMesh.hasColors) {
  20250. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20251. }
  20252. if (parsedMesh.hasMatricesIndices) {
  20253. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20254. }
  20255. if (parsedMesh.hasMatricesWeights) {
  20256. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20257. }
  20258. mesh._delayLoadingFunction = importGeometry;
  20259. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20260. mesh._checkDelayState();
  20261. }
  20262. }
  20263. else {
  20264. importGeometry(parsedMesh, mesh);
  20265. }
  20266. // Material
  20267. if (parsedMesh.materialId) {
  20268. mesh.setMaterialByID(parsedMesh.materialId);
  20269. }
  20270. else {
  20271. mesh.material = null;
  20272. }
  20273. // Skeleton
  20274. if (parsedMesh.skeletonId > -1) {
  20275. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20276. }
  20277. // Physics
  20278. if (parsedMesh.physicsImpostor) {
  20279. if (!scene.isPhysicsEnabled()) {
  20280. scene.enablePhysics();
  20281. }
  20282. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20283. }
  20284. // Animations
  20285. if (parsedMesh.animations) {
  20286. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20287. var parsedAnimation = parsedMesh.animations[animationIndex];
  20288. mesh.animations.push(parseAnimation(parsedAnimation));
  20289. }
  20290. }
  20291. if (parsedMesh.autoAnimate) {
  20292. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20293. }
  20294. // Layer Mask
  20295. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20296. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20297. }
  20298. else {
  20299. mesh.layerMask = 0xFFFFFFFF;
  20300. }
  20301. // Instances
  20302. if (parsedMesh.instances) {
  20303. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20304. var parsedInstance = parsedMesh.instances[index];
  20305. var instance = mesh.createInstance(parsedInstance.name);
  20306. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20307. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20308. if (parsedInstance.rotationQuaternion) {
  20309. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20310. }
  20311. else if (parsedInstance.rotation) {
  20312. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20313. }
  20314. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20315. instance.checkCollisions = mesh.checkCollisions;
  20316. if (parsedMesh.animations) {
  20317. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20318. parsedAnimation = parsedMesh.animations[animationIndex];
  20319. instance.animations.push(parseAnimation(parsedAnimation));
  20320. }
  20321. }
  20322. }
  20323. }
  20324. return mesh;
  20325. };
  20326. var parseActions = function (parsedActions, object, scene) {
  20327. var actionManager = new BABYLON.ActionManager(scene);
  20328. if (object === null)
  20329. scene.actionManager = actionManager;
  20330. else
  20331. object.actionManager = actionManager;
  20332. // instanciate a new object
  20333. var instanciate = function (name, params) {
  20334. var newInstance = Object.create(BABYLON[name].prototype);
  20335. newInstance.constructor.apply(newInstance, params);
  20336. return newInstance;
  20337. };
  20338. var parseParameter = function (name, value, target, propertyPath) {
  20339. if (propertyPath === null) {
  20340. // String, boolean or float
  20341. var floatValue = parseFloat(value);
  20342. if (value === "true" || value === "false")
  20343. return value === "true";
  20344. else
  20345. return isNaN(floatValue) ? value : floatValue;
  20346. }
  20347. var effectiveTarget = propertyPath.split(".");
  20348. var values = value.split(",");
  20349. for (var i = 0; i < effectiveTarget.length; i++) {
  20350. target = target[effectiveTarget[i]];
  20351. }
  20352. // Return appropriate value with its type
  20353. if (target instanceof Boolean)
  20354. return values[0] === "true";
  20355. if (target instanceof String)
  20356. return values[0];
  20357. // Parameters with multiple values such as Vector3 etc.
  20358. var split = new Array();
  20359. for (var i = 0; i < values.length; i++)
  20360. split.push(parseFloat(values[i]));
  20361. if (target instanceof BABYLON.Vector3)
  20362. return BABYLON.Vector3.FromArray(split);
  20363. if (target instanceof BABYLON.Vector4)
  20364. return BABYLON.Vector4.FromArray(split);
  20365. if (target instanceof BABYLON.Color3)
  20366. return BABYLON.Color3.FromArray(split);
  20367. if (target instanceof BABYLON.Color4)
  20368. return BABYLON.Color4.FromArray(split);
  20369. return parseFloat(values[0]);
  20370. };
  20371. // traverse graph per trigger
  20372. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20373. if (combineArray === void 0) { combineArray = null; }
  20374. if (parsedAction.detached)
  20375. return;
  20376. var parameters = new Array();
  20377. var target = null;
  20378. var propertyPath = null;
  20379. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20380. // Parameters
  20381. if (parsedAction.type === 2)
  20382. parameters.push(actionManager);
  20383. else
  20384. parameters.push(trigger);
  20385. if (combine) {
  20386. var actions = new Array();
  20387. for (var j = 0; j < parsedAction.combine.length; j++) {
  20388. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20389. }
  20390. parameters.push(actions);
  20391. }
  20392. else {
  20393. for (var i = 0; i < parsedAction.properties.length; i++) {
  20394. var value = parsedAction.properties[i].value;
  20395. var name = parsedAction.properties[i].name;
  20396. if (name === "target")
  20397. value = target = scene.getNodeByName(value);
  20398. else if (name === "parent")
  20399. value = scene.getNodeByName(value);
  20400. else if (name === "sound")
  20401. value = scene.getSoundByName(value);
  20402. else if (name !== "propertyPath") {
  20403. if (parsedAction.type === 2 && name === "operator")
  20404. value = BABYLON.ValueCondition[value];
  20405. else
  20406. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20407. }
  20408. else {
  20409. propertyPath = value;
  20410. }
  20411. parameters.push(value);
  20412. }
  20413. }
  20414. parameters.push(condition);
  20415. // If interpolate value action
  20416. if (parsedAction.name === "InterpolateValueAction") {
  20417. var param = parameters[parameters.length - 2];
  20418. parameters[parameters.length - 1] = param;
  20419. parameters[parameters.length - 2] = condition;
  20420. }
  20421. // Action or condition(s) and not CombineAction
  20422. var newAction = instanciate(parsedAction.name, parameters);
  20423. if (combineArray === null) {
  20424. if (newAction instanceof BABYLON.Condition) {
  20425. condition = newAction;
  20426. newAction = action;
  20427. }
  20428. else {
  20429. condition = null;
  20430. if (action)
  20431. action.then(newAction);
  20432. else
  20433. actionManager.registerAction(newAction);
  20434. }
  20435. }
  20436. else {
  20437. combineArray.push(newAction);
  20438. }
  20439. for (var i = 0; i < parsedAction.children.length; i++)
  20440. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20441. };
  20442. for (var i = 0; i < parsedActions.children.length; i++) {
  20443. var triggerParams;
  20444. var trigger = parsedActions.children[i];
  20445. if (trigger.properties.length > 0) {
  20446. var param = trigger.properties[0].value;
  20447. var value = trigger.properties[0].targetType == null ? param : scene.getMeshByName(param);
  20448. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20449. }
  20450. else
  20451. triggerParams = BABYLON.ActionManager[trigger.name];
  20452. for (var j = 0; j < trigger.children.length; j++) {
  20453. if (!trigger.detached)
  20454. traverse(trigger.children[j], triggerParams, null, null);
  20455. }
  20456. }
  20457. };
  20458. var parseSound = function (parsedSound, scene, rootUrl) {
  20459. var soundName = parsedSound.name;
  20460. var soundUrl = rootUrl + soundName;
  20461. var options = {
  20462. autoplay: parsedSound.autoplay,
  20463. loop: parsedSound.loop,
  20464. volume: parsedSound.volume,
  20465. spatialSound: parsedSound.spatialSound,
  20466. maxDistance: parsedSound.maxDistance,
  20467. rolloffFactor: parsedSound.rolloffFactor,
  20468. refDistance: parsedSound.refDistance,
  20469. distanceModel: parsedSound.distanceModel,
  20470. playbackRate: parsedSound.playbackRate
  20471. };
  20472. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  20473. scene._removePendingData(newSound);
  20474. }, options);
  20475. scene._addPendingData(newSound);
  20476. if (parsedSound.position) {
  20477. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20478. newSound.setPosition(soundPosition);
  20479. }
  20480. if (parsedSound.isDirectional) {
  20481. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20482. if (parsedSound.localDirectionToMesh) {
  20483. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20484. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20485. }
  20486. }
  20487. if (parsedSound.connectedMeshId) {
  20488. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20489. if (connectedMesh) {
  20490. newSound.attachToMesh(connectedMesh);
  20491. }
  20492. }
  20493. };
  20494. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20495. names = (names instanceof Array) ? names : [names];
  20496. for (var i in names) {
  20497. if (mesh.name === names[i]) {
  20498. hierarchyIds.push(mesh.id);
  20499. return true;
  20500. }
  20501. }
  20502. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20503. hierarchyIds.push(mesh.id);
  20504. return true;
  20505. }
  20506. return false;
  20507. };
  20508. var importVertexData = function (parsedVertexData, geometry) {
  20509. var vertexData = new BABYLON.VertexData();
  20510. // positions
  20511. var positions = parsedVertexData.positions;
  20512. if (positions) {
  20513. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20514. }
  20515. // normals
  20516. var normals = parsedVertexData.normals;
  20517. if (normals) {
  20518. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20519. }
  20520. // uvs
  20521. var uvs = parsedVertexData.uvs;
  20522. if (uvs) {
  20523. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20524. }
  20525. // uv2s
  20526. var uv2s = parsedVertexData.uv2s;
  20527. if (uv2s) {
  20528. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20529. }
  20530. // colors
  20531. var colors = parsedVertexData.colors;
  20532. if (colors) {
  20533. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20534. }
  20535. // matricesIndices
  20536. var matricesIndices = parsedVertexData.matricesIndices;
  20537. if (matricesIndices) {
  20538. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20539. }
  20540. // matricesWeights
  20541. var matricesWeights = parsedVertexData.matricesWeights;
  20542. if (matricesWeights) {
  20543. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20544. }
  20545. // indices
  20546. var indices = parsedVertexData.indices;
  20547. if (indices) {
  20548. vertexData.indices = indices;
  20549. }
  20550. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20551. };
  20552. var importGeometry = function (parsedGeometry, mesh) {
  20553. var scene = mesh.getScene();
  20554. // Geometry
  20555. var geometryId = parsedGeometry.geometryId;
  20556. if (geometryId) {
  20557. var geometry = scene.getGeometryByID(geometryId);
  20558. if (geometry) {
  20559. geometry.applyToMesh(mesh);
  20560. }
  20561. }
  20562. else if (parsedGeometry instanceof ArrayBuffer) {
  20563. var binaryInfo = mesh._binaryInfo;
  20564. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20565. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20566. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20567. }
  20568. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20569. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20570. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20571. }
  20572. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20573. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20574. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20575. }
  20576. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20577. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20578. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20579. }
  20580. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20581. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20582. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20583. }
  20584. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20585. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20586. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20587. }
  20588. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20589. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20590. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20591. }
  20592. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20593. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20594. mesh.setIndices(indicesData);
  20595. }
  20596. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20597. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20598. mesh.subMeshes = [];
  20599. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20600. var materialIndex = subMeshesData[(i * 5) + 0];
  20601. var verticesStart = subMeshesData[(i * 5) + 1];
  20602. var verticesCount = subMeshesData[(i * 5) + 2];
  20603. var indexStart = subMeshesData[(i * 5) + 3];
  20604. var indexCount = subMeshesData[(i * 5) + 4];
  20605. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20606. }
  20607. }
  20608. }
  20609. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20610. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20611. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20612. if (parsedGeometry.uvs) {
  20613. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20614. }
  20615. if (parsedGeometry.uvs2) {
  20616. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20617. }
  20618. if (parsedGeometry.colors) {
  20619. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20620. }
  20621. if (parsedGeometry.matricesIndices) {
  20622. if (!parsedGeometry.matricesIndices._isExpanded) {
  20623. var floatIndices = [];
  20624. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20625. var matricesIndex = parsedGeometry.matricesIndices[i];
  20626. floatIndices.push(matricesIndex & 0x000000FF);
  20627. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20628. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20629. floatIndices.push(matricesIndex >> 24);
  20630. }
  20631. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20632. }
  20633. else {
  20634. delete parsedGeometry.matricesIndices._isExpanded;
  20635. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20636. }
  20637. }
  20638. if (parsedGeometry.matricesWeights) {
  20639. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20640. }
  20641. mesh.setIndices(parsedGeometry.indices);
  20642. // SubMeshes
  20643. if (parsedGeometry.subMeshes) {
  20644. mesh.subMeshes = [];
  20645. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20646. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20647. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20648. }
  20649. }
  20650. }
  20651. // Flat shading
  20652. if (mesh._shouldGenerateFlatShading) {
  20653. mesh.convertToFlatShadedMesh();
  20654. delete mesh._shouldGenerateFlatShading;
  20655. }
  20656. // Update
  20657. mesh.computeWorldMatrix(true);
  20658. // Octree
  20659. if (scene._selectionOctree) {
  20660. scene._selectionOctree.addMesh(mesh);
  20661. }
  20662. };
  20663. BABYLON.SceneLoader.RegisterPlugin({
  20664. extensions: ".babylon",
  20665. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20666. var parsedData = JSON.parse(data);
  20667. var loadedSkeletonsIds = [];
  20668. var loadedMaterialsIds = [];
  20669. var hierarchyIds = [];
  20670. for (var index = 0; index < parsedData.meshes.length; index++) {
  20671. var parsedMesh = parsedData.meshes[index];
  20672. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20673. if (meshesNames instanceof Array) {
  20674. // Remove found mesh name from list.
  20675. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20676. }
  20677. // Material ?
  20678. if (parsedMesh.materialId) {
  20679. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20680. if (!materialFound) {
  20681. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20682. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20683. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20684. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20685. var subMatId = parsedMultiMaterial.materials[matIndex];
  20686. loadedMaterialsIds.push(subMatId);
  20687. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20688. }
  20689. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20690. parseMultiMaterial(parsedMultiMaterial, scene);
  20691. materialFound = true;
  20692. break;
  20693. }
  20694. }
  20695. }
  20696. if (!materialFound) {
  20697. loadedMaterialsIds.push(parsedMesh.materialId);
  20698. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20699. }
  20700. }
  20701. // Skeleton ?
  20702. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20703. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20704. if (!skeletonAlreadyLoaded) {
  20705. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20706. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20707. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20708. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20709. loadedSkeletonsIds.push(parsedSkeleton.id);
  20710. }
  20711. }
  20712. }
  20713. }
  20714. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20715. meshes.push(mesh);
  20716. }
  20717. }
  20718. for (index = 0; index < scene.meshes.length; index++) {
  20719. var currentMesh = scene.meshes[index];
  20720. if (currentMesh._waitingParentId) {
  20721. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20722. currentMesh._waitingParentId = undefined;
  20723. }
  20724. }
  20725. // Particles
  20726. if (parsedData.particleSystems) {
  20727. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20728. var parsedParticleSystem = parsedData.particleSystems[index];
  20729. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20730. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20731. }
  20732. }
  20733. }
  20734. return true;
  20735. },
  20736. load: function (scene, data, rootUrl) {
  20737. var parsedData = JSON.parse(data);
  20738. // Scene
  20739. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20740. scene.autoClear = parsedData.autoClear;
  20741. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20742. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20743. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20744. // Fog
  20745. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20746. scene.fogMode = parsedData.fogMode;
  20747. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20748. scene.fogStart = parsedData.fogStart;
  20749. scene.fogEnd = parsedData.fogEnd;
  20750. scene.fogDensity = parsedData.fogDensity;
  20751. }
  20752. for (var index = 0; index < parsedData.lights.length; index++) {
  20753. var parsedLight = parsedData.lights[index];
  20754. parseLight(parsedLight, scene);
  20755. }
  20756. // Materials
  20757. if (parsedData.materials) {
  20758. for (index = 0; index < parsedData.materials.length; index++) {
  20759. var parsedMaterial = parsedData.materials[index];
  20760. parseMaterial(parsedMaterial, scene, rootUrl);
  20761. }
  20762. }
  20763. if (parsedData.multiMaterials) {
  20764. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20765. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20766. parseMultiMaterial(parsedMultiMaterial, scene);
  20767. }
  20768. }
  20769. // Skeletons
  20770. if (parsedData.skeletons) {
  20771. for (index = 0; index < parsedData.skeletons.length; index++) {
  20772. var parsedSkeleton = parsedData.skeletons[index];
  20773. parseSkeleton(parsedSkeleton, scene);
  20774. }
  20775. }
  20776. // Geometries
  20777. var geometries = parsedData.geometries;
  20778. if (geometries) {
  20779. // Boxes
  20780. var boxes = geometries.boxes;
  20781. if (boxes) {
  20782. for (index = 0; index < boxes.length; index++) {
  20783. var parsedBox = boxes[index];
  20784. parseBox(parsedBox, scene);
  20785. }
  20786. }
  20787. // Spheres
  20788. var spheres = geometries.spheres;
  20789. if (spheres) {
  20790. for (index = 0; index < spheres.length; index++) {
  20791. var parsedSphere = spheres[index];
  20792. parseSphere(parsedSphere, scene);
  20793. }
  20794. }
  20795. // Cylinders
  20796. var cylinders = geometries.cylinders;
  20797. if (cylinders) {
  20798. for (index = 0; index < cylinders.length; index++) {
  20799. var parsedCylinder = cylinders[index];
  20800. parseCylinder(parsedCylinder, scene);
  20801. }
  20802. }
  20803. // Toruses
  20804. var toruses = geometries.toruses;
  20805. if (toruses) {
  20806. for (index = 0; index < toruses.length; index++) {
  20807. var parsedTorus = toruses[index];
  20808. parseTorus(parsedTorus, scene);
  20809. }
  20810. }
  20811. // Grounds
  20812. var grounds = geometries.grounds;
  20813. if (grounds) {
  20814. for (index = 0; index < grounds.length; index++) {
  20815. var parsedGround = grounds[index];
  20816. parseGround(parsedGround, scene);
  20817. }
  20818. }
  20819. // Planes
  20820. var planes = geometries.planes;
  20821. if (planes) {
  20822. for (index = 0; index < planes.length; index++) {
  20823. var parsedPlane = planes[index];
  20824. parsePlane(parsedPlane, scene);
  20825. }
  20826. }
  20827. // TorusKnots
  20828. var torusKnots = geometries.torusKnots;
  20829. if (torusKnots) {
  20830. for (index = 0; index < torusKnots.length; index++) {
  20831. var parsedTorusKnot = torusKnots[index];
  20832. parseTorusKnot(parsedTorusKnot, scene);
  20833. }
  20834. }
  20835. // VertexData
  20836. var vertexData = geometries.vertexData;
  20837. if (vertexData) {
  20838. for (index = 0; index < vertexData.length; index++) {
  20839. var parsedVertexData = vertexData[index];
  20840. parseVertexData(parsedVertexData, scene, rootUrl);
  20841. }
  20842. }
  20843. }
  20844. for (index = 0; index < parsedData.meshes.length; index++) {
  20845. var parsedMesh = parsedData.meshes[index];
  20846. parseMesh(parsedMesh, scene, rootUrl);
  20847. }
  20848. for (index = 0; index < parsedData.cameras.length; index++) {
  20849. var parsedCamera = parsedData.cameras[index];
  20850. parseCamera(parsedCamera, scene);
  20851. }
  20852. if (parsedData.activeCameraID) {
  20853. scene.setActiveCameraByID(parsedData.activeCameraID);
  20854. }
  20855. for (index = 0; index < scene.cameras.length; index++) {
  20856. var camera = scene.cameras[index];
  20857. if (camera._waitingParentId) {
  20858. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20859. camera._waitingParentId = undefined;
  20860. }
  20861. }
  20862. for (index = 0; index < scene.lights.length; index++) {
  20863. var light = scene.lights[index];
  20864. if (light._waitingParentId) {
  20865. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20866. light._waitingParentId = undefined;
  20867. }
  20868. }
  20869. // Sounds
  20870. if (parsedData.sounds) {
  20871. for (index = 0; index < parsedData.sounds.length; index++) {
  20872. var parsedSound = parsedData.sounds[index];
  20873. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20874. parseSound(parsedSound, scene, rootUrl);
  20875. }
  20876. else {
  20877. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20878. }
  20879. }
  20880. }
  20881. for (index = 0; index < scene.meshes.length; index++) {
  20882. var mesh = scene.meshes[index];
  20883. if (mesh._waitingParentId) {
  20884. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20885. mesh._waitingParentId = undefined;
  20886. }
  20887. if (mesh._waitingActions) {
  20888. parseActions(mesh._waitingActions, mesh, scene);
  20889. mesh._waitingActions = undefined;
  20890. }
  20891. }
  20892. // Particles Systems
  20893. if (parsedData.particleSystems) {
  20894. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20895. var parsedParticleSystem = parsedData.particleSystems[index];
  20896. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20897. }
  20898. }
  20899. // Lens flares
  20900. if (parsedData.lensFlareSystems) {
  20901. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20902. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20903. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20904. }
  20905. }
  20906. // Shadows
  20907. if (parsedData.shadowGenerators) {
  20908. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20909. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20910. parseShadowGenerator(parsedShadowGenerator, scene);
  20911. }
  20912. }
  20913. // Actions (scene)
  20914. if (parsedData.actions) {
  20915. parseActions(parsedData.actions, null, scene);
  20916. }
  20917. // Finish
  20918. return true;
  20919. }
  20920. });
  20921. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20922. })(BABYLON || (BABYLON = {}));
  20923. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20924. (function (BABYLON) {
  20925. // Unique ID when we import meshes from Babylon to CSG
  20926. var currentCSGMeshId = 0;
  20927. // # class Vertex
  20928. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20929. // one to provide additional features like texture coordinates and vertex
  20930. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20931. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20932. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20933. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20934. // is not used anywhere else.
  20935. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20936. var Vertex = (function () {
  20937. function Vertex(pos, normal, uv) {
  20938. this.pos = pos;
  20939. this.normal = normal;
  20940. this.uv = uv;
  20941. }
  20942. Vertex.prototype.clone = function () {
  20943. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20944. };
  20945. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20946. // orientation of a polygon is flipped.
  20947. Vertex.prototype.flip = function () {
  20948. this.normal = this.normal.scale(-1);
  20949. };
  20950. // Create a new vertex between this vertex and `other` by linearly
  20951. // interpolating all properties using a parameter of `t`. Subclasses should
  20952. // override this to interpolate additional properties.
  20953. Vertex.prototype.interpolate = function (other, t) {
  20954. 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));
  20955. };
  20956. return Vertex;
  20957. })();
  20958. // # class Plane
  20959. // Represents a plane in 3D space.
  20960. var Plane = (function () {
  20961. function Plane(normal, w) {
  20962. this.normal = normal;
  20963. this.w = w;
  20964. }
  20965. Plane.FromPoints = function (a, b, c) {
  20966. var v0 = c.subtract(a);
  20967. var v1 = b.subtract(a);
  20968. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20969. return null;
  20970. }
  20971. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20972. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20973. };
  20974. Plane.prototype.clone = function () {
  20975. return new Plane(this.normal.clone(), this.w);
  20976. };
  20977. Plane.prototype.flip = function () {
  20978. this.normal.scaleInPlace(-1);
  20979. this.w = -this.w;
  20980. };
  20981. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20982. // fragments in the appropriate lists. Coplanar polygons go into either
  20983. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20984. // respect to this plane. Polygons in front or in back of this plane go into
  20985. // either `front` or `back`.
  20986. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20987. var COPLANAR = 0;
  20988. var FRONT = 1;
  20989. var BACK = 2;
  20990. var SPANNING = 3;
  20991. // Classify each point as well as the entire polygon into one of the above
  20992. // four classes.
  20993. var polygonType = 0;
  20994. var types = [];
  20995. for (var i = 0; i < polygon.vertices.length; i++) {
  20996. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20997. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20998. polygonType |= type;
  20999. types.push(type);
  21000. }
  21001. switch (polygonType) {
  21002. case COPLANAR:
  21003. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  21004. break;
  21005. case FRONT:
  21006. front.push(polygon);
  21007. break;
  21008. case BACK:
  21009. back.push(polygon);
  21010. break;
  21011. case SPANNING:
  21012. var f = [], b = [];
  21013. for (i = 0; i < polygon.vertices.length; i++) {
  21014. var j = (i + 1) % polygon.vertices.length;
  21015. var ti = types[i], tj = types[j];
  21016. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  21017. if (ti != BACK)
  21018. f.push(vi);
  21019. if (ti != FRONT)
  21020. b.push(ti != BACK ? vi.clone() : vi);
  21021. if ((ti | tj) == SPANNING) {
  21022. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  21023. var v = vi.interpolate(vj, t);
  21024. f.push(v);
  21025. b.push(v.clone());
  21026. }
  21027. }
  21028. if (f.length >= 3) {
  21029. var poly = new Polygon(f, polygon.shared);
  21030. if (poly.plane)
  21031. front.push(poly);
  21032. }
  21033. if (b.length >= 3) {
  21034. poly = new Polygon(b, polygon.shared);
  21035. if (poly.plane)
  21036. back.push(poly);
  21037. }
  21038. break;
  21039. }
  21040. };
  21041. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  21042. // point is on the plane.
  21043. Plane.EPSILON = 1e-5;
  21044. return Plane;
  21045. })();
  21046. // # class Polygon
  21047. // Represents a convex polygon. The vertices used to initialize a polygon must
  21048. // be coplanar and form a convex loop.
  21049. //
  21050. // Each convex polygon has a `shared` property, which is shared between all
  21051. // polygons that are clones of each other or were split from the same polygon.
  21052. // This can be used to define per-polygon properties (such as surface color).
  21053. var Polygon = (function () {
  21054. function Polygon(vertices, shared) {
  21055. this.vertices = vertices;
  21056. this.shared = shared;
  21057. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  21058. }
  21059. Polygon.prototype.clone = function () {
  21060. var vertices = this.vertices.map(function (v) { return v.clone(); });
  21061. return new Polygon(vertices, this.shared);
  21062. };
  21063. Polygon.prototype.flip = function () {
  21064. this.vertices.reverse().map(function (v) {
  21065. v.flip();
  21066. });
  21067. this.plane.flip();
  21068. };
  21069. return Polygon;
  21070. })();
  21071. // # class Node
  21072. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  21073. // by picking a polygon to split along. That polygon (and all other coplanar
  21074. // polygons) are added directly to that node and the other polygons are added to
  21075. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  21076. // no distinction between internal and leaf nodes.
  21077. var Node = (function () {
  21078. function Node(polygons) {
  21079. this.plane = null;
  21080. this.front = null;
  21081. this.back = null;
  21082. this.polygons = [];
  21083. if (polygons) {
  21084. this.build(polygons);
  21085. }
  21086. }
  21087. Node.prototype.clone = function () {
  21088. var node = new Node();
  21089. node.plane = this.plane && this.plane.clone();
  21090. node.front = this.front && this.front.clone();
  21091. node.back = this.back && this.back.clone();
  21092. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  21093. return node;
  21094. };
  21095. // Convert solid space to empty space and empty space to solid space.
  21096. Node.prototype.invert = function () {
  21097. for (var i = 0; i < this.polygons.length; i++) {
  21098. this.polygons[i].flip();
  21099. }
  21100. if (this.plane) {
  21101. this.plane.flip();
  21102. }
  21103. if (this.front) {
  21104. this.front.invert();
  21105. }
  21106. if (this.back) {
  21107. this.back.invert();
  21108. }
  21109. var temp = this.front;
  21110. this.front = this.back;
  21111. this.back = temp;
  21112. };
  21113. // Recursively remove all polygons in `polygons` that are inside this BSP
  21114. // tree.
  21115. Node.prototype.clipPolygons = function (polygons) {
  21116. if (!this.plane)
  21117. return polygons.slice();
  21118. var front = [], back = [];
  21119. for (var i = 0; i < polygons.length; i++) {
  21120. this.plane.splitPolygon(polygons[i], front, back, front, back);
  21121. }
  21122. if (this.front) {
  21123. front = this.front.clipPolygons(front);
  21124. }
  21125. if (this.back) {
  21126. back = this.back.clipPolygons(back);
  21127. }
  21128. else {
  21129. back = [];
  21130. }
  21131. return front.concat(back);
  21132. };
  21133. // Remove all polygons in this BSP tree that are inside the other BSP tree
  21134. // `bsp`.
  21135. Node.prototype.clipTo = function (bsp) {
  21136. this.polygons = bsp.clipPolygons(this.polygons);
  21137. if (this.front)
  21138. this.front.clipTo(bsp);
  21139. if (this.back)
  21140. this.back.clipTo(bsp);
  21141. };
  21142. // Return a list of all polygons in this BSP tree.
  21143. Node.prototype.allPolygons = function () {
  21144. var polygons = this.polygons.slice();
  21145. if (this.front)
  21146. polygons = polygons.concat(this.front.allPolygons());
  21147. if (this.back)
  21148. polygons = polygons.concat(this.back.allPolygons());
  21149. return polygons;
  21150. };
  21151. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  21152. // new polygons are filtered down to the bottom of the tree and become new
  21153. // nodes there. Each set of polygons is partitioned using the first polygon
  21154. // (no heuristic is used to pick a good split).
  21155. Node.prototype.build = function (polygons) {
  21156. if (!polygons.length)
  21157. return;
  21158. if (!this.plane)
  21159. this.plane = polygons[0].plane.clone();
  21160. var front = [], back = [];
  21161. for (var i = 0; i < polygons.length; i++) {
  21162. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  21163. }
  21164. if (front.length) {
  21165. if (!this.front)
  21166. this.front = new Node();
  21167. this.front.build(front);
  21168. }
  21169. if (back.length) {
  21170. if (!this.back)
  21171. this.back = new Node();
  21172. this.back.build(back);
  21173. }
  21174. };
  21175. return Node;
  21176. })();
  21177. var CSG = (function () {
  21178. function CSG() {
  21179. this.polygons = new Array();
  21180. }
  21181. // Convert BABYLON.Mesh to BABYLON.CSG
  21182. CSG.FromMesh = function (mesh) {
  21183. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  21184. if (mesh instanceof BABYLON.Mesh) {
  21185. mesh.computeWorldMatrix(true);
  21186. var matrix = mesh.getWorldMatrix();
  21187. var meshPosition = mesh.position.clone();
  21188. var meshRotation = mesh.rotation.clone();
  21189. var meshScaling = mesh.scaling.clone();
  21190. }
  21191. else {
  21192. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  21193. }
  21194. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21195. var subMeshes = mesh.subMeshes;
  21196. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  21197. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  21198. vertices = [];
  21199. for (var j = 0; j < 3; j++) {
  21200. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  21201. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  21202. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  21203. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  21204. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  21205. vertex = new Vertex(position, normal, uv);
  21206. vertices.push(vertex);
  21207. }
  21208. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  21209. // To handle the case of degenerated triangle
  21210. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  21211. if (polygon.plane)
  21212. polygons.push(polygon);
  21213. }
  21214. }
  21215. var csg = CSG.FromPolygons(polygons);
  21216. csg.matrix = matrix;
  21217. csg.position = meshPosition;
  21218. csg.rotation = meshRotation;
  21219. csg.scaling = meshScaling;
  21220. currentCSGMeshId++;
  21221. return csg;
  21222. };
  21223. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  21224. CSG.FromPolygons = function (polygons) {
  21225. var csg = new BABYLON.CSG();
  21226. csg.polygons = polygons;
  21227. return csg;
  21228. };
  21229. CSG.prototype.clone = function () {
  21230. var csg = new BABYLON.CSG();
  21231. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  21232. csg.copyTransformAttributes(this);
  21233. return csg;
  21234. };
  21235. CSG.prototype.toPolygons = function () {
  21236. return this.polygons;
  21237. };
  21238. CSG.prototype.union = function (csg) {
  21239. var a = new Node(this.clone().polygons);
  21240. var b = new Node(csg.clone().polygons);
  21241. a.clipTo(b);
  21242. b.clipTo(a);
  21243. b.invert();
  21244. b.clipTo(a);
  21245. b.invert();
  21246. a.build(b.allPolygons());
  21247. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21248. };
  21249. CSG.prototype.unionInPlace = function (csg) {
  21250. var a = new Node(this.polygons);
  21251. var b = new Node(csg.polygons);
  21252. a.clipTo(b);
  21253. b.clipTo(a);
  21254. b.invert();
  21255. b.clipTo(a);
  21256. b.invert();
  21257. a.build(b.allPolygons());
  21258. this.polygons = a.allPolygons();
  21259. };
  21260. CSG.prototype.subtract = function (csg) {
  21261. var a = new Node(this.clone().polygons);
  21262. var b = new Node(csg.clone().polygons);
  21263. a.invert();
  21264. a.clipTo(b);
  21265. b.clipTo(a);
  21266. b.invert();
  21267. b.clipTo(a);
  21268. b.invert();
  21269. a.build(b.allPolygons());
  21270. a.invert();
  21271. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21272. };
  21273. CSG.prototype.subtractInPlace = function (csg) {
  21274. var a = new Node(this.polygons);
  21275. var b = new Node(csg.polygons);
  21276. a.invert();
  21277. a.clipTo(b);
  21278. b.clipTo(a);
  21279. b.invert();
  21280. b.clipTo(a);
  21281. b.invert();
  21282. a.build(b.allPolygons());
  21283. a.invert();
  21284. this.polygons = a.allPolygons();
  21285. };
  21286. CSG.prototype.intersect = function (csg) {
  21287. var a = new Node(this.clone().polygons);
  21288. var b = new Node(csg.clone().polygons);
  21289. a.invert();
  21290. b.clipTo(a);
  21291. b.invert();
  21292. a.clipTo(b);
  21293. b.clipTo(a);
  21294. a.build(b.allPolygons());
  21295. a.invert();
  21296. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21297. };
  21298. CSG.prototype.intersectInPlace = function (csg) {
  21299. var a = new Node(this.polygons);
  21300. var b = new Node(csg.polygons);
  21301. a.invert();
  21302. b.clipTo(a);
  21303. b.invert();
  21304. a.clipTo(b);
  21305. b.clipTo(a);
  21306. a.build(b.allPolygons());
  21307. a.invert();
  21308. this.polygons = a.allPolygons();
  21309. };
  21310. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  21311. // not modified.
  21312. CSG.prototype.inverse = function () {
  21313. var csg = this.clone();
  21314. csg.inverseInPlace();
  21315. return csg;
  21316. };
  21317. CSG.prototype.inverseInPlace = function () {
  21318. this.polygons.map(function (p) {
  21319. p.flip();
  21320. });
  21321. };
  21322. // This is used to keep meshes transformations so they can be restored
  21323. // when we build back a Babylon Mesh
  21324. // NB : All CSG operations are performed in world coordinates
  21325. CSG.prototype.copyTransformAttributes = function (csg) {
  21326. this.matrix = csg.matrix;
  21327. this.position = csg.position;
  21328. this.rotation = csg.rotation;
  21329. this.scaling = csg.scaling;
  21330. return this;
  21331. };
  21332. // Build Raw mesh from CSG
  21333. // Coordinates here are in world space
  21334. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  21335. var matrix = this.matrix.clone();
  21336. matrix.invert();
  21337. 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;
  21338. if (keepSubMeshes) {
  21339. // Sort Polygons, since subMeshes are indices range
  21340. polygons.sort(function (a, b) {
  21341. if (a.shared.meshId === b.shared.meshId) {
  21342. return a.shared.subMeshId - b.shared.subMeshId;
  21343. }
  21344. else {
  21345. return a.shared.meshId - b.shared.meshId;
  21346. }
  21347. });
  21348. }
  21349. for (var i = 0, il = polygons.length; i < il; i++) {
  21350. polygon = polygons[i];
  21351. // Building SubMeshes
  21352. if (!subMesh_dict[polygon.shared.meshId]) {
  21353. subMesh_dict[polygon.shared.meshId] = {};
  21354. }
  21355. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  21356. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  21357. indexStart: +Infinity,
  21358. indexEnd: -Infinity,
  21359. materialIndex: polygon.shared.materialIndex
  21360. };
  21361. }
  21362. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  21363. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  21364. polygonIndices[0] = 0;
  21365. polygonIndices[1] = j - 1;
  21366. polygonIndices[2] = j;
  21367. for (var k = 0; k < 3; k++) {
  21368. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  21369. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  21370. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  21371. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  21372. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  21373. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  21374. // Check if 2 points can be merged
  21375. 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)) {
  21376. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  21377. uvs.push(uv.x, uv.y);
  21378. normals.push(normal.x, normal.y, normal.z);
  21379. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  21380. }
  21381. indices.push(vertex_idx);
  21382. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  21383. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  21384. currentIndex++;
  21385. }
  21386. }
  21387. }
  21388. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  21389. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21390. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  21391. mesh.setIndices(indices);
  21392. if (keepSubMeshes) {
  21393. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  21394. var materialIndexOffset = 0, materialMaxIndex;
  21395. mesh.subMeshes.length = 0;
  21396. for (var m in subMesh_dict) {
  21397. materialMaxIndex = -1;
  21398. for (var sm in subMesh_dict[m]) {
  21399. subMesh_obj = subMesh_dict[m][sm];
  21400. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  21401. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  21402. }
  21403. materialIndexOffset += ++materialMaxIndex;
  21404. }
  21405. }
  21406. return mesh;
  21407. };
  21408. // Build Mesh from CSG taking material and transforms into account
  21409. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  21410. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  21411. mesh.material = material;
  21412. mesh.position.copyFrom(this.position);
  21413. mesh.rotation.copyFrom(this.rotation);
  21414. mesh.scaling.copyFrom(this.scaling);
  21415. mesh.computeWorldMatrix(true);
  21416. return mesh;
  21417. };
  21418. return CSG;
  21419. })();
  21420. BABYLON.CSG = CSG;
  21421. })(BABYLON || (BABYLON = {}));
  21422. //# sourceMappingURL=babylon.csg.js.map
  21423. var BABYLON;
  21424. (function (BABYLON) {
  21425. var OculusDistortionCorrectionPostProcess = (function (_super) {
  21426. __extends(OculusDistortionCorrectionPostProcess, _super);
  21427. //ANY
  21428. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  21429. var _this = this;
  21430. _super.call(this, name, "oculusDistortionCorrection", [
  21431. 'LensCenter',
  21432. 'Scale',
  21433. 'ScaleIn',
  21434. 'HmdWarpParam'
  21435. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  21436. this._isRightEye = isRightEye;
  21437. this._distortionFactors = cameraSettings.DistortionK;
  21438. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  21439. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  21440. this.onSizeChanged = function () {
  21441. _this.aspectRatio = _this.width * .5 / _this.height;
  21442. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  21443. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  21444. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  21445. };
  21446. this.onApply = function (effect) {
  21447. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  21448. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  21449. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  21450. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  21451. };
  21452. }
  21453. return OculusDistortionCorrectionPostProcess;
  21454. })(BABYLON.PostProcess);
  21455. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  21456. })(BABYLON || (BABYLON = {}));
  21457. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  21458. // 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
  21459. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  21460. var BABYLON;
  21461. (function (BABYLON) {
  21462. (function (JoystickAxis) {
  21463. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  21464. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  21465. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  21466. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  21467. var JoystickAxis = BABYLON.JoystickAxis;
  21468. var VirtualJoystick = (function () {
  21469. function VirtualJoystick(leftJoystick) {
  21470. var _this = this;
  21471. if (leftJoystick) {
  21472. this._leftJoystick = true;
  21473. }
  21474. else {
  21475. this._leftJoystick = false;
  21476. }
  21477. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  21478. VirtualJoystick._globalJoystickIndex++;
  21479. // By default left & right arrow keys are moving the X
  21480. // and up & down keys are moving the Y
  21481. this._axisTargetedByLeftAndRight = 0 /* X */;
  21482. this._axisTargetedByUpAndDown = 1 /* Y */;
  21483. this.reverseLeftRight = false;
  21484. this.reverseUpDown = false;
  21485. // collections of pointers
  21486. this._touches = new BABYLON.SmartCollection();
  21487. this.deltaPosition = BABYLON.Vector3.Zero();
  21488. this._joystickSensibility = 25;
  21489. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21490. this._rotationSpeed = 25;
  21491. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21492. this._rotateOnAxisRelativeToMesh = false;
  21493. // injecting a canvas element on top of the canvas 3D game
  21494. if (!VirtualJoystick.vjCanvas) {
  21495. window.addEventListener("resize", function () {
  21496. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21497. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21498. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21499. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21500. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21501. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21502. }, false);
  21503. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21504. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21505. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21506. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21507. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21508. VirtualJoystick.vjCanvas.style.width = "100%";
  21509. VirtualJoystick.vjCanvas.style.height = "100%";
  21510. VirtualJoystick.vjCanvas.style.position = "absolute";
  21511. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21512. VirtualJoystick.vjCanvas.style.top = "0px";
  21513. VirtualJoystick.vjCanvas.style.left = "0px";
  21514. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21515. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21516. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21517. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21518. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21519. document.body.appendChild(VirtualJoystick.vjCanvas);
  21520. }
  21521. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21522. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21523. this.pressed = false;
  21524. // default joystick color
  21525. this._joystickColor = "cyan";
  21526. this._joystickPointerID = -1;
  21527. // current joystick position
  21528. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21529. // origin joystick position
  21530. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21531. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21532. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21533. _this._onPointerDown(evt);
  21534. }, false);
  21535. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21536. _this._onPointerMove(evt);
  21537. }, false);
  21538. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21539. _this._onPointerUp(evt);
  21540. }, false);
  21541. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21542. _this._onPointerUp(evt);
  21543. }, false);
  21544. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21545. evt.preventDefault(); // Disables system menu
  21546. }, false);
  21547. requestAnimationFrame(function () {
  21548. _this._drawVirtualJoystick();
  21549. });
  21550. }
  21551. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21552. this._joystickSensibility = newJoystickSensibility;
  21553. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21554. };
  21555. VirtualJoystick.prototype._onPointerDown = function (e) {
  21556. var positionOnScreenCondition;
  21557. e.preventDefault();
  21558. if (this._leftJoystick === true) {
  21559. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21560. }
  21561. else {
  21562. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21563. }
  21564. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21565. // First contact will be dedicated to the virtual joystick
  21566. this._joystickPointerID = e.pointerId;
  21567. this._joystickPointerStartPos.x = e.clientX;
  21568. this._joystickPointerStartPos.y = e.clientY;
  21569. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21570. this._deltaJoystickVector.x = 0;
  21571. this._deltaJoystickVector.y = 0;
  21572. this.pressed = true;
  21573. this._touches.add(e.pointerId.toString(), e);
  21574. }
  21575. else {
  21576. // You can only trigger the action buttons with a joystick declared
  21577. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21578. this._action();
  21579. this._touches.add(e.pointerId.toString(), e);
  21580. }
  21581. }
  21582. };
  21583. VirtualJoystick.prototype._onPointerMove = function (e) {
  21584. // If the current pointer is the one associated to the joystick (first touch contact)
  21585. if (this._joystickPointerID == e.pointerId) {
  21586. this._joystickPointerPos.x = e.clientX;
  21587. this._joystickPointerPos.y = e.clientY;
  21588. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21589. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21590. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21591. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21592. switch (this._axisTargetedByLeftAndRight) {
  21593. case 0 /* X */:
  21594. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21595. break;
  21596. case 1 /* Y */:
  21597. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21598. break;
  21599. case 2 /* Z */:
  21600. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21601. break;
  21602. }
  21603. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21604. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21605. switch (this._axisTargetedByUpAndDown) {
  21606. case 0 /* X */:
  21607. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21608. break;
  21609. case 1 /* Y */:
  21610. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21611. break;
  21612. case 2 /* Z */:
  21613. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21614. break;
  21615. }
  21616. }
  21617. else {
  21618. if (this._touches.item(e.pointerId.toString())) {
  21619. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21620. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21621. }
  21622. }
  21623. };
  21624. VirtualJoystick.prototype._onPointerUp = function (e) {
  21625. this._clearCanvas();
  21626. if (this._joystickPointerID == e.pointerId) {
  21627. this._joystickPointerID = -1;
  21628. this.pressed = false;
  21629. }
  21630. this._deltaJoystickVector.x = 0;
  21631. this._deltaJoystickVector.y = 0;
  21632. this._touches.remove(e.pointerId.toString());
  21633. };
  21634. /**
  21635. * Change the color of the virtual joystick
  21636. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21637. */
  21638. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21639. this._joystickColor = newColor;
  21640. };
  21641. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21642. this._action = action;
  21643. };
  21644. // Define which axis you'd like to control for left & right
  21645. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21646. switch (axis) {
  21647. case 0 /* X */:
  21648. case 1 /* Y */:
  21649. case 2 /* Z */:
  21650. this._axisTargetedByLeftAndRight = axis;
  21651. break;
  21652. default:
  21653. this._axisTargetedByLeftAndRight = 0 /* X */;
  21654. break;
  21655. }
  21656. };
  21657. // Define which axis you'd like to control for up & down
  21658. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21659. switch (axis) {
  21660. case 0 /* X */:
  21661. case 1 /* Y */:
  21662. case 2 /* Z */:
  21663. this._axisTargetedByUpAndDown = axis;
  21664. break;
  21665. default:
  21666. this._axisTargetedByUpAndDown = 1 /* Y */;
  21667. break;
  21668. }
  21669. };
  21670. VirtualJoystick.prototype._clearCanvas = function () {
  21671. if (this._leftJoystick) {
  21672. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21673. }
  21674. else {
  21675. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21676. }
  21677. };
  21678. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21679. var _this = this;
  21680. if (this.pressed) {
  21681. this._clearCanvas();
  21682. this._touches.forEach(function (touch) {
  21683. if (touch.pointerId === _this._joystickPointerID) {
  21684. VirtualJoystick.vjCanvasContext.beginPath();
  21685. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21686. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21687. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21688. VirtualJoystick.vjCanvasContext.stroke();
  21689. VirtualJoystick.vjCanvasContext.beginPath();
  21690. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21691. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21692. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21693. VirtualJoystick.vjCanvasContext.stroke();
  21694. VirtualJoystick.vjCanvasContext.beginPath();
  21695. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21696. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21697. VirtualJoystick.vjCanvasContext.stroke();
  21698. }
  21699. else {
  21700. VirtualJoystick.vjCanvasContext.beginPath();
  21701. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21702. VirtualJoystick.vjCanvasContext.beginPath();
  21703. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21704. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21705. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21706. VirtualJoystick.vjCanvasContext.stroke();
  21707. }
  21708. ;
  21709. });
  21710. }
  21711. requestAnimationFrame(function () {
  21712. _this._drawVirtualJoystick();
  21713. });
  21714. };
  21715. VirtualJoystick.prototype.releaseCanvas = function () {
  21716. if (VirtualJoystick.vjCanvas) {
  21717. document.body.removeChild(VirtualJoystick.vjCanvas);
  21718. VirtualJoystick.vjCanvas = null;
  21719. }
  21720. };
  21721. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21722. VirtualJoystick._globalJoystickIndex = 0;
  21723. return VirtualJoystick;
  21724. })();
  21725. BABYLON.VirtualJoystick = VirtualJoystick;
  21726. })(BABYLON || (BABYLON = {}));
  21727. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21728. var BABYLON;
  21729. (function (BABYLON) {
  21730. var OculusRiftDevKit2013_Metric = {
  21731. HResolution: 1280,
  21732. VResolution: 800,
  21733. HScreenSize: 0.149759993,
  21734. VScreenSize: 0.0935999975,
  21735. VScreenCenter: 0.0467999987,
  21736. EyeToScreenDistance: 0.0410000011,
  21737. LensSeparationDistance: 0.0635000020,
  21738. InterpupillaryDistance: 0.0640000030,
  21739. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21740. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21741. PostProcessScaleFactor: 1.714605507808412,
  21742. LensCenterOffset: 0.151976421
  21743. };
  21744. var _OculusInnerCamera = (function (_super) {
  21745. __extends(_OculusInnerCamera, _super);
  21746. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21747. _super.call(this, name, position, scene);
  21748. this._workMatrix = new BABYLON.Matrix();
  21749. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21750. // Constants
  21751. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21752. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21753. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21754. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21755. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21756. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21757. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21758. // Postprocess
  21759. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21760. }
  21761. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21762. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21763. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21764. return this._projectionMatrix;
  21765. };
  21766. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21767. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21768. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21769. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21770. // Computing target and final matrix
  21771. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21772. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21773. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21774. return this._viewMatrix;
  21775. };
  21776. return _OculusInnerCamera;
  21777. })(BABYLON.FreeCamera);
  21778. var OculusCamera = (function (_super) {
  21779. __extends(OculusCamera, _super);
  21780. function OculusCamera(name, position, scene) {
  21781. _super.call(this, name, position, scene);
  21782. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21783. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21784. this.subCameras.push(this._leftCamera);
  21785. this.subCameras.push(this._rightCamera);
  21786. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21787. }
  21788. OculusCamera.prototype._update = function () {
  21789. this._leftCamera.position.copyFrom(this.position);
  21790. this._rightCamera.position.copyFrom(this.position);
  21791. this._updateCamera(this._leftCamera);
  21792. this._updateCamera(this._rightCamera);
  21793. _super.prototype._update.call(this);
  21794. };
  21795. OculusCamera.prototype._updateCamera = function (camera) {
  21796. camera.minZ = this.minZ;
  21797. camera.maxZ = this.maxZ;
  21798. camera.rotation.x = this.rotation.x;
  21799. camera.rotation.y = this.rotation.y;
  21800. camera.rotation.z = this.rotation.z;
  21801. };
  21802. // Oculus events
  21803. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21804. var yaw = evt.alpha / 180 * Math.PI;
  21805. var pitch = evt.beta / 180 * Math.PI;
  21806. var roll = evt.gamma / 180 * Math.PI;
  21807. if (!this._offsetOrientation) {
  21808. this._offsetOrientation = {
  21809. yaw: yaw,
  21810. pitch: pitch,
  21811. roll: roll
  21812. };
  21813. return;
  21814. }
  21815. else {
  21816. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21817. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21818. this.rotation.z += this._offsetOrientation.roll - roll;
  21819. this._offsetOrientation.yaw = yaw;
  21820. this._offsetOrientation.pitch = pitch;
  21821. this._offsetOrientation.roll = roll;
  21822. }
  21823. };
  21824. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21825. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21826. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21827. };
  21828. OculusCamera.prototype.detachControl = function (element) {
  21829. _super.prototype.detachControl.call(this, element);
  21830. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21831. };
  21832. return OculusCamera;
  21833. })(BABYLON.FreeCamera);
  21834. BABYLON.OculusCamera = OculusCamera;
  21835. })(BABYLON || (BABYLON = {}));
  21836. //# sourceMappingURL=babylon.oculusCamera.js.map
  21837. var BABYLON;
  21838. (function (BABYLON) {
  21839. var OculusRiftDevKit2013_Metric = {
  21840. HResolution: 1280,
  21841. VResolution: 800,
  21842. HScreenSize: 0.149759993,
  21843. VScreenSize: 0.0935999975,
  21844. VScreenCenter: 0.0467999987,
  21845. EyeToScreenDistance: 0.0410000011,
  21846. LensSeparationDistance: 0.0635000020,
  21847. InterpupillaryDistance: 0.0640000030,
  21848. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21849. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21850. PostProcessScaleFactor: 1.714605507808412,
  21851. LensCenterOffset: 0.151976421
  21852. };
  21853. var _OculusInnerGamepadCamera = (function (_super) {
  21854. __extends(_OculusInnerGamepadCamera, _super);
  21855. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21856. _super.call(this, name, position, scene);
  21857. this._workMatrix = new BABYLON.Matrix();
  21858. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21859. // Constants
  21860. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21861. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21862. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21863. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21864. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21865. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21866. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21867. // Postprocess
  21868. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21869. }
  21870. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21871. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21872. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21873. return this._projectionMatrix;
  21874. };
  21875. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21876. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21877. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21878. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21879. // Computing target and final matrix
  21880. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21881. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21882. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21883. return this._viewMatrix;
  21884. };
  21885. return _OculusInnerGamepadCamera;
  21886. })(BABYLON.FreeCamera);
  21887. var OculusGamepadCamera = (function (_super) {
  21888. __extends(OculusGamepadCamera, _super);
  21889. function OculusGamepadCamera(name, position, scene) {
  21890. var _this = this;
  21891. _super.call(this, name, position, scene);
  21892. this.angularSensibility = 200;
  21893. this.moveSensibility = 75;
  21894. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21895. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21896. this.subCameras.push(this._leftCamera);
  21897. this.subCameras.push(this._rightCamera);
  21898. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21899. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21900. _this._onNewGameConnected(gamepad);
  21901. });
  21902. }
  21903. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21904. // Only the first gamepad can control the camera
  21905. if (gamepad.index === 0) {
  21906. this._gamepad = gamepad;
  21907. }
  21908. };
  21909. OculusGamepadCamera.prototype._update = function () {
  21910. this._leftCamera.position.copyFrom(this.position);
  21911. this._rightCamera.position.copyFrom(this.position);
  21912. this._updateCamera(this._leftCamera);
  21913. this._updateCamera(this._rightCamera);
  21914. _super.prototype._update.call(this);
  21915. };
  21916. OculusGamepadCamera.prototype._checkInputs = function () {
  21917. if (!this._gamepad) {
  21918. return;
  21919. }
  21920. var LSValues = this._gamepad.leftStick;
  21921. var normalizedLX = LSValues.x / this.moveSensibility;
  21922. var normalizedLY = LSValues.y / this.moveSensibility;
  21923. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21924. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21925. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21926. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21927. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21928. };
  21929. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21930. camera.minZ = this.minZ;
  21931. camera.maxZ = this.maxZ;
  21932. camera.rotation.x = this.rotation.x;
  21933. camera.rotation.y = this.rotation.y;
  21934. camera.rotation.z = this.rotation.z;
  21935. };
  21936. // Oculus events
  21937. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21938. var yaw = evt.alpha / 180 * Math.PI;
  21939. var pitch = evt.beta / 180 * Math.PI;
  21940. var roll = evt.gamma / 180 * Math.PI;
  21941. if (!this._offsetOrientation) {
  21942. this._offsetOrientation = {
  21943. yaw: yaw,
  21944. pitch: pitch,
  21945. roll: roll
  21946. };
  21947. return;
  21948. }
  21949. else {
  21950. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21951. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21952. this.rotation.z += this._offsetOrientation.roll - roll;
  21953. this._offsetOrientation.yaw = yaw;
  21954. this._offsetOrientation.pitch = pitch;
  21955. this._offsetOrientation.roll = roll;
  21956. }
  21957. };
  21958. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21959. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21960. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21961. };
  21962. OculusGamepadCamera.prototype.detachControl = function (element) {
  21963. _super.prototype.detachControl.call(this, element);
  21964. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21965. };
  21966. OculusGamepadCamera.prototype.dispose = function () {
  21967. this._gamepads.dispose();
  21968. _super.prototype.dispose.call(this);
  21969. };
  21970. return OculusGamepadCamera;
  21971. })(BABYLON.FreeCamera);
  21972. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21973. })(BABYLON || (BABYLON = {}));
  21974. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21975. var BABYLON;
  21976. (function (BABYLON) {
  21977. // We're mainly based on the logic defined into the FreeCamera code
  21978. var VirtualJoysticksCamera = (function (_super) {
  21979. __extends(VirtualJoysticksCamera, _super);
  21980. function VirtualJoysticksCamera(name, position, scene) {
  21981. _super.call(this, name, position, scene);
  21982. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21983. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21984. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21985. this._leftjoystick.setJoystickSensibility(0.15);
  21986. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21987. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21988. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21989. this._rightjoystick.reverseUpDown = true;
  21990. this._rightjoystick.setJoystickSensibility(0.05);
  21991. this._rightjoystick.setJoystickColor("yellow");
  21992. }
  21993. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21994. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21995. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21996. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21997. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21998. if (!this._leftjoystick.pressed) {
  21999. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  22000. }
  22001. if (!this._rightjoystick.pressed) {
  22002. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  22003. }
  22004. };
  22005. VirtualJoysticksCamera.prototype.dispose = function () {
  22006. this._leftjoystick.releaseCanvas();
  22007. _super.prototype.dispose.call(this);
  22008. };
  22009. return VirtualJoysticksCamera;
  22010. })(BABYLON.FreeCamera);
  22011. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  22012. })(BABYLON || (BABYLON = {}));
  22013. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  22014. var BABYLON;
  22015. (function (BABYLON) {
  22016. var ShaderMaterial = (function (_super) {
  22017. __extends(ShaderMaterial, _super);
  22018. function ShaderMaterial(name, scene, shaderPath, options) {
  22019. _super.call(this, name, scene);
  22020. this._textures = new Array();
  22021. this._floats = new Array();
  22022. this._floatsArrays = {};
  22023. this._colors3 = new Array();
  22024. this._colors4 = new Array();
  22025. this._vectors2 = new Array();
  22026. this._vectors3 = new Array();
  22027. this._matrices = new Array();
  22028. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  22029. this._shaderPath = shaderPath;
  22030. options.needAlphaBlending = options.needAlphaBlending || false;
  22031. options.needAlphaTesting = options.needAlphaTesting || false;
  22032. options.attributes = options.attributes || ["position", "normal", "uv"];
  22033. options.uniforms = options.uniforms || ["worldViewProjection"];
  22034. options.samplers = options.samplers || [];
  22035. this._options = options;
  22036. }
  22037. ShaderMaterial.prototype.needAlphaBlending = function () {
  22038. return this._options.needAlphaBlending;
  22039. };
  22040. ShaderMaterial.prototype.needAlphaTesting = function () {
  22041. return this._options.needAlphaTesting;
  22042. };
  22043. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  22044. if (this._options.uniforms.indexOf(uniformName) === -1) {
  22045. this._options.uniforms.push(uniformName);
  22046. }
  22047. };
  22048. ShaderMaterial.prototype.setTexture = function (name, texture) {
  22049. if (this._options.samplers.indexOf(name) === -1) {
  22050. this._options.samplers.push(name);
  22051. }
  22052. this._textures[name] = texture;
  22053. return this;
  22054. };
  22055. ShaderMaterial.prototype.setFloat = function (name, value) {
  22056. this._checkUniform(name);
  22057. this._floats[name] = value;
  22058. return this;
  22059. };
  22060. ShaderMaterial.prototype.setFloats = function (name, value) {
  22061. this._checkUniform(name);
  22062. this._floatsArrays[name] = value;
  22063. return this;
  22064. };
  22065. ShaderMaterial.prototype.setColor3 = function (name, value) {
  22066. this._checkUniform(name);
  22067. this._colors3[name] = value;
  22068. return this;
  22069. };
  22070. ShaderMaterial.prototype.setColor4 = function (name, value) {
  22071. this._checkUniform(name);
  22072. this._colors4[name] = value;
  22073. return this;
  22074. };
  22075. ShaderMaterial.prototype.setVector2 = function (name, value) {
  22076. this._checkUniform(name);
  22077. this._vectors2[name] = value;
  22078. return this;
  22079. };
  22080. ShaderMaterial.prototype.setVector3 = function (name, value) {
  22081. this._checkUniform(name);
  22082. this._vectors3[name] = value;
  22083. return this;
  22084. };
  22085. ShaderMaterial.prototype.setMatrix = function (name, value) {
  22086. this._checkUniform(name);
  22087. this._matrices[name] = value;
  22088. return this;
  22089. };
  22090. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  22091. var scene = this.getScene();
  22092. var engine = scene.getEngine();
  22093. if (!this.checkReadyOnEveryCall) {
  22094. if (this._renderId === scene.getRenderId()) {
  22095. return true;
  22096. }
  22097. }
  22098. // Instances
  22099. var defines = [];
  22100. var fallbacks = new BABYLON.EffectFallbacks();
  22101. if (useInstances) {
  22102. defines.push("#define INSTANCES");
  22103. }
  22104. // Bones
  22105. if (mesh && mesh.useBones) {
  22106. defines.push("#define BONES");
  22107. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  22108. defines.push("#define BONES4");
  22109. fallbacks.addFallback(0, "BONES4");
  22110. }
  22111. // Alpha test
  22112. if (engine.getAlphaTesting()) {
  22113. defines.push("#define ALPHATEST");
  22114. }
  22115. var previousEffect = this._effect;
  22116. var join = defines.join("\n");
  22117. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  22118. if (!this._effect.isReady()) {
  22119. return false;
  22120. }
  22121. if (previousEffect !== this._effect) {
  22122. scene.resetCachedMaterial();
  22123. }
  22124. this._renderId = scene.getRenderId();
  22125. return true;
  22126. };
  22127. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22128. var scene = this.getScene();
  22129. if (this._options.uniforms.indexOf("world") !== -1) {
  22130. this._effect.setMatrix("world", world);
  22131. }
  22132. if (this._options.uniforms.indexOf("worldView") !== -1) {
  22133. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  22134. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  22135. }
  22136. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  22137. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  22138. }
  22139. };
  22140. ShaderMaterial.prototype.bind = function (world, mesh) {
  22141. // Std values
  22142. this.bindOnlyWorldMatrix(world);
  22143. if (this.getScene().getCachedMaterial() !== this) {
  22144. if (this._options.uniforms.indexOf("view") !== -1) {
  22145. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  22146. }
  22147. if (this._options.uniforms.indexOf("projection") !== -1) {
  22148. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  22149. }
  22150. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  22151. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22152. }
  22153. // Bones
  22154. if (mesh && mesh.useBones) {
  22155. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22156. }
  22157. for (var name in this._textures) {
  22158. this._effect.setTexture(name, this._textures[name]);
  22159. }
  22160. for (name in this._floats) {
  22161. this._effect.setFloat(name, this._floats[name]);
  22162. }
  22163. for (name in this._floatsArrays) {
  22164. this._effect.setArray(name, this._floatsArrays[name]);
  22165. }
  22166. for (name in this._colors3) {
  22167. this._effect.setColor3(name, this._colors3[name]);
  22168. }
  22169. for (name in this._colors4) {
  22170. var color = this._colors4[name];
  22171. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22172. }
  22173. for (name in this._vectors2) {
  22174. this._effect.setVector2(name, this._vectors2[name]);
  22175. }
  22176. for (name in this._vectors3) {
  22177. this._effect.setVector3(name, this._vectors3[name]);
  22178. }
  22179. for (name in this._matrices) {
  22180. this._effect.setMatrix(name, this._matrices[name]);
  22181. }
  22182. }
  22183. _super.prototype.bind.call(this, world, mesh);
  22184. };
  22185. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  22186. for (var name in this._textures) {
  22187. this._textures[name].dispose();
  22188. }
  22189. this._textures = [];
  22190. _super.prototype.dispose.call(this, forceDisposeEffect);
  22191. };
  22192. return ShaderMaterial;
  22193. })(BABYLON.Material);
  22194. BABYLON.ShaderMaterial = ShaderMaterial;
  22195. })(BABYLON || (BABYLON = {}));
  22196. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  22197. (function (BABYLON) {
  22198. var VertexData = (function () {
  22199. function VertexData() {
  22200. }
  22201. VertexData.prototype.set = function (data, kind) {
  22202. switch (kind) {
  22203. case BABYLON.VertexBuffer.PositionKind:
  22204. this.positions = data;
  22205. break;
  22206. case BABYLON.VertexBuffer.NormalKind:
  22207. this.normals = data;
  22208. break;
  22209. case BABYLON.VertexBuffer.UVKind:
  22210. this.uvs = data;
  22211. break;
  22212. case BABYLON.VertexBuffer.UV2Kind:
  22213. this.uv2s = data;
  22214. break;
  22215. case BABYLON.VertexBuffer.ColorKind:
  22216. this.colors = data;
  22217. break;
  22218. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22219. this.matricesIndices = data;
  22220. break;
  22221. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22222. this.matricesWeights = data;
  22223. break;
  22224. }
  22225. };
  22226. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22227. this._applyTo(mesh, updatable);
  22228. };
  22229. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22230. this._applyTo(geometry, updatable);
  22231. };
  22232. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22233. this._update(mesh);
  22234. };
  22235. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22236. this._update(geometry);
  22237. };
  22238. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22239. if (this.positions) {
  22240. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22241. }
  22242. if (this.normals) {
  22243. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22244. }
  22245. if (this.uvs) {
  22246. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22247. }
  22248. if (this.uv2s) {
  22249. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  22250. }
  22251. if (this.colors) {
  22252. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22253. }
  22254. if (this.matricesIndices) {
  22255. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22256. }
  22257. if (this.matricesWeights) {
  22258. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22259. }
  22260. if (this.indices) {
  22261. meshOrGeometry.setIndices(this.indices);
  22262. }
  22263. };
  22264. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22265. if (this.positions) {
  22266. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22267. }
  22268. if (this.normals) {
  22269. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22270. }
  22271. if (this.uvs) {
  22272. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22273. }
  22274. if (this.uv2s) {
  22275. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  22276. }
  22277. if (this.colors) {
  22278. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22279. }
  22280. if (this.matricesIndices) {
  22281. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22282. }
  22283. if (this.matricesWeights) {
  22284. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22285. }
  22286. if (this.indices) {
  22287. meshOrGeometry.setIndices(this.indices);
  22288. }
  22289. };
  22290. VertexData.prototype.transform = function (matrix) {
  22291. var transformed = BABYLON.Vector3.Zero();
  22292. if (this.positions) {
  22293. var position = BABYLON.Vector3.Zero();
  22294. for (var index = 0; index < this.positions.length; index += 3) {
  22295. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22296. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22297. this.positions[index] = transformed.x;
  22298. this.positions[index + 1] = transformed.y;
  22299. this.positions[index + 2] = transformed.z;
  22300. }
  22301. }
  22302. if (this.normals) {
  22303. var normal = BABYLON.Vector3.Zero();
  22304. for (index = 0; index < this.normals.length; index += 3) {
  22305. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22306. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22307. this.normals[index] = transformed.x;
  22308. this.normals[index + 1] = transformed.y;
  22309. this.normals[index + 2] = transformed.z;
  22310. }
  22311. }
  22312. };
  22313. VertexData.prototype.merge = function (other) {
  22314. if (other.indices) {
  22315. if (!this.indices) {
  22316. this.indices = [];
  22317. }
  22318. var offset = this.positions ? this.positions.length / 3 : 0;
  22319. for (var index = 0; index < other.indices.length; index++) {
  22320. this.indices.push(other.indices[index] + offset);
  22321. }
  22322. }
  22323. if (other.positions) {
  22324. if (!this.positions) {
  22325. this.positions = [];
  22326. }
  22327. for (index = 0; index < other.positions.length; index++) {
  22328. this.positions.push(other.positions[index]);
  22329. }
  22330. }
  22331. if (other.normals) {
  22332. if (!this.normals) {
  22333. this.normals = [];
  22334. }
  22335. for (index = 0; index < other.normals.length; index++) {
  22336. this.normals.push(other.normals[index]);
  22337. }
  22338. }
  22339. if (other.uvs) {
  22340. if (!this.uvs) {
  22341. this.uvs = [];
  22342. }
  22343. for (index = 0; index < other.uvs.length; index++) {
  22344. this.uvs.push(other.uvs[index]);
  22345. }
  22346. }
  22347. if (other.uv2s) {
  22348. if (!this.uv2s) {
  22349. this.uv2s = [];
  22350. }
  22351. for (index = 0; index < other.uv2s.length; index++) {
  22352. this.uv2s.push(other.uv2s[index]);
  22353. }
  22354. }
  22355. if (other.matricesIndices) {
  22356. if (!this.matricesIndices) {
  22357. this.matricesIndices = [];
  22358. }
  22359. for (index = 0; index < other.matricesIndices.length; index++) {
  22360. this.matricesIndices.push(other.matricesIndices[index]);
  22361. }
  22362. }
  22363. if (other.matricesWeights) {
  22364. if (!this.matricesWeights) {
  22365. this.matricesWeights = [];
  22366. }
  22367. for (index = 0; index < other.matricesWeights.length; index++) {
  22368. this.matricesWeights.push(other.matricesWeights[index]);
  22369. }
  22370. }
  22371. if (other.colors) {
  22372. if (!this.colors) {
  22373. this.colors = [];
  22374. }
  22375. for (index = 0; index < other.colors.length; index++) {
  22376. this.colors.push(other.colors[index]);
  22377. }
  22378. }
  22379. };
  22380. // Statics
  22381. VertexData.ExtractFromMesh = function (mesh) {
  22382. return VertexData._ExtractFrom(mesh);
  22383. };
  22384. VertexData.ExtractFromGeometry = function (geometry) {
  22385. return VertexData._ExtractFrom(geometry);
  22386. };
  22387. VertexData._ExtractFrom = function (meshOrGeometry) {
  22388. var result = new VertexData();
  22389. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22390. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22391. }
  22392. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22393. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22394. }
  22395. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22396. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22397. }
  22398. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22399. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22400. }
  22401. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22402. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22403. }
  22404. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22405. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22406. }
  22407. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22408. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22409. }
  22410. result.indices = meshOrGeometry.getIndices();
  22411. return result;
  22412. };
  22413. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  22414. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22415. closeArray = closeArray || false;
  22416. closePath = closePath || false;
  22417. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22418. offset = offset || defaultOffset;
  22419. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22420. var positions = [];
  22421. var indices = [];
  22422. var normals = [];
  22423. var uvs = [];
  22424. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22425. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22426. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22427. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22428. var minlg; // minimal length among all paths from pathArray
  22429. var lg = []; // array of path lengths : nb of vertex per path
  22430. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  22431. var p; // path iterator
  22432. var i; // point iterator
  22433. var j; // point iterator
  22434. // if single path in pathArray
  22435. if (pathArray.length < 2) {
  22436. var ar1 = [];
  22437. var ar2 = [];
  22438. for (i = 0; i < pathArray[0].length - offset; i++) {
  22439. ar1.push(pathArray[0][i]);
  22440. ar2.push(pathArray[0][i + offset]);
  22441. }
  22442. pathArray = [ar1, ar2];
  22443. }
  22444. // positions and horizontal distances (u)
  22445. var idc = 0;
  22446. minlg = pathArray[0].length;
  22447. for (p = 0; p < pathArray.length; p++) {
  22448. uTotalDistance[p] = 0;
  22449. us[p] = [0];
  22450. var path = pathArray[p];
  22451. var l = path.length;
  22452. minlg = (minlg < l) ? minlg : l;
  22453. lg[p] = l;
  22454. idx[p] = idc;
  22455. j = 0;
  22456. while (j < l) {
  22457. positions.push(path[j].x, path[j].y, path[j].z);
  22458. if (j > 0) {
  22459. var vectlg = path[j].subtract(path[j - 1]).length();
  22460. var dist = vectlg + uTotalDistance[p];
  22461. us[p].push(dist);
  22462. uTotalDistance[p] = dist;
  22463. }
  22464. j++;
  22465. }
  22466. if (closePath) {
  22467. vectlg = path[0].subtract(path[j - 1]).length();
  22468. dist = vectlg + uTotalDistance[p];
  22469. uTotalDistance[p] = dist;
  22470. }
  22471. idc += l;
  22472. }
  22473. for (i = 0; i < minlg; i++) {
  22474. vTotalDistance[i] = 0;
  22475. vs[i] = [0];
  22476. var path1;
  22477. var path2;
  22478. for (p = 0; p < pathArray.length - 1; p++) {
  22479. path1 = pathArray[p];
  22480. path2 = pathArray[p + 1];
  22481. vectlg = path2[i].subtract(path1[i]).length();
  22482. dist = vectlg + vTotalDistance[i];
  22483. vs[i].push(dist);
  22484. vTotalDistance[i] = dist;
  22485. }
  22486. if (closeArray) {
  22487. path1 = pathArray[p];
  22488. path2 = pathArray[0];
  22489. vectlg = path2[i].subtract(path1[i]).length();
  22490. dist = vectlg + vTotalDistance[i];
  22491. vTotalDistance[i] = dist;
  22492. }
  22493. }
  22494. // uvs
  22495. var u;
  22496. var v;
  22497. for (p = 0; p < pathArray.length; p++) {
  22498. for (i = 0; i < minlg; i++) {
  22499. u = us[p][i] / uTotalDistance[p];
  22500. v = vs[i][p] / vTotalDistance[i];
  22501. uvs.push(u, v);
  22502. }
  22503. }
  22504. // indices
  22505. p = 0; // path index
  22506. var pi = 0; // positions array index
  22507. var l1 = lg[p] - 1; // path1 length
  22508. var l2 = lg[p + 1] - 1; // path2 length
  22509. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22510. var shft = idx[1] - idx[0]; // shift
  22511. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22512. var t1; // two consecutive triangles, so 4 points : point1
  22513. var t2; // point2
  22514. var t3; // point3
  22515. var t4; // point4
  22516. while (pi <= min && p < path1nb) {
  22517. // 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
  22518. t1 = pi;
  22519. t2 = pi + shft;
  22520. t3 = pi + 1;
  22521. t4 = pi + shft + 1;
  22522. indices.push(pi, pi + shft, pi + 1);
  22523. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22524. pi += 1;
  22525. if (pi === min) {
  22526. if (closePath) {
  22527. indices.push(pi, pi + shft, idx[p]);
  22528. indices.push(idx[p] + shft, idx[p], pi + shft);
  22529. t3 = idx[p];
  22530. t4 = idx[p] + shft;
  22531. }
  22532. p++;
  22533. if (p === lg.length - 1) {
  22534. shft = idx[0] - idx[p];
  22535. l1 = lg[p] - 1;
  22536. l2 = lg[0] - 1;
  22537. }
  22538. else {
  22539. shft = idx[p + 1] - idx[p];
  22540. l1 = lg[p] - 1;
  22541. l2 = lg[p + 1] - 1;
  22542. }
  22543. pi = idx[p];
  22544. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22545. }
  22546. }
  22547. // normals
  22548. VertexData.ComputeNormals(positions, indices, normals);
  22549. // sides
  22550. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22551. // Result
  22552. var vertexData = new VertexData();
  22553. vertexData.indices = indices;
  22554. vertexData.positions = positions;
  22555. vertexData.normals = normals;
  22556. vertexData.uvs = uvs;
  22557. return vertexData;
  22558. };
  22559. VertexData.CreateBox = function (size, sideOrientation) {
  22560. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22561. var normalsSource = [
  22562. new BABYLON.Vector3(0, 0, 1),
  22563. new BABYLON.Vector3(0, 0, -1),
  22564. new BABYLON.Vector3(1, 0, 0),
  22565. new BABYLON.Vector3(-1, 0, 0),
  22566. new BABYLON.Vector3(0, 1, 0),
  22567. new BABYLON.Vector3(0, -1, 0)
  22568. ];
  22569. var indices = [];
  22570. var positions = [];
  22571. var normals = [];
  22572. var uvs = [];
  22573. size = size || 1;
  22574. for (var index = 0; index < normalsSource.length; index++) {
  22575. var normal = normalsSource[index];
  22576. // Get two vectors perpendicular to the face normal and to each other.
  22577. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22578. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22579. // Six indices (two triangles) per face.
  22580. var verticesLength = positions.length / 3;
  22581. indices.push(verticesLength);
  22582. indices.push(verticesLength + 1);
  22583. indices.push(verticesLength + 2);
  22584. indices.push(verticesLength);
  22585. indices.push(verticesLength + 2);
  22586. indices.push(verticesLength + 3);
  22587. // Four vertices per face.
  22588. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22589. positions.push(vertex.x, vertex.y, vertex.z);
  22590. normals.push(normal.x, normal.y, normal.z);
  22591. uvs.push(1.0, 1.0);
  22592. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22593. positions.push(vertex.x, vertex.y, vertex.z);
  22594. normals.push(normal.x, normal.y, normal.z);
  22595. uvs.push(0.0, 1.0);
  22596. vertex = normal.add(side1).add(side2).scale(size / 2);
  22597. positions.push(vertex.x, vertex.y, vertex.z);
  22598. normals.push(normal.x, normal.y, normal.z);
  22599. uvs.push(0.0, 0.0);
  22600. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22601. positions.push(vertex.x, vertex.y, vertex.z);
  22602. normals.push(normal.x, normal.y, normal.z);
  22603. uvs.push(1.0, 0.0);
  22604. }
  22605. // sides
  22606. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22607. // Result
  22608. var vertexData = new VertexData();
  22609. vertexData.indices = indices;
  22610. vertexData.positions = positions;
  22611. vertexData.normals = normals;
  22612. vertexData.uvs = uvs;
  22613. return vertexData;
  22614. };
  22615. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22616. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22617. segments = segments || 32;
  22618. diameter = diameter || 1;
  22619. var radius = diameter / 2;
  22620. var totalZRotationSteps = 2 + segments;
  22621. var totalYRotationSteps = 2 * totalZRotationSteps;
  22622. var indices = [];
  22623. var positions = [];
  22624. var normals = [];
  22625. var uvs = [];
  22626. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22627. var normalizedZ = zRotationStep / totalZRotationSteps;
  22628. var angleZ = (normalizedZ * Math.PI);
  22629. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22630. var normalizedY = yRotationStep / totalYRotationSteps;
  22631. var angleY = normalizedY * Math.PI * 2;
  22632. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22633. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22634. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22635. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22636. var vertex = complete.scale(radius);
  22637. var normal = BABYLON.Vector3.Normalize(vertex);
  22638. positions.push(vertex.x, vertex.y, vertex.z);
  22639. normals.push(normal.x, normal.y, normal.z);
  22640. uvs.push(normalizedZ, normalizedY);
  22641. }
  22642. if (zRotationStep > 0) {
  22643. var verticesCount = positions.length / 3;
  22644. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22645. indices.push((firstIndex));
  22646. indices.push((firstIndex + 1));
  22647. indices.push(firstIndex + totalYRotationSteps + 1);
  22648. indices.push((firstIndex + totalYRotationSteps + 1));
  22649. indices.push((firstIndex + 1));
  22650. indices.push((firstIndex + totalYRotationSteps + 2));
  22651. }
  22652. }
  22653. }
  22654. // Sides
  22655. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22656. // Result
  22657. var vertexData = new VertexData();
  22658. vertexData.indices = indices;
  22659. vertexData.positions = positions;
  22660. vertexData.normals = normals;
  22661. vertexData.uvs = uvs;
  22662. return vertexData;
  22663. };
  22664. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22665. if (subdivisions === void 0) { subdivisions = 1; }
  22666. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22667. var radiusTop = diameterTop / 2;
  22668. var radiusBottom = diameterBottom / 2;
  22669. var indices = [];
  22670. var positions = [];
  22671. var normals = [];
  22672. var uvs = [];
  22673. height = height || 1;
  22674. diameterTop = diameterTop || 0.5;
  22675. diameterBottom = diameterBottom || 1;
  22676. tessellation = tessellation || 16;
  22677. subdivisions = subdivisions || 1;
  22678. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22679. var getCircleVector = function (i) {
  22680. var angle = (i * 2.0 * Math.PI / tessellation);
  22681. var dx = Math.cos(angle);
  22682. var dz = Math.sin(angle);
  22683. return new BABYLON.Vector3(dx, 0, dz);
  22684. };
  22685. var createCylinderCap = function (isTop) {
  22686. var radius = isTop ? radiusTop : radiusBottom;
  22687. if (radius === 0) {
  22688. return;
  22689. }
  22690. var vbase = positions.length / 3;
  22691. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22692. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22693. if (!isTop) {
  22694. offset.scaleInPlace(-1);
  22695. textureScale.x = -textureScale.x;
  22696. }
  22697. for (var i = 0; i < tessellation; i++) {
  22698. var circleVector = getCircleVector(i);
  22699. var position = circleVector.scale(radius).add(offset);
  22700. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22701. positions.push(position.x, position.y, position.z);
  22702. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22703. }
  22704. for (i = 0; i < tessellation - 2; i++) {
  22705. if (!isTop) {
  22706. indices.push(vbase);
  22707. indices.push(vbase + (i + 2) % tessellation);
  22708. indices.push(vbase + (i + 1) % tessellation);
  22709. }
  22710. else {
  22711. indices.push(vbase);
  22712. indices.push(vbase + (i + 1) % tessellation);
  22713. indices.push(vbase + (i + 2) % tessellation);
  22714. }
  22715. }
  22716. };
  22717. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22718. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22719. var stride = tessellation + 1;
  22720. for (var i = 0; i <= tessellation; i++) {
  22721. var circleVector = getCircleVector(i);
  22722. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22723. var position, radius = radiusBottom;
  22724. for (var s = 0; s <= subdivisions; s++) {
  22725. // Update variables
  22726. position = circleVector.scale(radius);
  22727. position.addInPlace(base.add(offset.scale(s)));
  22728. textureCoordinate.y += 1 / subdivisions;
  22729. radius += (radiusTop - radiusBottom) / subdivisions;
  22730. // Push in arrays
  22731. positions.push(position.x, position.y, position.z);
  22732. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22733. }
  22734. }
  22735. subdivisions += 1;
  22736. for (s = 0; s < subdivisions - 1; s++) {
  22737. for (i = 0; i <= tessellation; i++) {
  22738. indices.push(i * subdivisions + s);
  22739. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22740. indices.push(i * subdivisions + (s + 1));
  22741. indices.push(i * subdivisions + (s + 1));
  22742. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22743. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22744. }
  22745. }
  22746. // Create flat triangle fan caps to seal the top and bottom.
  22747. createCylinderCap(true);
  22748. createCylinderCap(false);
  22749. // Normals
  22750. VertexData.ComputeNormals(positions, indices, normals);
  22751. // Sides
  22752. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22753. // Result
  22754. var vertexData = new VertexData();
  22755. vertexData.indices = indices;
  22756. vertexData.positions = positions;
  22757. vertexData.normals = normals;
  22758. vertexData.uvs = uvs;
  22759. return vertexData;
  22760. };
  22761. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22762. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22763. var indices = [];
  22764. var positions = [];
  22765. var normals = [];
  22766. var uvs = [];
  22767. diameter = diameter || 1;
  22768. thickness = thickness || 0.5;
  22769. tessellation = tessellation || 16;
  22770. var stride = tessellation + 1;
  22771. for (var i = 0; i <= tessellation; i++) {
  22772. var u = i / tessellation;
  22773. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22774. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22775. for (var j = 0; j <= tessellation; j++) {
  22776. var v = 1 - j / tessellation;
  22777. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22778. var dx = Math.cos(innerAngle);
  22779. var dy = Math.sin(innerAngle);
  22780. // Create a vertex.
  22781. var normal = new BABYLON.Vector3(dx, dy, 0);
  22782. var position = normal.scale(thickness / 2);
  22783. var textureCoordinate = new BABYLON.Vector2(u, v);
  22784. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22785. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22786. positions.push(position.x, position.y, position.z);
  22787. normals.push(normal.x, normal.y, normal.z);
  22788. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22789. // And create indices for two triangles.
  22790. var nextI = (i + 1) % stride;
  22791. var nextJ = (j + 1) % stride;
  22792. indices.push(i * stride + j);
  22793. indices.push(i * stride + nextJ);
  22794. indices.push(nextI * stride + j);
  22795. indices.push(i * stride + nextJ);
  22796. indices.push(nextI * stride + nextJ);
  22797. indices.push(nextI * stride + j);
  22798. }
  22799. }
  22800. // Sides
  22801. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22802. // Result
  22803. var vertexData = new VertexData();
  22804. vertexData.indices = indices;
  22805. vertexData.positions = positions;
  22806. vertexData.normals = normals;
  22807. vertexData.uvs = uvs;
  22808. return vertexData;
  22809. };
  22810. VertexData.CreateLines = function (points) {
  22811. var indices = [];
  22812. var positions = [];
  22813. for (var index = 0; index < points.length; index++) {
  22814. positions.push(points[index].x, points[index].y, points[index].z);
  22815. if (index > 0) {
  22816. indices.push(index - 1);
  22817. indices.push(index);
  22818. }
  22819. }
  22820. // Result
  22821. var vertexData = new VertexData();
  22822. vertexData.indices = indices;
  22823. vertexData.positions = positions;
  22824. return vertexData;
  22825. };
  22826. VertexData.CreateGround = function (width, height, subdivisions) {
  22827. var indices = [];
  22828. var positions = [];
  22829. var normals = [];
  22830. var uvs = [];
  22831. var row, col;
  22832. width = width || 1;
  22833. height = height || 1;
  22834. subdivisions = subdivisions || 1;
  22835. for (row = 0; row <= subdivisions; row++) {
  22836. for (col = 0; col <= subdivisions; col++) {
  22837. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22838. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22839. positions.push(position.x, position.y, position.z);
  22840. normals.push(normal.x, normal.y, normal.z);
  22841. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22842. }
  22843. }
  22844. for (row = 0; row < subdivisions; row++) {
  22845. for (col = 0; col < subdivisions; col++) {
  22846. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22847. indices.push(col + 1 + row * (subdivisions + 1));
  22848. indices.push(col + row * (subdivisions + 1));
  22849. indices.push(col + (row + 1) * (subdivisions + 1));
  22850. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22851. indices.push(col + row * (subdivisions + 1));
  22852. }
  22853. }
  22854. // Result
  22855. var vertexData = new VertexData();
  22856. vertexData.indices = indices;
  22857. vertexData.positions = positions;
  22858. vertexData.normals = normals;
  22859. vertexData.uvs = uvs;
  22860. return vertexData;
  22861. };
  22862. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22863. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22864. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22865. var indices = [];
  22866. var positions = [];
  22867. var normals = [];
  22868. var uvs = [];
  22869. var row, col, tileRow, tileCol;
  22870. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22871. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22872. precision.w = (precision.w < 1) ? 1 : precision.w;
  22873. precision.h = (precision.h < 1) ? 1 : precision.h;
  22874. var tileSize = {
  22875. 'w': (xmax - xmin) / subdivisions.w,
  22876. 'h': (zmax - zmin) / subdivisions.h
  22877. };
  22878. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22879. // Indices
  22880. var base = positions.length / 3;
  22881. var rowLength = precision.w + 1;
  22882. for (row = 0; row < precision.h; row++) {
  22883. for (col = 0; col < precision.w; col++) {
  22884. var square = [
  22885. base + col + row * rowLength,
  22886. base + (col + 1) + row * rowLength,
  22887. base + (col + 1) + (row + 1) * rowLength,
  22888. base + col + (row + 1) * rowLength
  22889. ];
  22890. indices.push(square[1]);
  22891. indices.push(square[2]);
  22892. indices.push(square[3]);
  22893. indices.push(square[0]);
  22894. indices.push(square[1]);
  22895. indices.push(square[3]);
  22896. }
  22897. }
  22898. // Position, normals and uvs
  22899. var position = BABYLON.Vector3.Zero();
  22900. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22901. for (row = 0; row <= precision.h; row++) {
  22902. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22903. for (col = 0; col <= precision.w; col++) {
  22904. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22905. position.y = 0;
  22906. positions.push(position.x, position.y, position.z);
  22907. normals.push(normal.x, normal.y, normal.z);
  22908. uvs.push(col / precision.w, row / precision.h);
  22909. }
  22910. }
  22911. }
  22912. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22913. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22914. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22915. }
  22916. }
  22917. // Result
  22918. var vertexData = new VertexData();
  22919. vertexData.indices = indices;
  22920. vertexData.positions = positions;
  22921. vertexData.normals = normals;
  22922. vertexData.uvs = uvs;
  22923. return vertexData;
  22924. };
  22925. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22926. var indices = [];
  22927. var positions = [];
  22928. var normals = [];
  22929. var uvs = [];
  22930. var row, col;
  22931. for (row = 0; row <= subdivisions; row++) {
  22932. for (col = 0; col <= subdivisions; col++) {
  22933. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22934. // Compute height
  22935. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22936. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22937. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22938. var r = buffer[pos] / 255.0;
  22939. var g = buffer[pos + 1] / 255.0;
  22940. var b = buffer[pos + 2] / 255.0;
  22941. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22942. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22943. // Add vertex
  22944. positions.push(position.x, position.y, position.z);
  22945. normals.push(0, 0, 0);
  22946. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22947. }
  22948. }
  22949. for (row = 0; row < subdivisions; row++) {
  22950. for (col = 0; col < subdivisions; col++) {
  22951. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22952. indices.push(col + 1 + row * (subdivisions + 1));
  22953. indices.push(col + row * (subdivisions + 1));
  22954. indices.push(col + (row + 1) * (subdivisions + 1));
  22955. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22956. indices.push(col + row * (subdivisions + 1));
  22957. }
  22958. }
  22959. // Normals
  22960. VertexData.ComputeNormals(positions, indices, normals);
  22961. // Result
  22962. var vertexData = new VertexData();
  22963. vertexData.indices = indices;
  22964. vertexData.positions = positions;
  22965. vertexData.normals = normals;
  22966. vertexData.uvs = uvs;
  22967. return vertexData;
  22968. };
  22969. VertexData.CreatePlane = function (size, sideOrientation) {
  22970. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22971. var indices = [];
  22972. var positions = [];
  22973. var normals = [];
  22974. var uvs = [];
  22975. size = size || 1;
  22976. // Vertices
  22977. var halfSize = size / 2.0;
  22978. positions.push(-halfSize, -halfSize, 0);
  22979. normals.push(0, 0, -1.0);
  22980. uvs.push(0.0, 0.0);
  22981. positions.push(halfSize, -halfSize, 0);
  22982. normals.push(0, 0, -1.0);
  22983. uvs.push(1.0, 0.0);
  22984. positions.push(halfSize, halfSize, 0);
  22985. normals.push(0, 0, -1.0);
  22986. uvs.push(1.0, 1.0);
  22987. positions.push(-halfSize, halfSize, 0);
  22988. normals.push(0, 0, -1.0);
  22989. uvs.push(0.0, 1.0);
  22990. // Indices
  22991. indices.push(0);
  22992. indices.push(1);
  22993. indices.push(2);
  22994. indices.push(0);
  22995. indices.push(2);
  22996. indices.push(3);
  22997. // Sides
  22998. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22999. // Result
  23000. var vertexData = new VertexData();
  23001. vertexData.indices = indices;
  23002. vertexData.positions = positions;
  23003. vertexData.normals = normals;
  23004. vertexData.uvs = uvs;
  23005. return vertexData;
  23006. };
  23007. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  23008. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  23009. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23010. var indices = [];
  23011. var positions = [];
  23012. var normals = [];
  23013. var uvs = [];
  23014. radius = radius || 2;
  23015. tube = tube || 0.5;
  23016. radialSegments = radialSegments || 32;
  23017. tubularSegments = tubularSegments || 32;
  23018. p = p || 2;
  23019. q = q || 3;
  23020. // Helper
  23021. var getPos = function (angle) {
  23022. var cu = Math.cos(angle);
  23023. var su = Math.sin(angle);
  23024. var quOverP = q / p * angle;
  23025. var cs = Math.cos(quOverP);
  23026. var tx = radius * (2 + cs) * 0.5 * cu;
  23027. var ty = radius * (2 + cs) * su * 0.5;
  23028. var tz = radius * Math.sin(quOverP) * 0.5;
  23029. return new BABYLON.Vector3(tx, ty, tz);
  23030. };
  23031. for (var i = 0; i <= radialSegments; i++) {
  23032. var modI = i % radialSegments;
  23033. var u = modI / radialSegments * 2 * p * Math.PI;
  23034. var p1 = getPos(u);
  23035. var p2 = getPos(u + 0.01);
  23036. var tang = p2.subtract(p1);
  23037. var n = p2.add(p1);
  23038. var bitan = BABYLON.Vector3.Cross(tang, n);
  23039. n = BABYLON.Vector3.Cross(bitan, tang);
  23040. bitan.normalize();
  23041. n.normalize();
  23042. for (var j = 0; j < tubularSegments; j++) {
  23043. var modJ = j % tubularSegments;
  23044. var v = modJ / tubularSegments * 2 * Math.PI;
  23045. var cx = -tube * Math.cos(v);
  23046. var cy = tube * Math.sin(v);
  23047. positions.push(p1.x + cx * n.x + cy * bitan.x);
  23048. positions.push(p1.y + cx * n.y + cy * bitan.y);
  23049. positions.push(p1.z + cx * n.z + cy * bitan.z);
  23050. uvs.push(i / radialSegments);
  23051. uvs.push(j / tubularSegments);
  23052. }
  23053. }
  23054. for (i = 0; i < radialSegments; i++) {
  23055. for (j = 0; j < tubularSegments; j++) {
  23056. var jNext = (j + 1) % tubularSegments;
  23057. var a = i * tubularSegments + j;
  23058. var b = (i + 1) * tubularSegments + j;
  23059. var c = (i + 1) * tubularSegments + jNext;
  23060. var d = i * tubularSegments + jNext;
  23061. indices.push(d);
  23062. indices.push(b);
  23063. indices.push(a);
  23064. indices.push(d);
  23065. indices.push(c);
  23066. indices.push(b);
  23067. }
  23068. }
  23069. // Normals
  23070. VertexData.ComputeNormals(positions, indices, normals);
  23071. // Sides
  23072. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23073. // Result
  23074. var vertexData = new VertexData();
  23075. vertexData.indices = indices;
  23076. vertexData.positions = positions;
  23077. vertexData.normals = normals;
  23078. vertexData.uvs = uvs;
  23079. return vertexData;
  23080. };
  23081. // Tools
  23082. /**
  23083. * @param {any} - positions (number[] or Float32Array)
  23084. * @param {any} - indices (number[] or Uint16Array)
  23085. * @param {any} - normals (number[] or Float32Array)
  23086. */
  23087. VertexData.ComputeNormals = function (positions, indices, normals) {
  23088. var positionVectors = [];
  23089. var facesOfVertices = [];
  23090. var index;
  23091. for (index = 0; index < positions.length; index += 3) {
  23092. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  23093. positionVectors.push(vector3);
  23094. facesOfVertices.push([]);
  23095. }
  23096. // Compute normals
  23097. var facesNormals = [];
  23098. for (index = 0; index < indices.length / 3; index++) {
  23099. var i1 = indices[index * 3];
  23100. var i2 = indices[index * 3 + 1];
  23101. var i3 = indices[index * 3 + 2];
  23102. var p1 = positionVectors[i1];
  23103. var p2 = positionVectors[i2];
  23104. var p3 = positionVectors[i3];
  23105. var p1p2 = p1.subtract(p2);
  23106. var p3p2 = p3.subtract(p2);
  23107. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23108. facesOfVertices[i1].push(index);
  23109. facesOfVertices[i2].push(index);
  23110. facesOfVertices[i3].push(index);
  23111. }
  23112. for (index = 0; index < positionVectors.length; index++) {
  23113. var faces = facesOfVertices[index];
  23114. var normal = BABYLON.Vector3.Zero();
  23115. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  23116. normal.addInPlace(facesNormals[faces[faceIndex]]);
  23117. }
  23118. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  23119. normals[index * 3] = normal.x;
  23120. normals[index * 3 + 1] = normal.y;
  23121. normals[index * 3 + 2] = normal.z;
  23122. }
  23123. };
  23124. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  23125. var li = indices.length;
  23126. var ln = normals.length;
  23127. var i;
  23128. var n;
  23129. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23130. switch (sideOrientation) {
  23131. case BABYLON.Mesh.FRONTSIDE:
  23132. break;
  23133. case BABYLON.Mesh.BACKSIDE:
  23134. var tmp;
  23135. for (i = 0; i < li; i += 3) {
  23136. tmp = indices[i];
  23137. indices[i] = indices[i + 2];
  23138. indices[i + 2] = tmp;
  23139. }
  23140. for (n = 0; n < ln; n++) {
  23141. normals[n] = -normals[n];
  23142. }
  23143. break;
  23144. case BABYLON.Mesh.DOUBLESIDE:
  23145. // positions
  23146. var lp = positions.length;
  23147. var l = lp / 3;
  23148. for (var p = 0; p < lp; p++) {
  23149. positions[lp + p] = positions[p];
  23150. }
  23151. for (i = 0; i < li; i += 3) {
  23152. indices[i + li] = indices[i + 2] + l;
  23153. indices[i + 1 + li] = indices[i + 1] + l;
  23154. indices[i + 2 + li] = indices[i] + l;
  23155. }
  23156. for (n = 0; n < ln; n++) {
  23157. normals[ln + n] = -normals[n];
  23158. }
  23159. // uvs
  23160. var lu = uvs.length;
  23161. for (var u = 0; u < lu; u++) {
  23162. uvs[u + lu] = uvs[u];
  23163. }
  23164. break;
  23165. }
  23166. };
  23167. return VertexData;
  23168. })();
  23169. BABYLON.VertexData = VertexData;
  23170. })(BABYLON || (BABYLON = {}));
  23171. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  23172. var BABYLON;
  23173. (function (BABYLON) {
  23174. var buildCamera = function (that, name) {
  23175. that._leftCamera.isIntermediate = true;
  23176. that.subCameras.push(that._leftCamera);
  23177. that.subCameras.push(that._rightCamera);
  23178. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  23179. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  23180. that._anaglyphPostProcess.onApply = function (effect) {
  23181. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  23182. };
  23183. that._update();
  23184. };
  23185. var AnaglyphArcRotateCamera = (function (_super) {
  23186. __extends(AnaglyphArcRotateCamera, _super);
  23187. // ANY
  23188. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  23189. _super.call(this, name, alpha, beta, radius, target, scene);
  23190. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23191. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  23192. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  23193. buildCamera(this, name);
  23194. }
  23195. AnaglyphArcRotateCamera.prototype._update = function () {
  23196. this._updateCamera(this._leftCamera);
  23197. this._updateCamera(this._rightCamera);
  23198. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  23199. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  23200. _super.prototype._update.call(this);
  23201. };
  23202. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  23203. camera.beta = this.beta;
  23204. camera.radius = this.radius;
  23205. camera.minZ = this.minZ;
  23206. camera.maxZ = this.maxZ;
  23207. camera.fov = this.fov;
  23208. camera.target = this.target;
  23209. };
  23210. return AnaglyphArcRotateCamera;
  23211. })(BABYLON.ArcRotateCamera);
  23212. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  23213. var AnaglyphFreeCamera = (function (_super) {
  23214. __extends(AnaglyphFreeCamera, _super);
  23215. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  23216. _super.call(this, name, position, scene);
  23217. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23218. this._transformMatrix = new BABYLON.Matrix();
  23219. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  23220. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  23221. buildCamera(this, name);
  23222. }
  23223. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  23224. var target = this.getTarget();
  23225. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  23226. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  23227. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  23228. };
  23229. AnaglyphFreeCamera.prototype._update = function () {
  23230. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  23231. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  23232. this._updateCamera(this._leftCamera);
  23233. this._updateCamera(this._rightCamera);
  23234. _super.prototype._update.call(this);
  23235. };
  23236. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  23237. camera.minZ = this.minZ;
  23238. camera.maxZ = this.maxZ;
  23239. camera.fov = this.fov;
  23240. camera.viewport = this.viewport;
  23241. camera.setTarget(this.getTarget());
  23242. };
  23243. return AnaglyphFreeCamera;
  23244. })(BABYLON.FreeCamera);
  23245. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  23246. })(BABYLON || (BABYLON = {}));
  23247. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  23248. var BABYLON;
  23249. (function (BABYLON) {
  23250. var AnaglyphPostProcess = (function (_super) {
  23251. __extends(AnaglyphPostProcess, _super);
  23252. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23253. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  23254. }
  23255. return AnaglyphPostProcess;
  23256. })(BABYLON.PostProcess);
  23257. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  23258. })(BABYLON || (BABYLON = {}));
  23259. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  23260. (function (BABYLON) {
  23261. var Tags = (function () {
  23262. function Tags() {
  23263. }
  23264. Tags.EnableFor = function (obj) {
  23265. obj._tags = obj._tags || {};
  23266. obj.hasTags = function () {
  23267. return Tags.HasTags(obj);
  23268. };
  23269. obj.addTags = function (tagsString) {
  23270. return Tags.AddTagsTo(obj, tagsString);
  23271. };
  23272. obj.removeTags = function (tagsString) {
  23273. return Tags.RemoveTagsFrom(obj, tagsString);
  23274. };
  23275. obj.matchesTagsQuery = function (tagsQuery) {
  23276. return Tags.MatchesQuery(obj, tagsQuery);
  23277. };
  23278. };
  23279. Tags.DisableFor = function (obj) {
  23280. delete obj._tags;
  23281. delete obj.hasTags;
  23282. delete obj.addTags;
  23283. delete obj.removeTags;
  23284. delete obj.matchesTagsQuery;
  23285. };
  23286. Tags.HasTags = function (obj) {
  23287. if (!obj._tags) {
  23288. return false;
  23289. }
  23290. return !BABYLON.Tools.IsEmpty(obj._tags);
  23291. };
  23292. Tags.GetTags = function (obj) {
  23293. if (!obj._tags) {
  23294. return null;
  23295. }
  23296. return obj._tags;
  23297. };
  23298. // the tags 'true' and 'false' are reserved and cannot be used as tags
  23299. // a tag cannot start with '||', '&&', and '!'
  23300. // it cannot contain whitespaces
  23301. Tags.AddTagsTo = function (obj, tagsString) {
  23302. if (!tagsString) {
  23303. return;
  23304. }
  23305. var tags = tagsString.split(" ");
  23306. for (var t in tags) {
  23307. Tags._AddTagTo(obj, tags[t]);
  23308. }
  23309. };
  23310. Tags._AddTagTo = function (obj, tag) {
  23311. tag = tag.trim();
  23312. if (tag === "" || tag === "true" || tag === "false") {
  23313. return;
  23314. }
  23315. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  23316. return;
  23317. }
  23318. Tags.EnableFor(obj);
  23319. obj._tags[tag] = true;
  23320. };
  23321. Tags.RemoveTagsFrom = function (obj, tagsString) {
  23322. if (!Tags.HasTags(obj)) {
  23323. return;
  23324. }
  23325. var tags = tagsString.split(" ");
  23326. for (var t in tags) {
  23327. Tags._RemoveTagFrom(obj, tags[t]);
  23328. }
  23329. };
  23330. Tags._RemoveTagFrom = function (obj, tag) {
  23331. delete obj._tags[tag];
  23332. };
  23333. Tags.MatchesQuery = function (obj, tagsQuery) {
  23334. if (tagsQuery === undefined) {
  23335. return true;
  23336. }
  23337. if (tagsQuery === "") {
  23338. return Tags.HasTags(obj);
  23339. }
  23340. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  23341. };
  23342. return Tags;
  23343. })();
  23344. BABYLON.Tags = Tags;
  23345. })(BABYLON || (BABYLON = {}));
  23346. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  23347. (function (BABYLON) {
  23348. var Internals;
  23349. (function (Internals) {
  23350. var AndOrNotEvaluator = (function () {
  23351. function AndOrNotEvaluator() {
  23352. }
  23353. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  23354. if (!query.match(/\([^\(\)]*\)/g)) {
  23355. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  23356. }
  23357. else {
  23358. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  23359. // remove parenthesis
  23360. r = r.slice(1, r.length - 1);
  23361. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  23362. });
  23363. }
  23364. if (query === "true") {
  23365. return true;
  23366. }
  23367. if (query === "false") {
  23368. return false;
  23369. }
  23370. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  23371. };
  23372. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  23373. evaluateCallback = evaluateCallback || (function (r) {
  23374. return r === "true" ? true : false;
  23375. });
  23376. var result;
  23377. var or = parenthesisContent.split("||");
  23378. for (var i in or) {
  23379. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  23380. var and = ori.split("&&");
  23381. if (and.length > 1) {
  23382. for (var j = 0; j < and.length; ++j) {
  23383. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  23384. if (andj !== "true" && andj !== "false") {
  23385. if (andj[0] === "!") {
  23386. result = !evaluateCallback(andj.substring(1));
  23387. }
  23388. else {
  23389. result = evaluateCallback(andj);
  23390. }
  23391. }
  23392. else {
  23393. result = andj === "true" ? true : false;
  23394. }
  23395. if (!result) {
  23396. ori = "false";
  23397. break;
  23398. }
  23399. }
  23400. }
  23401. if (result || ori === "true") {
  23402. result = true;
  23403. break;
  23404. }
  23405. // result equals false (or undefined)
  23406. if (ori !== "true" && ori !== "false") {
  23407. if (ori[0] === "!") {
  23408. result = !evaluateCallback(ori.substring(1));
  23409. }
  23410. else {
  23411. result = evaluateCallback(ori);
  23412. }
  23413. }
  23414. else {
  23415. result = ori === "true" ? true : false;
  23416. }
  23417. }
  23418. // the whole parenthesis scope is replaced by 'true' or 'false'
  23419. return result ? "true" : "false";
  23420. };
  23421. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  23422. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  23423. // remove whitespaces
  23424. r = r.replace(/[\s]/g, function () { return ""; });
  23425. return r.length % 2 ? "!" : "";
  23426. });
  23427. booleanString = booleanString.trim();
  23428. if (booleanString === "!true") {
  23429. booleanString = "false";
  23430. }
  23431. else if (booleanString === "!false") {
  23432. booleanString = "true";
  23433. }
  23434. return booleanString;
  23435. };
  23436. return AndOrNotEvaluator;
  23437. })();
  23438. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  23439. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23440. })(BABYLON || (BABYLON = {}));
  23441. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  23442. (function (BABYLON) {
  23443. var PostProcessRenderPass = (function () {
  23444. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  23445. this._enabled = true;
  23446. this._refCount = 0;
  23447. this._name = name;
  23448. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  23449. this.setRenderList(renderList);
  23450. this._renderTexture.onBeforeRender = beforeRender;
  23451. this._renderTexture.onAfterRender = afterRender;
  23452. this._scene = scene;
  23453. this._renderList = renderList;
  23454. }
  23455. // private
  23456. PostProcessRenderPass.prototype._incRefCount = function () {
  23457. if (this._refCount === 0) {
  23458. this._scene.customRenderTargets.push(this._renderTexture);
  23459. }
  23460. return ++this._refCount;
  23461. };
  23462. PostProcessRenderPass.prototype._decRefCount = function () {
  23463. this._refCount--;
  23464. if (this._refCount <= 0) {
  23465. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  23466. }
  23467. return this._refCount;
  23468. };
  23469. PostProcessRenderPass.prototype._update = function () {
  23470. this.setRenderList(this._renderList);
  23471. };
  23472. // public
  23473. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23474. this._renderTexture.renderList = renderList;
  23475. };
  23476. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23477. return this._renderTexture;
  23478. };
  23479. return PostProcessRenderPass;
  23480. })();
  23481. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23482. })(BABYLON || (BABYLON = {}));
  23483. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23484. (function (BABYLON) {
  23485. var PostProcessRenderEffect = (function () {
  23486. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23487. this._engine = engine;
  23488. this._name = name;
  23489. this._singleInstance = singleInstance || true;
  23490. this._getPostProcess = getPostProcess;
  23491. this._cameras = [];
  23492. this._indicesForCamera = [];
  23493. this._postProcesses = {};
  23494. this._renderPasses = {};
  23495. this._renderEffectAsPasses = {};
  23496. }
  23497. PostProcessRenderEffect.prototype._update = function () {
  23498. for (var renderPassName in this._renderPasses) {
  23499. this._renderPasses[renderPassName]._update();
  23500. }
  23501. };
  23502. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23503. this._renderPasses[renderPass._name] = renderPass;
  23504. this._linkParameters();
  23505. };
  23506. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23507. delete this._renderPasses[renderPass._name];
  23508. this._linkParameters();
  23509. };
  23510. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23511. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23512. this._linkParameters();
  23513. };
  23514. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23515. for (var renderPassName in this._renderPasses) {
  23516. if (renderPassName === passName) {
  23517. return this._renderPasses[passName];
  23518. }
  23519. }
  23520. };
  23521. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23522. this._renderPasses = {};
  23523. this._linkParameters();
  23524. };
  23525. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23526. var cameraKey;
  23527. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23528. for (var i = 0; i < _cam.length; i++) {
  23529. var camera = _cam[i];
  23530. var cameraName = camera.name;
  23531. if (this._singleInstance) {
  23532. cameraKey = 0;
  23533. }
  23534. else {
  23535. cameraKey = cameraName;
  23536. }
  23537. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23538. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23539. if (!this._indicesForCamera[cameraName]) {
  23540. this._indicesForCamera[cameraName] = [];
  23541. }
  23542. this._indicesForCamera[cameraName].push(index);
  23543. if (this._cameras.indexOf(camera) === -1) {
  23544. this._cameras[cameraName] = camera;
  23545. }
  23546. for (var passName in this._renderPasses) {
  23547. this._renderPasses[passName]._incRefCount();
  23548. }
  23549. }
  23550. this._linkParameters();
  23551. };
  23552. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23553. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23554. for (var i = 0; i < _cam.length; i++) {
  23555. var camera = _cam[i];
  23556. var cameraName = camera.name;
  23557. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23558. var index = this._cameras.indexOf(cameraName);
  23559. this._indicesForCamera.splice(index, 1);
  23560. this._cameras.splice(index, 1);
  23561. for (var passName in this._renderPasses) {
  23562. this._renderPasses[passName]._decRefCount();
  23563. }
  23564. }
  23565. };
  23566. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23567. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23568. for (var i = 0; i < _cam.length; i++) {
  23569. var camera = _cam[i];
  23570. var cameraName = camera.name;
  23571. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23572. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23573. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23574. }
  23575. }
  23576. for (var passName in this._renderPasses) {
  23577. this._renderPasses[passName]._incRefCount();
  23578. }
  23579. }
  23580. };
  23581. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23582. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23583. for (var i = 0; i < _cam.length; i++) {
  23584. var camera = _cam[i];
  23585. var cameraName = camera.Name;
  23586. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23587. for (var passName in this._renderPasses) {
  23588. this._renderPasses[passName]._decRefCount();
  23589. }
  23590. }
  23591. };
  23592. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23593. if (this._singleInstance) {
  23594. return this._postProcesses[0];
  23595. }
  23596. else {
  23597. return this._postProcesses[camera.name];
  23598. }
  23599. };
  23600. PostProcessRenderEffect.prototype._linkParameters = function () {
  23601. var _this = this;
  23602. for (var index in this._postProcesses) {
  23603. if (this.applyParameters) {
  23604. this.applyParameters(this._postProcesses[index]);
  23605. }
  23606. this._postProcesses[index].onBeforeRender = function (effect) {
  23607. _this._linkTextures(effect);
  23608. };
  23609. }
  23610. };
  23611. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23612. for (var renderPassName in this._renderPasses) {
  23613. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23614. }
  23615. for (var renderEffectName in this._renderEffectAsPasses) {
  23616. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23617. }
  23618. };
  23619. return PostProcessRenderEffect;
  23620. })();
  23621. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23622. })(BABYLON || (BABYLON = {}));
  23623. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23624. (function (BABYLON) {
  23625. var PostProcessRenderPipeline = (function () {
  23626. function PostProcessRenderPipeline(engine, name) {
  23627. this._engine = engine;
  23628. this._name = name;
  23629. this._renderEffects = {};
  23630. this._renderEffectsForIsolatedPass = {};
  23631. this._cameras = [];
  23632. }
  23633. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23634. this._renderEffects[renderEffect._name] = renderEffect;
  23635. };
  23636. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23637. var renderEffects = this._renderEffects[renderEffectName];
  23638. if (!renderEffects) {
  23639. return;
  23640. }
  23641. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23642. };
  23643. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23644. var renderEffects = this._renderEffects[renderEffectName];
  23645. if (!renderEffects) {
  23646. return;
  23647. }
  23648. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23649. };
  23650. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23651. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23652. var indicesToDelete = [];
  23653. for (var i = 0; i < _cam.length; i++) {
  23654. var camera = _cam[i];
  23655. var cameraName = camera.name;
  23656. if (this._cameras.indexOf(camera) === -1) {
  23657. this._cameras[cameraName] = camera;
  23658. }
  23659. else if (unique) {
  23660. indicesToDelete.push(i);
  23661. }
  23662. }
  23663. for (var i = 0; i < indicesToDelete.length; i++) {
  23664. cameras.splice(indicesToDelete[i], 1);
  23665. }
  23666. for (var renderEffectName in this._renderEffects) {
  23667. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23668. }
  23669. };
  23670. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23671. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23672. for (var renderEffectName in this._renderEffects) {
  23673. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23674. }
  23675. for (var i = 0; i < _cam.length; i++) {
  23676. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23677. }
  23678. };
  23679. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23680. var _this = this;
  23681. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23682. var pass = null;
  23683. for (var renderEffectName in this._renderEffects) {
  23684. pass = this._renderEffects[renderEffectName].getPass(passName);
  23685. if (pass != null) {
  23686. break;
  23687. }
  23688. }
  23689. if (pass === null) {
  23690. return;
  23691. }
  23692. for (var renderEffectName in this._renderEffects) {
  23693. this._renderEffects[renderEffectName]._disable(_cam);
  23694. }
  23695. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23696. for (var i = 0; i < _cam.length; i++) {
  23697. var camera = _cam[i];
  23698. var cameraName = camera.name;
  23699. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23700. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23701. });
  23702. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23703. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23704. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23705. }
  23706. };
  23707. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23708. var _this = this;
  23709. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23710. for (var i = 0; i < _cam.length; i++) {
  23711. var camera = _cam[i];
  23712. var cameraName = camera.name;
  23713. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23714. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23715. });
  23716. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23717. }
  23718. for (var renderEffectName in this._renderEffects) {
  23719. this._renderEffects[renderEffectName]._enable(_cam);
  23720. }
  23721. };
  23722. PostProcessRenderPipeline.prototype._update = function () {
  23723. for (var renderEffectName in this._renderEffects) {
  23724. this._renderEffects[renderEffectName]._update();
  23725. }
  23726. for (var i = 0; i < this._cameras.length; i++) {
  23727. var cameraName = this._cameras[i].name;
  23728. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23729. this._renderEffectsForIsolatedPass[cameraName]._update();
  23730. }
  23731. }
  23732. };
  23733. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23734. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23735. return PostProcessRenderPipeline;
  23736. })();
  23737. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23738. })(BABYLON || (BABYLON = {}));
  23739. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23740. (function (BABYLON) {
  23741. var PostProcessRenderPipelineManager = (function () {
  23742. function PostProcessRenderPipelineManager() {
  23743. this._renderPipelines = {};
  23744. }
  23745. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23746. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23747. };
  23748. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23749. var renderPipeline = this._renderPipelines[renderPipelineName];
  23750. if (!renderPipeline) {
  23751. return;
  23752. }
  23753. renderPipeline._attachCameras(cameras, unique);
  23754. };
  23755. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23756. var renderPipeline = this._renderPipelines[renderPipelineName];
  23757. if (!renderPipeline) {
  23758. return;
  23759. }
  23760. renderPipeline._detachCameras(cameras);
  23761. };
  23762. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23763. var renderPipeline = this._renderPipelines[renderPipelineName];
  23764. if (!renderPipeline) {
  23765. return;
  23766. }
  23767. renderPipeline._enableEffect(renderEffectName, cameras);
  23768. };
  23769. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23770. var renderPipeline = this._renderPipelines[renderPipelineName];
  23771. if (!renderPipeline) {
  23772. return;
  23773. }
  23774. renderPipeline._disableEffect(renderEffectName, cameras);
  23775. };
  23776. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23777. var renderPipeline = this._renderPipelines[renderPipelineName];
  23778. if (!renderPipeline) {
  23779. return;
  23780. }
  23781. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23782. };
  23783. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23784. var renderPipeline = this._renderPipelines[renderPipelineName];
  23785. if (!renderPipeline) {
  23786. return;
  23787. }
  23788. renderPipeline._disableDisplayOnlyPass(cameras);
  23789. };
  23790. PostProcessRenderPipelineManager.prototype.update = function () {
  23791. for (var renderPipelineName in this._renderPipelines) {
  23792. this._renderPipelines[renderPipelineName]._update();
  23793. }
  23794. };
  23795. return PostProcessRenderPipelineManager;
  23796. })();
  23797. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23798. })(BABYLON || (BABYLON = {}));
  23799. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23800. var BABYLON;
  23801. (function (BABYLON) {
  23802. var DisplayPassPostProcess = (function (_super) {
  23803. __extends(DisplayPassPostProcess, _super);
  23804. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23805. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23806. }
  23807. return DisplayPassPostProcess;
  23808. })(BABYLON.PostProcess);
  23809. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23810. })(BABYLON || (BABYLON = {}));
  23811. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23812. (function (BABYLON) {
  23813. var BoundingBoxRenderer = (function () {
  23814. function BoundingBoxRenderer(scene) {
  23815. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23816. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23817. this.showBackLines = true;
  23818. this.renderList = new BABYLON.SmartArray(32);
  23819. this._scene = scene;
  23820. }
  23821. BoundingBoxRenderer.prototype._prepareRessources = function () {
  23822. if (this._colorShader) {
  23823. return;
  23824. }
  23825. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  23826. attributes: ["position"],
  23827. uniforms: ["worldViewProjection", "color"]
  23828. });
  23829. var engine = this._scene.getEngine();
  23830. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23831. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23832. 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]);
  23833. };
  23834. BoundingBoxRenderer.prototype.reset = function () {
  23835. this.renderList.reset();
  23836. };
  23837. BoundingBoxRenderer.prototype.render = function () {
  23838. if (this.renderList.length === 0) {
  23839. return;
  23840. }
  23841. this._prepareRessources();
  23842. if (!this._colorShader.isReady()) {
  23843. return;
  23844. }
  23845. var engine = this._scene.getEngine();
  23846. engine.setDepthWrite(false);
  23847. this._colorShader._preBind();
  23848. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23849. var boundingBox = this.renderList.data[boundingBoxIndex];
  23850. var min = boundingBox.minimum;
  23851. var max = boundingBox.maximum;
  23852. var diff = max.subtract(min);
  23853. var median = min.add(diff.scale(0.5));
  23854. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23855. // VBOs
  23856. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23857. if (this.showBackLines) {
  23858. // Back
  23859. engine.setDepthFunctionToGreaterOrEqual();
  23860. this._scene.resetCachedMaterial();
  23861. this._colorShader.setColor4("color", this.backColor.toColor4());
  23862. this._colorShader.bind(worldMatrix);
  23863. // Draw order
  23864. engine.draw(false, 0, 24);
  23865. }
  23866. // Front
  23867. engine.setDepthFunctionToLess();
  23868. this._scene.resetCachedMaterial();
  23869. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23870. this._colorShader.bind(worldMatrix);
  23871. // Draw order
  23872. engine.draw(false, 0, 24);
  23873. }
  23874. this._colorShader.unbind();
  23875. engine.setDepthFunctionToLessOrEqual();
  23876. engine.setDepthWrite(true);
  23877. };
  23878. BoundingBoxRenderer.prototype.dispose = function () {
  23879. if (!this._colorShader) {
  23880. return;
  23881. }
  23882. this._colorShader.dispose();
  23883. this._vb.dispose();
  23884. this._scene.getEngine()._releaseBuffer(this._ib);
  23885. };
  23886. return BoundingBoxRenderer;
  23887. })();
  23888. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23889. })(BABYLON || (BABYLON = {}));
  23890. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23891. (function (BABYLON) {
  23892. var Internals;
  23893. (function (Internals) {
  23894. /*
  23895. * Based on jsTGALoader - Javascript loader for TGA file
  23896. * By Vincent Thibault
  23897. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23898. */
  23899. var TGATools = (function () {
  23900. function TGATools() {
  23901. }
  23902. TGATools.GetTGAHeader = function (data) {
  23903. var offset = 0;
  23904. var header = {
  23905. id_length: data[offset++],
  23906. colormap_type: data[offset++],
  23907. image_type: data[offset++],
  23908. colormap_index: data[offset++] | data[offset++] << 8,
  23909. colormap_length: data[offset++] | data[offset++] << 8,
  23910. colormap_size: data[offset++],
  23911. origin: [
  23912. data[offset++] | data[offset++] << 8,
  23913. data[offset++] | data[offset++] << 8
  23914. ],
  23915. width: data[offset++] | data[offset++] << 8,
  23916. height: data[offset++] | data[offset++] << 8,
  23917. pixel_size: data[offset++],
  23918. flags: data[offset++]
  23919. };
  23920. return header;
  23921. };
  23922. TGATools.UploadContent = function (gl, data) {
  23923. // Not enough data to contain header ?
  23924. if (data.length < 19) {
  23925. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23926. return;
  23927. }
  23928. // Read Header
  23929. var offset = 18;
  23930. var header = TGATools.GetTGAHeader(data);
  23931. // Assume it's a valid Targa file.
  23932. if (header.id_length + offset > data.length) {
  23933. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23934. return;
  23935. }
  23936. // Skip not needed data
  23937. offset += header.id_length;
  23938. var use_rle = false;
  23939. var use_pal = false;
  23940. var use_rgb = false;
  23941. var use_grey = false;
  23942. switch (header.image_type) {
  23943. case TGATools._TYPE_RLE_INDEXED:
  23944. use_rle = true;
  23945. case TGATools._TYPE_INDEXED:
  23946. use_pal = true;
  23947. break;
  23948. case TGATools._TYPE_RLE_RGB:
  23949. use_rle = true;
  23950. case TGATools._TYPE_RGB:
  23951. use_rgb = true;
  23952. break;
  23953. case TGATools._TYPE_RLE_GREY:
  23954. use_rle = true;
  23955. case TGATools._TYPE_GREY:
  23956. use_grey = true;
  23957. break;
  23958. }
  23959. var pixel_data;
  23960. var numAlphaBits = header.flags & 0xf;
  23961. var pixel_size = header.pixel_size >> 3;
  23962. var pixel_total = header.width * header.height * pixel_size;
  23963. // Read palettes
  23964. var palettes;
  23965. if (use_pal) {
  23966. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23967. }
  23968. // Read LRE
  23969. if (use_rle) {
  23970. pixel_data = new Uint8Array(pixel_total);
  23971. var c, count, i;
  23972. var localOffset = 0;
  23973. var pixels = new Uint8Array(pixel_size);
  23974. while (offset < pixel_total && localOffset < pixel_total) {
  23975. c = data[offset++];
  23976. count = (c & 0x7f) + 1;
  23977. // RLE pixels
  23978. if (c & 0x80) {
  23979. for (i = 0; i < pixel_size; ++i) {
  23980. pixels[i] = data[offset++];
  23981. }
  23982. for (i = 0; i < count; ++i) {
  23983. pixel_data.set(pixels, localOffset + i * pixel_size);
  23984. }
  23985. localOffset += pixel_size * count;
  23986. }
  23987. else {
  23988. count *= pixel_size;
  23989. for (i = 0; i < count; ++i) {
  23990. pixel_data[localOffset + i] = data[offset++];
  23991. }
  23992. localOffset += count;
  23993. }
  23994. }
  23995. }
  23996. else {
  23997. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23998. }
  23999. // Load to texture
  24000. var x_start, y_start, x_step, y_step, y_end, x_end;
  24001. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  24002. default:
  24003. case TGATools._ORIGIN_UL:
  24004. x_start = 0;
  24005. x_step = 1;
  24006. x_end = header.width;
  24007. y_start = 0;
  24008. y_step = 1;
  24009. y_end = header.height;
  24010. break;
  24011. case TGATools._ORIGIN_BL:
  24012. x_start = 0;
  24013. x_step = 1;
  24014. x_end = header.width;
  24015. y_start = header.height - 1;
  24016. y_step = -1;
  24017. y_end = -1;
  24018. break;
  24019. case TGATools._ORIGIN_UR:
  24020. x_start = header.width - 1;
  24021. x_step = -1;
  24022. x_end = -1;
  24023. y_start = 0;
  24024. y_step = 1;
  24025. y_end = header.height;
  24026. break;
  24027. case TGATools._ORIGIN_BR:
  24028. x_start = header.width - 1;
  24029. x_step = -1;
  24030. x_end = -1;
  24031. y_start = header.height - 1;
  24032. y_step = -1;
  24033. y_end = -1;
  24034. break;
  24035. }
  24036. // Load the specify method
  24037. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  24038. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  24039. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  24040. };
  24041. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24042. var image = pixel_data, colormap = palettes;
  24043. var width = header.width, height = header.height;
  24044. var color, i = 0, x, y;
  24045. var imageData = new Uint8Array(width * height * 4);
  24046. for (y = y_start; y !== y_end; y += y_step) {
  24047. for (x = x_start; x !== x_end; x += x_step, i++) {
  24048. color = image[i];
  24049. imageData[(x + width * y) * 4 + 3] = 255;
  24050. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  24051. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  24052. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  24053. }
  24054. }
  24055. return imageData;
  24056. };
  24057. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24058. var image = pixel_data;
  24059. var width = header.width, height = header.height;
  24060. var color, i = 0, x, y;
  24061. var imageData = new Uint8Array(width * height * 4);
  24062. for (y = y_start; y !== y_end; y += y_step) {
  24063. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24064. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  24065. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  24066. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  24067. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  24068. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  24069. }
  24070. }
  24071. return imageData;
  24072. };
  24073. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24074. var image = pixel_data;
  24075. var width = header.width, height = header.height;
  24076. var i = 0, x, y;
  24077. var imageData = new Uint8Array(width * height * 4);
  24078. for (y = y_start; y !== y_end; y += y_step) {
  24079. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  24080. imageData[(x + width * y) * 4 + 3] = 255;
  24081. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24082. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24083. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24084. }
  24085. }
  24086. return imageData;
  24087. };
  24088. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24089. var image = pixel_data;
  24090. var width = header.width, height = header.height;
  24091. var i = 0, x, y;
  24092. var imageData = new Uint8Array(width * height * 4);
  24093. for (y = y_start; y !== y_end; y += y_step) {
  24094. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  24095. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24096. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24097. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24098. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  24099. }
  24100. }
  24101. return imageData;
  24102. };
  24103. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24104. var image = pixel_data;
  24105. var width = header.width, height = header.height;
  24106. var color, i = 0, x, y;
  24107. var imageData = new Uint8Array(width * height * 4);
  24108. for (y = y_start; y !== y_end; y += y_step) {
  24109. for (x = x_start; x !== x_end; x += x_step, i++) {
  24110. color = image[i];
  24111. imageData[(x + width * y) * 4 + 0] = color;
  24112. imageData[(x + width * y) * 4 + 1] = color;
  24113. imageData[(x + width * y) * 4 + 2] = color;
  24114. imageData[(x + width * y) * 4 + 3] = 255;
  24115. }
  24116. }
  24117. return imageData;
  24118. };
  24119. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24120. var image = pixel_data;
  24121. var width = header.width, height = header.height;
  24122. var i = 0, x, y;
  24123. var imageData = new Uint8Array(width * height * 4);
  24124. for (y = y_start; y !== y_end; y += y_step) {
  24125. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24126. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  24127. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  24128. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24129. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  24130. }
  24131. }
  24132. return imageData;
  24133. };
  24134. TGATools._TYPE_NO_DATA = 0;
  24135. TGATools._TYPE_INDEXED = 1;
  24136. TGATools._TYPE_RGB = 2;
  24137. TGATools._TYPE_GREY = 3;
  24138. TGATools._TYPE_RLE_INDEXED = 9;
  24139. TGATools._TYPE_RLE_RGB = 10;
  24140. TGATools._TYPE_RLE_GREY = 11;
  24141. TGATools._ORIGIN_MASK = 0x30;
  24142. TGATools._ORIGIN_SHIFT = 0x04;
  24143. TGATools._ORIGIN_BL = 0x00;
  24144. TGATools._ORIGIN_BR = 0x01;
  24145. TGATools._ORIGIN_UL = 0x02;
  24146. TGATools._ORIGIN_UR = 0x03;
  24147. return TGATools;
  24148. })();
  24149. Internals.TGATools = TGATools;
  24150. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24151. })(BABYLON || (BABYLON = {}));
  24152. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  24153. (function (BABYLON) {
  24154. var Internals;
  24155. (function (Internals) {
  24156. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  24157. // All values and structures referenced from:
  24158. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  24159. var DDS_MAGIC = 0x20534444;
  24160. 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;
  24161. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  24162. 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;
  24163. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  24164. function FourCCToInt32(value) {
  24165. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  24166. }
  24167. function Int32ToFourCC(value) {
  24168. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  24169. }
  24170. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  24171. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  24172. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  24173. var headerLengthInt = 31; // The header length in 32 bit ints
  24174. // Offsets into the header array
  24175. var off_magic = 0;
  24176. var off_size = 1;
  24177. var off_flags = 2;
  24178. var off_height = 3;
  24179. var off_width = 4;
  24180. var off_mipmapCount = 7;
  24181. var off_pfFlags = 20;
  24182. var off_pfFourCC = 21;
  24183. var off_RGBbpp = 22;
  24184. var off_RMask = 23;
  24185. var off_GMask = 24;
  24186. var off_BMask = 25;
  24187. var off_AMask = 26;
  24188. var off_caps1 = 27;
  24189. var off_caps2 = 28;
  24190. ;
  24191. var DDSTools = (function () {
  24192. function DDSTools() {
  24193. }
  24194. DDSTools.GetDDSInfo = function (arrayBuffer) {
  24195. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  24196. var mipmapCount = 1;
  24197. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  24198. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24199. }
  24200. return {
  24201. width: header[off_width],
  24202. height: header[off_height],
  24203. mipmapCount: mipmapCount,
  24204. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  24205. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  24206. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  24207. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  24208. };
  24209. };
  24210. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24211. var byteArray = new Uint8Array(dataLength);
  24212. var srcData = new Uint8Array(arrayBuffer);
  24213. var index = 0;
  24214. for (var y = height - 1; y >= 0; y--) {
  24215. for (var x = 0; x < width; x++) {
  24216. var srcPos = dataOffset + (x + y * width) * 4;
  24217. byteArray[index + 2] = srcData[srcPos];
  24218. byteArray[index + 1] = srcData[srcPos + 1];
  24219. byteArray[index] = srcData[srcPos + 2];
  24220. byteArray[index + 3] = srcData[srcPos + 3];
  24221. index += 4;
  24222. }
  24223. }
  24224. return byteArray;
  24225. };
  24226. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24227. var byteArray = new Uint8Array(dataLength);
  24228. var srcData = new Uint8Array(arrayBuffer);
  24229. var index = 0;
  24230. for (var y = height - 1; y >= 0; y--) {
  24231. for (var x = 0; x < width; x++) {
  24232. var srcPos = dataOffset + (x + y * width) * 3;
  24233. byteArray[index + 2] = srcData[srcPos];
  24234. byteArray[index + 1] = srcData[srcPos + 1];
  24235. byteArray[index] = srcData[srcPos + 2];
  24236. index += 3;
  24237. }
  24238. }
  24239. return byteArray;
  24240. };
  24241. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24242. var byteArray = new Uint8Array(dataLength);
  24243. var srcData = new Uint8Array(arrayBuffer);
  24244. var index = 0;
  24245. for (var y = height - 1; y >= 0; y--) {
  24246. for (var x = 0; x < width; x++) {
  24247. var srcPos = dataOffset + (x + y * width);
  24248. byteArray[index] = srcData[srcPos];
  24249. index++;
  24250. }
  24251. }
  24252. return byteArray;
  24253. };
  24254. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  24255. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  24256. if (header[off_magic] != DDS_MAGIC) {
  24257. BABYLON.Tools.Error("Invalid magic number in DDS header");
  24258. return;
  24259. }
  24260. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  24261. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  24262. return;
  24263. }
  24264. if (info.isFourCC) {
  24265. fourCC = header[off_pfFourCC];
  24266. switch (fourCC) {
  24267. case FOURCC_DXT1:
  24268. blockBytes = 8;
  24269. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24270. break;
  24271. case FOURCC_DXT3:
  24272. blockBytes = 16;
  24273. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24274. break;
  24275. case FOURCC_DXT5:
  24276. blockBytes = 16;
  24277. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24278. break;
  24279. default:
  24280. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  24281. return;
  24282. }
  24283. }
  24284. mipmapCount = 1;
  24285. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  24286. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24287. }
  24288. var bpp = header[off_RGBbpp];
  24289. for (var face = 0; face < faces; face++) {
  24290. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  24291. width = header[off_width];
  24292. height = header[off_height];
  24293. dataOffset = header[off_size] + 4;
  24294. for (i = 0; i < mipmapCount; ++i) {
  24295. if (info.isRGB) {
  24296. if (bpp == 24) {
  24297. dataLength = width * height * 3;
  24298. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24299. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  24300. }
  24301. else {
  24302. dataLength = width * height * 4;
  24303. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24304. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  24305. }
  24306. }
  24307. else if (info.isLuminance) {
  24308. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  24309. var unpaddedRowSize = width;
  24310. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  24311. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  24312. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24313. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  24314. }
  24315. else {
  24316. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  24317. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  24318. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  24319. }
  24320. dataOffset += dataLength;
  24321. width *= 0.5;
  24322. height *= 0.5;
  24323. width = Math.max(1.0, width);
  24324. height = Math.max(1.0, height);
  24325. }
  24326. }
  24327. };
  24328. return DDSTools;
  24329. })();
  24330. Internals.DDSTools = DDSTools;
  24331. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24332. })(BABYLON || (BABYLON = {}));
  24333. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  24334. (function (BABYLON) {
  24335. var SmartArray = (function () {
  24336. function SmartArray(capacity) {
  24337. this.length = 0;
  24338. this._duplicateId = 0;
  24339. this.data = new Array(capacity);
  24340. this._id = SmartArray._GlobalId++;
  24341. }
  24342. SmartArray.prototype.push = function (value) {
  24343. this.data[this.length++] = value;
  24344. if (this.length > this.data.length) {
  24345. this.data.length *= 2;
  24346. }
  24347. if (!value.__smartArrayFlags) {
  24348. value.__smartArrayFlags = {};
  24349. }
  24350. value.__smartArrayFlags[this._id] = this._duplicateId;
  24351. };
  24352. SmartArray.prototype.pushNoDuplicate = function (value) {
  24353. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  24354. return;
  24355. }
  24356. this.push(value);
  24357. };
  24358. SmartArray.prototype.sort = function (compareFn) {
  24359. this.data.sort(compareFn);
  24360. };
  24361. SmartArray.prototype.reset = function () {
  24362. this.length = 0;
  24363. this._duplicateId++;
  24364. };
  24365. SmartArray.prototype.concat = function (array) {
  24366. if (array.length === 0) {
  24367. return;
  24368. }
  24369. if (this.length + array.length > this.data.length) {
  24370. this.data.length = (this.length + array.length) * 2;
  24371. }
  24372. for (var index = 0; index < array.length; index++) {
  24373. this.data[this.length++] = (array.data || array)[index];
  24374. }
  24375. };
  24376. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  24377. if (array.length === 0) {
  24378. return;
  24379. }
  24380. if (this.length + array.length > this.data.length) {
  24381. this.data.length = (this.length + array.length) * 2;
  24382. }
  24383. for (var index = 0; index < array.length; index++) {
  24384. var item = (array.data || array)[index];
  24385. this.pushNoDuplicate(item);
  24386. }
  24387. };
  24388. SmartArray.prototype.indexOf = function (value) {
  24389. var position = this.data.indexOf(value);
  24390. if (position >= this.length) {
  24391. return -1;
  24392. }
  24393. return position;
  24394. };
  24395. // Statics
  24396. SmartArray._GlobalId = 0;
  24397. return SmartArray;
  24398. })();
  24399. BABYLON.SmartArray = SmartArray;
  24400. })(BABYLON || (BABYLON = {}));
  24401. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  24402. (function (BABYLON) {
  24403. var CannonJSPlugin = (function () {
  24404. function CannonJSPlugin() {
  24405. this._registeredMeshes = [];
  24406. this._physicsMaterials = [];
  24407. this.updateBodyPosition = function (mesh) {
  24408. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24409. var registeredMesh = this._registeredMeshes[index];
  24410. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24411. var body = registeredMesh.body;
  24412. var center = mesh.getBoundingInfo().boundingBox.center;
  24413. body.position.set(center.x, center.z, center.y);
  24414. body.quaternion.x = mesh.rotationQuaternion.x;
  24415. body.quaternion.z = mesh.rotationQuaternion.y;
  24416. body.quaternion.y = mesh.rotationQuaternion.z;
  24417. body.quaternion.w = -mesh.rotationQuaternion.w;
  24418. return;
  24419. }
  24420. }
  24421. };
  24422. }
  24423. CannonJSPlugin.prototype.initialize = function (iterations) {
  24424. if (iterations === void 0) { iterations = 10; }
  24425. this._world = new CANNON.World();
  24426. this._world.broadphase = new CANNON.NaiveBroadphase();
  24427. this._world.solver.iterations = iterations;
  24428. };
  24429. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  24430. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24431. };
  24432. CannonJSPlugin.prototype.runOneStep = function (delta) {
  24433. this._world.step(delta);
  24434. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24435. var registeredMesh = this._registeredMeshes[index];
  24436. if (registeredMesh.isChild) {
  24437. continue;
  24438. }
  24439. // Body position
  24440. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  24441. var deltaPos = registeredMesh.delta;
  24442. if (deltaPos) {
  24443. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  24444. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  24445. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  24446. }
  24447. else {
  24448. registeredMesh.mesh.position.x = bodyX;
  24449. registeredMesh.mesh.position.y = bodyZ;
  24450. registeredMesh.mesh.position.z = bodyY;
  24451. }
  24452. if (!registeredMesh.mesh.rotationQuaternion) {
  24453. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24454. }
  24455. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  24456. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  24457. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  24458. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  24459. }
  24460. };
  24461. CannonJSPlugin.prototype.setGravity = function (gravity) {
  24462. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  24463. };
  24464. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24465. this.unregisterMesh(mesh);
  24466. mesh.computeWorldMatrix(true);
  24467. switch (impostor) {
  24468. case BABYLON.PhysicsEngine.SphereImpostor:
  24469. var bbox = mesh.getBoundingInfo().boundingBox;
  24470. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24471. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24472. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24473. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24474. case BABYLON.PhysicsEngine.BoxImpostor:
  24475. bbox = mesh.getBoundingInfo().boundingBox;
  24476. var min = bbox.minimumWorld;
  24477. var max = bbox.maximumWorld;
  24478. var box = max.subtract(min).scale(0.5);
  24479. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24480. case BABYLON.PhysicsEngine.PlaneImpostor:
  24481. return this._createPlane(mesh, options);
  24482. case BABYLON.PhysicsEngine.MeshImpostor:
  24483. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24484. var rawFaces = mesh.getIndices();
  24485. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24486. }
  24487. return null;
  24488. };
  24489. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24490. var shape = new CANNON.Sphere(radius);
  24491. if (!options) {
  24492. return shape;
  24493. }
  24494. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24495. };
  24496. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24497. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24498. if (!options) {
  24499. return shape;
  24500. }
  24501. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24502. };
  24503. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24504. var shape = new CANNON.Plane();
  24505. if (!options) {
  24506. return shape;
  24507. }
  24508. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24509. };
  24510. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24511. var verts = [], faces = [];
  24512. mesh.computeWorldMatrix(true);
  24513. for (var i = 0; i < rawVerts.length; i += 3) {
  24514. var transformed = BABYLON.Vector3.Zero();
  24515. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24516. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24517. }
  24518. for (var j = 0; j < rawFaces.length; j += 3) {
  24519. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24520. }
  24521. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24522. if (!options) {
  24523. return shape;
  24524. }
  24525. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24526. };
  24527. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24528. var index;
  24529. var mat;
  24530. for (index = 0; index < this._physicsMaterials.length; index++) {
  24531. mat = this._physicsMaterials[index];
  24532. if (mat.friction === friction && mat.restitution === restitution) {
  24533. return mat;
  24534. }
  24535. }
  24536. var currentMat = new CANNON.Material();
  24537. currentMat.friction = friction;
  24538. currentMat.restitution = restitution;
  24539. this._physicsMaterials.push(currentMat);
  24540. for (index = 0; index < this._physicsMaterials.length; index++) {
  24541. mat = this._physicsMaterials[index];
  24542. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24543. contactMaterial.contactEquationStiffness = 1e10;
  24544. contactMaterial.contactEquationRegularizationTime = 10;
  24545. this._world.addContactMaterial(contactMaterial);
  24546. }
  24547. return currentMat;
  24548. };
  24549. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24550. var initialRotation = null;
  24551. if (mesh.rotationQuaternion) {
  24552. initialRotation = mesh.rotationQuaternion.clone();
  24553. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24554. }
  24555. // The delta between the mesh position and the mesh bounding box center
  24556. var bbox = mesh.getBoundingInfo().boundingBox;
  24557. var deltaPosition = mesh.position.subtract(bbox.center);
  24558. var material = this._addMaterial(friction, restitution);
  24559. var body = new CANNON.RigidBody(mass, shape, material);
  24560. if (initialRotation) {
  24561. body.quaternion.x = initialRotation.x;
  24562. body.quaternion.z = initialRotation.y;
  24563. body.quaternion.y = initialRotation.z;
  24564. body.quaternion.w = -initialRotation.w;
  24565. }
  24566. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24567. this._world.add(body);
  24568. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24569. return body;
  24570. };
  24571. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24572. var compoundShape = new CANNON.Compound();
  24573. for (var index = 0; index < parts.length; index++) {
  24574. var mesh = parts[index].mesh;
  24575. var shape = this.registerMesh(mesh, parts[index].impostor);
  24576. if (index == 0) {
  24577. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24578. }
  24579. else {
  24580. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24581. }
  24582. }
  24583. var initialMesh = parts[0].mesh;
  24584. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24585. body.parts = parts;
  24586. return body;
  24587. };
  24588. CannonJSPlugin.prototype._unbindBody = function (body) {
  24589. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24590. var registeredMesh = this._registeredMeshes[index];
  24591. if (registeredMesh.body === body) {
  24592. registeredMesh.body = null;
  24593. registeredMesh.delta = 0;
  24594. }
  24595. }
  24596. };
  24597. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24598. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24599. var registeredMesh = this._registeredMeshes[index];
  24600. if (registeredMesh.mesh === mesh) {
  24601. // Remove body
  24602. if (registeredMesh.body) {
  24603. this._world.remove(registeredMesh.body);
  24604. this._unbindBody(registeredMesh.body);
  24605. }
  24606. this._registeredMeshes.splice(index, 1);
  24607. return;
  24608. }
  24609. }
  24610. };
  24611. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24612. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24613. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24614. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24615. var registeredMesh = this._registeredMeshes[index];
  24616. if (registeredMesh.mesh === mesh) {
  24617. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24618. return;
  24619. }
  24620. }
  24621. };
  24622. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24623. var body1 = null, body2 = null;
  24624. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24625. var registeredMesh = this._registeredMeshes[index];
  24626. if (registeredMesh.mesh === mesh1) {
  24627. body1 = registeredMesh.body;
  24628. }
  24629. else if (registeredMesh.mesh === mesh2) {
  24630. body2 = registeredMesh.body;
  24631. }
  24632. }
  24633. if (!body1 || !body2) {
  24634. return false;
  24635. }
  24636. 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));
  24637. this._world.addConstraint(constraint);
  24638. return true;
  24639. };
  24640. CannonJSPlugin.prototype.dispose = function () {
  24641. while (this._registeredMeshes.length) {
  24642. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24643. }
  24644. };
  24645. CannonJSPlugin.prototype.isSupported = function () {
  24646. return window.CANNON !== undefined;
  24647. };
  24648. return CannonJSPlugin;
  24649. })();
  24650. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24651. })(BABYLON || (BABYLON = {}));
  24652. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24653. var BABYLON;
  24654. (function (BABYLON) {
  24655. var Condition = (function () {
  24656. function Condition(actionManager) {
  24657. this._actionManager = actionManager;
  24658. }
  24659. Condition.prototype.isValid = function () {
  24660. return true;
  24661. };
  24662. Condition.prototype._getProperty = function (propertyPath) {
  24663. return this._actionManager._getProperty(propertyPath);
  24664. };
  24665. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24666. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24667. };
  24668. return Condition;
  24669. })();
  24670. BABYLON.Condition = Condition;
  24671. var ValueCondition = (function (_super) {
  24672. __extends(ValueCondition, _super);
  24673. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24674. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24675. _super.call(this, actionManager);
  24676. this.propertyPath = propertyPath;
  24677. this.value = value;
  24678. this.operator = operator;
  24679. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24680. this._property = this._getProperty(this.propertyPath);
  24681. }
  24682. Object.defineProperty(ValueCondition, "IsEqual", {
  24683. get: function () {
  24684. return ValueCondition._IsEqual;
  24685. },
  24686. enumerable: true,
  24687. configurable: true
  24688. });
  24689. Object.defineProperty(ValueCondition, "IsDifferent", {
  24690. get: function () {
  24691. return ValueCondition._IsDifferent;
  24692. },
  24693. enumerable: true,
  24694. configurable: true
  24695. });
  24696. Object.defineProperty(ValueCondition, "IsGreater", {
  24697. get: function () {
  24698. return ValueCondition._IsGreater;
  24699. },
  24700. enumerable: true,
  24701. configurable: true
  24702. });
  24703. Object.defineProperty(ValueCondition, "IsLesser", {
  24704. get: function () {
  24705. return ValueCondition._IsLesser;
  24706. },
  24707. enumerable: true,
  24708. configurable: true
  24709. });
  24710. // Methods
  24711. ValueCondition.prototype.isValid = function () {
  24712. switch (this.operator) {
  24713. case ValueCondition.IsGreater:
  24714. return this._target[this._property] > this.value;
  24715. case ValueCondition.IsLesser:
  24716. return this._target[this._property] < this.value;
  24717. case ValueCondition.IsEqual:
  24718. case ValueCondition.IsDifferent:
  24719. var check;
  24720. if (this.value.equals) {
  24721. check = this.value.equals(this._target[this._property]);
  24722. }
  24723. else {
  24724. check = this.value === this._target[this._property];
  24725. }
  24726. return this.operator === ValueCondition.IsEqual ? check : !check;
  24727. }
  24728. return false;
  24729. };
  24730. // Statics
  24731. ValueCondition._IsEqual = 0;
  24732. ValueCondition._IsDifferent = 1;
  24733. ValueCondition._IsGreater = 2;
  24734. ValueCondition._IsLesser = 3;
  24735. return ValueCondition;
  24736. })(Condition);
  24737. BABYLON.ValueCondition = ValueCondition;
  24738. var PredicateCondition = (function (_super) {
  24739. __extends(PredicateCondition, _super);
  24740. function PredicateCondition(actionManager, predicate) {
  24741. _super.call(this, actionManager);
  24742. this.predicate = predicate;
  24743. }
  24744. PredicateCondition.prototype.isValid = function () {
  24745. return this.predicate();
  24746. };
  24747. return PredicateCondition;
  24748. })(Condition);
  24749. BABYLON.PredicateCondition = PredicateCondition;
  24750. var StateCondition = (function (_super) {
  24751. __extends(StateCondition, _super);
  24752. function StateCondition(actionManager, target, value) {
  24753. _super.call(this, actionManager);
  24754. this.value = value;
  24755. this._target = target;
  24756. }
  24757. // Methods
  24758. StateCondition.prototype.isValid = function () {
  24759. return this._target.state === this.value;
  24760. };
  24761. return StateCondition;
  24762. })(Condition);
  24763. BABYLON.StateCondition = StateCondition;
  24764. })(BABYLON || (BABYLON = {}));
  24765. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24766. (function (BABYLON) {
  24767. var Action = (function () {
  24768. function Action(triggerOptions, condition) {
  24769. this.triggerOptions = triggerOptions;
  24770. if (triggerOptions.parameter) {
  24771. this.trigger = triggerOptions.trigger;
  24772. this._triggerParameter = triggerOptions.parameter;
  24773. }
  24774. else {
  24775. this.trigger = triggerOptions;
  24776. }
  24777. this._nextActiveAction = this;
  24778. this._condition = condition;
  24779. }
  24780. // Methods
  24781. Action.prototype._prepare = function () {
  24782. };
  24783. Action.prototype.getTriggerParameter = function () {
  24784. return this._triggerParameter;
  24785. };
  24786. Action.prototype._executeCurrent = function (evt) {
  24787. if (this._nextActiveAction._condition) {
  24788. var condition = this._nextActiveAction._condition;
  24789. var currentRenderId = this._actionManager.getScene().getRenderId();
  24790. // We cache the current evaluation for the current frame
  24791. if (condition._evaluationId === currentRenderId) {
  24792. if (!condition._currentResult) {
  24793. return;
  24794. }
  24795. }
  24796. else {
  24797. condition._evaluationId = currentRenderId;
  24798. if (!condition.isValid()) {
  24799. condition._currentResult = false;
  24800. return;
  24801. }
  24802. condition._currentResult = true;
  24803. }
  24804. }
  24805. this._nextActiveAction.execute(evt);
  24806. if (this._nextActiveAction._child) {
  24807. if (!this._nextActiveAction._child._actionManager) {
  24808. this._nextActiveAction._child._actionManager = this._actionManager;
  24809. }
  24810. this._nextActiveAction = this._nextActiveAction._child;
  24811. }
  24812. else {
  24813. this._nextActiveAction = this;
  24814. }
  24815. };
  24816. Action.prototype.execute = function (evt) {
  24817. };
  24818. Action.prototype.then = function (action) {
  24819. this._child = action;
  24820. action._actionManager = this._actionManager;
  24821. action._prepare();
  24822. return action;
  24823. };
  24824. Action.prototype._getProperty = function (propertyPath) {
  24825. return this._actionManager._getProperty(propertyPath);
  24826. };
  24827. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24828. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24829. };
  24830. return Action;
  24831. })();
  24832. BABYLON.Action = Action;
  24833. })(BABYLON || (BABYLON = {}));
  24834. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24835. (function (BABYLON) {
  24836. /**
  24837. * ActionEvent is the event beint sent when an action is triggered.
  24838. */
  24839. var ActionEvent = (function () {
  24840. /**
  24841. * @constructor
  24842. * @param source The mesh that triggered the action.
  24843. * @param pointerX the X mouse cursor position at the time of the event
  24844. * @param pointerY the Y mouse cursor position at the time of the event
  24845. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24846. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24847. */
  24848. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24849. this.source = source;
  24850. this.pointerX = pointerX;
  24851. this.pointerY = pointerY;
  24852. this.meshUnderPointer = meshUnderPointer;
  24853. this.sourceEvent = sourceEvent;
  24854. }
  24855. /**
  24856. * Helper function to auto-create an ActionEvent from a source mesh.
  24857. * @param source the source mesh that triggered the event
  24858. * @param evt {Event} The original (browser) event
  24859. */
  24860. ActionEvent.CreateNew = function (source, evt) {
  24861. var scene = source.getScene();
  24862. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24863. };
  24864. /**
  24865. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24866. * @param scene the scene where the event occurred
  24867. * @param evt {Event} The original (browser) event
  24868. */
  24869. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24870. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24871. };
  24872. return ActionEvent;
  24873. })();
  24874. BABYLON.ActionEvent = ActionEvent;
  24875. /**
  24876. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24877. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24878. */
  24879. var ActionManager = (function () {
  24880. function ActionManager(scene) {
  24881. // Members
  24882. this.actions = new Array();
  24883. this._scene = scene;
  24884. scene._actionManagers.push(this);
  24885. }
  24886. Object.defineProperty(ActionManager, "NothingTrigger", {
  24887. get: function () {
  24888. return ActionManager._NothingTrigger;
  24889. },
  24890. enumerable: true,
  24891. configurable: true
  24892. });
  24893. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24894. get: function () {
  24895. return ActionManager._OnPickTrigger;
  24896. },
  24897. enumerable: true,
  24898. configurable: true
  24899. });
  24900. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24901. get: function () {
  24902. return ActionManager._OnLeftPickTrigger;
  24903. },
  24904. enumerable: true,
  24905. configurable: true
  24906. });
  24907. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24908. get: function () {
  24909. return ActionManager._OnRightPickTrigger;
  24910. },
  24911. enumerable: true,
  24912. configurable: true
  24913. });
  24914. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24915. get: function () {
  24916. return ActionManager._OnCenterPickTrigger;
  24917. },
  24918. enumerable: true,
  24919. configurable: true
  24920. });
  24921. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24922. get: function () {
  24923. return ActionManager._OnPointerOverTrigger;
  24924. },
  24925. enumerable: true,
  24926. configurable: true
  24927. });
  24928. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24929. get: function () {
  24930. return ActionManager._OnPointerOutTrigger;
  24931. },
  24932. enumerable: true,
  24933. configurable: true
  24934. });
  24935. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24936. get: function () {
  24937. return ActionManager._OnEveryFrameTrigger;
  24938. },
  24939. enumerable: true,
  24940. configurable: true
  24941. });
  24942. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24943. get: function () {
  24944. return ActionManager._OnIntersectionEnterTrigger;
  24945. },
  24946. enumerable: true,
  24947. configurable: true
  24948. });
  24949. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24950. get: function () {
  24951. return ActionManager._OnIntersectionExitTrigger;
  24952. },
  24953. enumerable: true,
  24954. configurable: true
  24955. });
  24956. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24957. get: function () {
  24958. return ActionManager._OnKeyDownTrigger;
  24959. },
  24960. enumerable: true,
  24961. configurable: true
  24962. });
  24963. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24964. get: function () {
  24965. return ActionManager._OnKeyUpTrigger;
  24966. },
  24967. enumerable: true,
  24968. configurable: true
  24969. });
  24970. // Methods
  24971. ActionManager.prototype.dispose = function () {
  24972. var index = this._scene._actionManagers.indexOf(this);
  24973. if (index > -1) {
  24974. this._scene._actionManagers.splice(index, 1);
  24975. }
  24976. };
  24977. ActionManager.prototype.getScene = function () {
  24978. return this._scene;
  24979. };
  24980. /**
  24981. * Does this action manager handles actions of any of the given triggers
  24982. * @param {number[]} triggers - the triggers to be tested
  24983. * @return {boolean} whether one (or more) of the triggers is handeled
  24984. */
  24985. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24986. for (var index = 0; index < this.actions.length; index++) {
  24987. var action = this.actions[index];
  24988. if (triggers.indexOf(action.trigger) > -1) {
  24989. return true;
  24990. }
  24991. }
  24992. return false;
  24993. };
  24994. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24995. /**
  24996. * Does this action manager has pointer triggers
  24997. * @return {boolean} whether or not it has pointer triggers
  24998. */
  24999. get: function () {
  25000. for (var index = 0; index < this.actions.length; index++) {
  25001. var action = this.actions[index];
  25002. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25003. return true;
  25004. }
  25005. }
  25006. return false;
  25007. },
  25008. enumerable: true,
  25009. configurable: true
  25010. });
  25011. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25012. /**
  25013. * Does this action manager has pick triggers
  25014. * @return {boolean} whether or not it has pick triggers
  25015. */
  25016. get: function () {
  25017. for (var index = 0; index < this.actions.length; index++) {
  25018. var action = this.actions[index];
  25019. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25020. return true;
  25021. }
  25022. }
  25023. return false;
  25024. },
  25025. enumerable: true,
  25026. configurable: true
  25027. });
  25028. /**
  25029. * Registers an action to this action manager
  25030. * @param {BABYLON.Action} action - the action to be registered
  25031. * @return {BABYLON.Action} the action amended (prepared) after registration
  25032. */
  25033. ActionManager.prototype.registerAction = function (action) {
  25034. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25035. if (this.getScene().actionManager !== this) {
  25036. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25037. return null;
  25038. }
  25039. }
  25040. this.actions.push(action);
  25041. action._actionManager = this;
  25042. action._prepare();
  25043. return action;
  25044. };
  25045. /**
  25046. * Process a specific trigger
  25047. * @param {number} trigger - the trigger to process
  25048. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25049. */
  25050. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25051. for (var index = 0; index < this.actions.length; index++) {
  25052. var action = this.actions[index];
  25053. if (action.trigger === trigger) {
  25054. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  25055. var parameter = action.getTriggerParameter();
  25056. if (parameter) {
  25057. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25058. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25059. if (actualkey !== parameter.toLowerCase()) {
  25060. continue;
  25061. }
  25062. }
  25063. }
  25064. action._executeCurrent(evt);
  25065. }
  25066. }
  25067. };
  25068. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25069. var properties = propertyPath.split(".");
  25070. for (var index = 0; index < properties.length - 1; index++) {
  25071. target = target[properties[index]];
  25072. }
  25073. return target;
  25074. };
  25075. ActionManager.prototype._getProperty = function (propertyPath) {
  25076. var properties = propertyPath.split(".");
  25077. return properties[properties.length - 1];
  25078. };
  25079. // Statics
  25080. ActionManager._NothingTrigger = 0;
  25081. ActionManager._OnPickTrigger = 1;
  25082. ActionManager._OnLeftPickTrigger = 2;
  25083. ActionManager._OnRightPickTrigger = 3;
  25084. ActionManager._OnCenterPickTrigger = 4;
  25085. ActionManager._OnPointerOverTrigger = 5;
  25086. ActionManager._OnPointerOutTrigger = 6;
  25087. ActionManager._OnEveryFrameTrigger = 7;
  25088. ActionManager._OnIntersectionEnterTrigger = 8;
  25089. ActionManager._OnIntersectionExitTrigger = 9;
  25090. ActionManager._OnKeyDownTrigger = 10;
  25091. ActionManager._OnKeyUpTrigger = 11;
  25092. return ActionManager;
  25093. })();
  25094. BABYLON.ActionManager = ActionManager;
  25095. })(BABYLON || (BABYLON = {}));
  25096. //# sourceMappingURL=babylon.actionManager.js.map
  25097. var BABYLON;
  25098. (function (BABYLON) {
  25099. var InterpolateValueAction = (function (_super) {
  25100. __extends(InterpolateValueAction, _super);
  25101. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  25102. if (duration === void 0) { duration = 1000; }
  25103. _super.call(this, triggerOptions, condition);
  25104. this.propertyPath = propertyPath;
  25105. this.value = value;
  25106. this.duration = duration;
  25107. this.stopOtherAnimations = stopOtherAnimations;
  25108. this._target = target;
  25109. }
  25110. InterpolateValueAction.prototype._prepare = function () {
  25111. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25112. this._property = this._getProperty(this.propertyPath);
  25113. };
  25114. InterpolateValueAction.prototype.execute = function () {
  25115. var scene = this._actionManager.getScene();
  25116. var keys = [
  25117. {
  25118. frame: 0,
  25119. value: this._target[this._property]
  25120. },
  25121. {
  25122. frame: 100,
  25123. value: this.value
  25124. }
  25125. ];
  25126. var dataType;
  25127. if (typeof this.value === "number") {
  25128. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25129. }
  25130. else if (this.value instanceof BABYLON.Color3) {
  25131. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25132. }
  25133. else if (this.value instanceof BABYLON.Vector3) {
  25134. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25135. }
  25136. else if (this.value instanceof BABYLON.Matrix) {
  25137. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25138. }
  25139. else if (this.value instanceof BABYLON.Quaternion) {
  25140. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25141. }
  25142. else {
  25143. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25144. return;
  25145. }
  25146. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25147. animation.setKeys(keys);
  25148. if (this.stopOtherAnimations) {
  25149. scene.stopAnimation(this._target);
  25150. }
  25151. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  25152. };
  25153. return InterpolateValueAction;
  25154. })(BABYLON.Action);
  25155. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25156. })(BABYLON || (BABYLON = {}));
  25157. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  25158. var BABYLON;
  25159. (function (BABYLON) {
  25160. var SwitchBooleanAction = (function (_super) {
  25161. __extends(SwitchBooleanAction, _super);
  25162. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25163. _super.call(this, triggerOptions, condition);
  25164. this.propertyPath = propertyPath;
  25165. this._target = target;
  25166. }
  25167. SwitchBooleanAction.prototype._prepare = function () {
  25168. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25169. this._property = this._getProperty(this.propertyPath);
  25170. };
  25171. SwitchBooleanAction.prototype.execute = function () {
  25172. this._target[this._property] = !this._target[this._property];
  25173. };
  25174. return SwitchBooleanAction;
  25175. })(BABYLON.Action);
  25176. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25177. var SetStateAction = (function (_super) {
  25178. __extends(SetStateAction, _super);
  25179. function SetStateAction(triggerOptions, target, value, condition) {
  25180. _super.call(this, triggerOptions, condition);
  25181. this.value = value;
  25182. this._target = target;
  25183. }
  25184. SetStateAction.prototype.execute = function () {
  25185. this._target.state = this.value;
  25186. };
  25187. return SetStateAction;
  25188. })(BABYLON.Action);
  25189. BABYLON.SetStateAction = SetStateAction;
  25190. var SetValueAction = (function (_super) {
  25191. __extends(SetValueAction, _super);
  25192. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25193. _super.call(this, triggerOptions, condition);
  25194. this.propertyPath = propertyPath;
  25195. this.value = value;
  25196. this._target = target;
  25197. }
  25198. SetValueAction.prototype._prepare = function () {
  25199. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25200. this._property = this._getProperty(this.propertyPath);
  25201. };
  25202. SetValueAction.prototype.execute = function () {
  25203. this._target[this._property] = this.value;
  25204. };
  25205. return SetValueAction;
  25206. })(BABYLON.Action);
  25207. BABYLON.SetValueAction = SetValueAction;
  25208. var IncrementValueAction = (function (_super) {
  25209. __extends(IncrementValueAction, _super);
  25210. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25211. _super.call(this, triggerOptions, condition);
  25212. this.propertyPath = propertyPath;
  25213. this.value = value;
  25214. this._target = target;
  25215. }
  25216. IncrementValueAction.prototype._prepare = function () {
  25217. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25218. this._property = this._getProperty(this.propertyPath);
  25219. if (typeof this._target[this._property] !== "number") {
  25220. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25221. }
  25222. };
  25223. IncrementValueAction.prototype.execute = function () {
  25224. this._target[this._property] += this.value;
  25225. };
  25226. return IncrementValueAction;
  25227. })(BABYLON.Action);
  25228. BABYLON.IncrementValueAction = IncrementValueAction;
  25229. var PlayAnimationAction = (function (_super) {
  25230. __extends(PlayAnimationAction, _super);
  25231. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25232. _super.call(this, triggerOptions, condition);
  25233. this.from = from;
  25234. this.to = to;
  25235. this.loop = loop;
  25236. this._target = target;
  25237. }
  25238. PlayAnimationAction.prototype._prepare = function () {
  25239. };
  25240. PlayAnimationAction.prototype.execute = function () {
  25241. var scene = this._actionManager.getScene();
  25242. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25243. };
  25244. return PlayAnimationAction;
  25245. })(BABYLON.Action);
  25246. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25247. var StopAnimationAction = (function (_super) {
  25248. __extends(StopAnimationAction, _super);
  25249. function StopAnimationAction(triggerOptions, target, condition) {
  25250. _super.call(this, triggerOptions, condition);
  25251. this._target = target;
  25252. }
  25253. StopAnimationAction.prototype._prepare = function () {
  25254. };
  25255. StopAnimationAction.prototype.execute = function () {
  25256. var scene = this._actionManager.getScene();
  25257. scene.stopAnimation(this._target);
  25258. };
  25259. return StopAnimationAction;
  25260. })(BABYLON.Action);
  25261. BABYLON.StopAnimationAction = StopAnimationAction;
  25262. var DoNothingAction = (function (_super) {
  25263. __extends(DoNothingAction, _super);
  25264. function DoNothingAction(triggerOptions, condition) {
  25265. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25266. _super.call(this, triggerOptions, condition);
  25267. }
  25268. DoNothingAction.prototype.execute = function () {
  25269. };
  25270. return DoNothingAction;
  25271. })(BABYLON.Action);
  25272. BABYLON.DoNothingAction = DoNothingAction;
  25273. var CombineAction = (function (_super) {
  25274. __extends(CombineAction, _super);
  25275. function CombineAction(triggerOptions, children, condition) {
  25276. _super.call(this, triggerOptions, condition);
  25277. this.children = children;
  25278. }
  25279. CombineAction.prototype._prepare = function () {
  25280. for (var index = 0; index < this.children.length; index++) {
  25281. this.children[index]._actionManager = this._actionManager;
  25282. this.children[index]._prepare();
  25283. }
  25284. };
  25285. CombineAction.prototype.execute = function (evt) {
  25286. for (var index = 0; index < this.children.length; index++) {
  25287. this.children[index].execute(evt);
  25288. }
  25289. };
  25290. return CombineAction;
  25291. })(BABYLON.Action);
  25292. BABYLON.CombineAction = CombineAction;
  25293. var ExecuteCodeAction = (function (_super) {
  25294. __extends(ExecuteCodeAction, _super);
  25295. function ExecuteCodeAction(triggerOptions, func, condition) {
  25296. _super.call(this, triggerOptions, condition);
  25297. this.func = func;
  25298. }
  25299. ExecuteCodeAction.prototype.execute = function (evt) {
  25300. this.func(evt);
  25301. };
  25302. return ExecuteCodeAction;
  25303. })(BABYLON.Action);
  25304. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25305. var SetParentAction = (function (_super) {
  25306. __extends(SetParentAction, _super);
  25307. function SetParentAction(triggerOptions, target, parent, condition) {
  25308. _super.call(this, triggerOptions, condition);
  25309. this._target = target;
  25310. this._parent = parent;
  25311. }
  25312. SetParentAction.prototype._prepare = function () {
  25313. };
  25314. SetParentAction.prototype.execute = function () {
  25315. if (this._target.parent === this._parent) {
  25316. return;
  25317. }
  25318. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25319. invertParentWorldMatrix.invert();
  25320. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25321. this._target.parent = this._parent;
  25322. };
  25323. return SetParentAction;
  25324. })(BABYLON.Action);
  25325. BABYLON.SetParentAction = SetParentAction;
  25326. var PlaySoundAction = (function (_super) {
  25327. __extends(PlaySoundAction, _super);
  25328. function PlaySoundAction(triggerOptions, sound, condition) {
  25329. _super.call(this, triggerOptions, condition);
  25330. this._sound = sound;
  25331. }
  25332. PlaySoundAction.prototype._prepare = function () {
  25333. };
  25334. PlaySoundAction.prototype.execute = function () {
  25335. if (this._sound !== undefined)
  25336. this._sound.play();
  25337. };
  25338. return PlaySoundAction;
  25339. })(BABYLON.Action);
  25340. BABYLON.PlaySoundAction = PlaySoundAction;
  25341. var StopSoundAction = (function (_super) {
  25342. __extends(StopSoundAction, _super);
  25343. function StopSoundAction(triggerOptions, sound, condition) {
  25344. _super.call(this, triggerOptions, condition);
  25345. this._sound = sound;
  25346. }
  25347. StopSoundAction.prototype._prepare = function () {
  25348. };
  25349. StopSoundAction.prototype.execute = function () {
  25350. if (this._sound !== undefined)
  25351. this._sound.stop();
  25352. };
  25353. return StopSoundAction;
  25354. })(BABYLON.Action);
  25355. BABYLON.StopSoundAction = StopSoundAction;
  25356. })(BABYLON || (BABYLON = {}));
  25357. //# sourceMappingURL=babylon.directActions.js.map
  25358. var BABYLON;
  25359. (function (BABYLON) {
  25360. var Geometry = (function () {
  25361. function Geometry(id, scene, vertexData, updatable, mesh) {
  25362. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25363. this._totalVertices = 0;
  25364. this._indices = [];
  25365. this._isDisposed = false;
  25366. this.id = id;
  25367. this._engine = scene.getEngine();
  25368. this._meshes = [];
  25369. this._scene = scene;
  25370. // vertexData
  25371. if (vertexData) {
  25372. this.setAllVerticesData(vertexData, updatable);
  25373. }
  25374. else {
  25375. this._totalVertices = 0;
  25376. this._indices = [];
  25377. }
  25378. // applyToMesh
  25379. if (mesh) {
  25380. this.applyToMesh(mesh);
  25381. mesh.computeWorldMatrix(true);
  25382. }
  25383. }
  25384. Geometry.prototype.getScene = function () {
  25385. return this._scene;
  25386. };
  25387. Geometry.prototype.getEngine = function () {
  25388. return this._engine;
  25389. };
  25390. Geometry.prototype.isReady = function () {
  25391. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25392. };
  25393. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25394. vertexData.applyToGeometry(this, updatable);
  25395. this.notifyUpdate();
  25396. };
  25397. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25398. this._vertexBuffers = this._vertexBuffers || {};
  25399. if (this._vertexBuffers[kind]) {
  25400. this._vertexBuffers[kind].dispose();
  25401. }
  25402. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25403. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25404. stride = this._vertexBuffers[kind].getStrideSize();
  25405. this._totalVertices = data.length / stride;
  25406. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25407. var meshes = this._meshes;
  25408. var numOfMeshes = meshes.length;
  25409. for (var index = 0; index < numOfMeshes; index++) {
  25410. var mesh = meshes[index];
  25411. mesh._resetPointsArrayCache();
  25412. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25413. mesh._createGlobalSubMesh();
  25414. mesh.computeWorldMatrix(true);
  25415. }
  25416. }
  25417. this.notifyUpdate(kind);
  25418. };
  25419. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25420. var vertexBuffer = this.getVertexBuffer(kind);
  25421. if (!vertexBuffer) {
  25422. return;
  25423. }
  25424. vertexBuffer.updateDirectly(data, offset);
  25425. this.notifyUpdate(kind);
  25426. };
  25427. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25428. var vertexBuffer = this.getVertexBuffer(kind);
  25429. if (!vertexBuffer) {
  25430. return;
  25431. }
  25432. vertexBuffer.update(data);
  25433. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25434. var extend;
  25435. var stride = vertexBuffer.getStrideSize();
  25436. this._totalVertices = data.length / stride;
  25437. if (updateExtends) {
  25438. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25439. }
  25440. var meshes = this._meshes;
  25441. var numOfMeshes = meshes.length;
  25442. for (var index = 0; index < numOfMeshes; index++) {
  25443. var mesh = meshes[index];
  25444. mesh._resetPointsArrayCache();
  25445. if (updateExtends) {
  25446. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25447. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25448. var subMesh = mesh.subMeshes[subIndex];
  25449. subMesh.refreshBoundingInfo();
  25450. }
  25451. }
  25452. }
  25453. }
  25454. this.notifyUpdate(kind);
  25455. };
  25456. Geometry.prototype.getTotalVertices = function () {
  25457. if (!this.isReady()) {
  25458. return 0;
  25459. }
  25460. return this._totalVertices;
  25461. };
  25462. Geometry.prototype.getVerticesData = function (kind) {
  25463. var vertexBuffer = this.getVertexBuffer(kind);
  25464. if (!vertexBuffer) {
  25465. return null;
  25466. }
  25467. return vertexBuffer.getData();
  25468. };
  25469. Geometry.prototype.getVertexBuffer = function (kind) {
  25470. if (!this.isReady()) {
  25471. return null;
  25472. }
  25473. return this._vertexBuffers[kind];
  25474. };
  25475. Geometry.prototype.getVertexBuffers = function () {
  25476. if (!this.isReady()) {
  25477. return null;
  25478. }
  25479. return this._vertexBuffers;
  25480. };
  25481. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25482. if (!this._vertexBuffers) {
  25483. if (this._delayInfo) {
  25484. return this._delayInfo.indexOf(kind) !== -1;
  25485. }
  25486. return false;
  25487. }
  25488. return this._vertexBuffers[kind] !== undefined;
  25489. };
  25490. Geometry.prototype.getVerticesDataKinds = function () {
  25491. var result = [];
  25492. if (!this._vertexBuffers && this._delayInfo) {
  25493. for (var kind in this._delayInfo) {
  25494. result.push(kind);
  25495. }
  25496. }
  25497. else {
  25498. for (kind in this._vertexBuffers) {
  25499. result.push(kind);
  25500. }
  25501. }
  25502. return result;
  25503. };
  25504. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25505. if (this._indexBuffer) {
  25506. this._engine._releaseBuffer(this._indexBuffer);
  25507. }
  25508. this._indices = indices;
  25509. if (this._meshes.length !== 0 && this._indices) {
  25510. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25511. }
  25512. if (totalVertices !== undefined) {
  25513. this._totalVertices = totalVertices;
  25514. }
  25515. var meshes = this._meshes;
  25516. var numOfMeshes = meshes.length;
  25517. for (var index = 0; index < numOfMeshes; index++) {
  25518. meshes[index]._createGlobalSubMesh();
  25519. }
  25520. this.notifyUpdate();
  25521. };
  25522. Geometry.prototype.getTotalIndices = function () {
  25523. if (!this.isReady()) {
  25524. return 0;
  25525. }
  25526. return this._indices.length;
  25527. };
  25528. Geometry.prototype.getIndices = function () {
  25529. if (!this.isReady()) {
  25530. return null;
  25531. }
  25532. return this._indices;
  25533. };
  25534. Geometry.prototype.getIndexBuffer = function () {
  25535. if (!this.isReady()) {
  25536. return null;
  25537. }
  25538. return this._indexBuffer;
  25539. };
  25540. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25541. var meshes = this._meshes;
  25542. var index = meshes.indexOf(mesh);
  25543. if (index === -1) {
  25544. return;
  25545. }
  25546. for (var kind in this._vertexBuffers) {
  25547. this._vertexBuffers[kind].dispose();
  25548. }
  25549. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25550. this._indexBuffer = null;
  25551. }
  25552. meshes.splice(index, 1);
  25553. mesh._geometry = null;
  25554. if (meshes.length === 0 && shouldDispose) {
  25555. this.dispose();
  25556. }
  25557. };
  25558. Geometry.prototype.applyToMesh = function (mesh) {
  25559. if (mesh._geometry === this) {
  25560. return;
  25561. }
  25562. var previousGeometry = mesh._geometry;
  25563. if (previousGeometry) {
  25564. previousGeometry.releaseForMesh(mesh);
  25565. }
  25566. var meshes = this._meshes;
  25567. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25568. mesh._geometry = this;
  25569. this._scene.pushGeometry(this);
  25570. meshes.push(mesh);
  25571. if (this.isReady()) {
  25572. this._applyToMesh(mesh);
  25573. }
  25574. else {
  25575. mesh._boundingInfo = this._boundingInfo;
  25576. }
  25577. };
  25578. Geometry.prototype._applyToMesh = function (mesh) {
  25579. var numOfMeshes = this._meshes.length;
  25580. for (var kind in this._vertexBuffers) {
  25581. if (numOfMeshes === 1) {
  25582. this._vertexBuffers[kind].create();
  25583. }
  25584. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25585. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25586. mesh._resetPointsArrayCache();
  25587. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25588. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25589. mesh._createGlobalSubMesh();
  25590. //bounding info was just created again, world matrix should be applied again.
  25591. mesh._updateBoundingInfo();
  25592. }
  25593. }
  25594. // indexBuffer
  25595. if (numOfMeshes === 1 && this._indices) {
  25596. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25597. }
  25598. if (this._indexBuffer) {
  25599. this._indexBuffer.references = numOfMeshes;
  25600. }
  25601. };
  25602. Geometry.prototype.notifyUpdate = function (kind) {
  25603. if (this.onGeometryUpdated) {
  25604. this.onGeometryUpdated(this, kind);
  25605. }
  25606. };
  25607. Geometry.prototype.load = function (scene, onLoaded) {
  25608. var _this = this;
  25609. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25610. return;
  25611. }
  25612. if (this.isReady()) {
  25613. if (onLoaded) {
  25614. onLoaded();
  25615. }
  25616. return;
  25617. }
  25618. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25619. scene._addPendingData(this);
  25620. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25621. _this._delayLoadingFunction(JSON.parse(data), _this);
  25622. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25623. _this._delayInfo = [];
  25624. scene._removePendingData(_this);
  25625. var meshes = _this._meshes;
  25626. var numOfMeshes = meshes.length;
  25627. for (var index = 0; index < numOfMeshes; index++) {
  25628. _this._applyToMesh(meshes[index]);
  25629. }
  25630. if (onLoaded) {
  25631. onLoaded();
  25632. }
  25633. }, function () {
  25634. }, scene.database);
  25635. };
  25636. Geometry.prototype.isDisposed = function () {
  25637. return this._isDisposed;
  25638. };
  25639. Geometry.prototype.dispose = function () {
  25640. var meshes = this._meshes;
  25641. var numOfMeshes = meshes.length;
  25642. var index;
  25643. for (index = 0; index < numOfMeshes; index++) {
  25644. this.releaseForMesh(meshes[index]);
  25645. }
  25646. this._meshes = [];
  25647. for (var kind in this._vertexBuffers) {
  25648. this._vertexBuffers[kind].dispose();
  25649. }
  25650. this._vertexBuffers = [];
  25651. this._totalVertices = 0;
  25652. if (this._indexBuffer) {
  25653. this._engine._releaseBuffer(this._indexBuffer);
  25654. }
  25655. this._indexBuffer = null;
  25656. this._indices = [];
  25657. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25658. this.delayLoadingFile = null;
  25659. this._delayLoadingFunction = null;
  25660. this._delayInfo = [];
  25661. this._boundingInfo = null; // todo: .dispose()
  25662. this._scene.removeGeometry(this);
  25663. this._isDisposed = true;
  25664. };
  25665. Geometry.prototype.copy = function (id) {
  25666. var vertexData = new BABYLON.VertexData();
  25667. vertexData.indices = [];
  25668. var indices = this.getIndices();
  25669. for (var index = 0; index < indices.length; index++) {
  25670. vertexData.indices.push(indices[index]);
  25671. }
  25672. var updatable = false;
  25673. var stopChecking = false;
  25674. for (var kind in this._vertexBuffers) {
  25675. // using slice() to make a copy of the array and not just reference it
  25676. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25677. if (!stopChecking) {
  25678. updatable = this.getVertexBuffer(kind).isUpdatable();
  25679. stopChecking = !updatable;
  25680. }
  25681. }
  25682. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25683. geometry.delayLoadState = this.delayLoadState;
  25684. geometry.delayLoadingFile = this.delayLoadingFile;
  25685. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25686. for (kind in this._delayInfo) {
  25687. geometry._delayInfo = geometry._delayInfo || [];
  25688. geometry._delayInfo.push(kind);
  25689. }
  25690. // Bounding info
  25691. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25692. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25693. return geometry;
  25694. };
  25695. // Statics
  25696. Geometry.ExtractFromMesh = function (mesh, id) {
  25697. var geometry = mesh._geometry;
  25698. if (!geometry) {
  25699. return null;
  25700. }
  25701. return geometry.copy(id);
  25702. };
  25703. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25704. // be aware Math.random() could cause collisions
  25705. Geometry.RandomId = function () {
  25706. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25707. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25708. return v.toString(16);
  25709. });
  25710. };
  25711. return Geometry;
  25712. })();
  25713. BABYLON.Geometry = Geometry;
  25714. /////// Primitives //////////////////////////////////////////////
  25715. var Geometry;
  25716. (function (Geometry) {
  25717. var Primitives;
  25718. (function (Primitives) {
  25719. /// Abstract class
  25720. var _Primitive = (function (_super) {
  25721. __extends(_Primitive, _super);
  25722. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25723. this._beingRegenerated = true;
  25724. this._canBeRegenerated = canBeRegenerated;
  25725. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25726. this._beingRegenerated = false;
  25727. }
  25728. _Primitive.prototype.canBeRegenerated = function () {
  25729. return this._canBeRegenerated;
  25730. };
  25731. _Primitive.prototype.regenerate = function () {
  25732. if (!this._canBeRegenerated) {
  25733. return;
  25734. }
  25735. this._beingRegenerated = true;
  25736. this.setAllVerticesData(this._regenerateVertexData(), false);
  25737. this._beingRegenerated = false;
  25738. };
  25739. _Primitive.prototype.asNewGeometry = function (id) {
  25740. return _super.prototype.copy.call(this, id);
  25741. };
  25742. // overrides
  25743. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25744. if (!this._beingRegenerated) {
  25745. return;
  25746. }
  25747. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25748. };
  25749. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25750. if (!this._beingRegenerated) {
  25751. return;
  25752. }
  25753. _super.prototype.setVerticesData.call(this, kind, data, false);
  25754. };
  25755. // to override
  25756. // protected
  25757. _Primitive.prototype._regenerateVertexData = function () {
  25758. throw new Error("Abstract method");
  25759. };
  25760. _Primitive.prototype.copy = function (id) {
  25761. throw new Error("Must be overriden in sub-classes.");
  25762. };
  25763. return _Primitive;
  25764. })(Geometry);
  25765. Primitives._Primitive = _Primitive;
  25766. var Ribbon = (function (_super) {
  25767. __extends(Ribbon, _super);
  25768. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25769. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25770. this.pathArray = pathArray;
  25771. this.closeArray = closeArray;
  25772. this.closePath = closePath;
  25773. this.offset = offset;
  25774. this.side = side;
  25775. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25776. }
  25777. Ribbon.prototype._regenerateVertexData = function () {
  25778. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25779. };
  25780. Ribbon.prototype.copy = function (id) {
  25781. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25782. };
  25783. return Ribbon;
  25784. })(_Primitive);
  25785. Primitives.Ribbon = Ribbon;
  25786. var Box = (function (_super) {
  25787. __extends(Box, _super);
  25788. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25789. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25790. this.size = size;
  25791. this.side = side;
  25792. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25793. }
  25794. Box.prototype._regenerateVertexData = function () {
  25795. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25796. };
  25797. Box.prototype.copy = function (id) {
  25798. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25799. };
  25800. return Box;
  25801. })(_Primitive);
  25802. Primitives.Box = Box;
  25803. var Sphere = (function (_super) {
  25804. __extends(Sphere, _super);
  25805. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25806. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25807. this.segments = segments;
  25808. this.diameter = diameter;
  25809. this.side = side;
  25810. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25811. }
  25812. Sphere.prototype._regenerateVertexData = function () {
  25813. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25814. };
  25815. Sphere.prototype.copy = function (id) {
  25816. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25817. };
  25818. return Sphere;
  25819. })(_Primitive);
  25820. Primitives.Sphere = Sphere;
  25821. var Cylinder = (function (_super) {
  25822. __extends(Cylinder, _super);
  25823. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25824. if (subdivisions === void 0) { subdivisions = 1; }
  25825. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25826. this.height = height;
  25827. this.diameterTop = diameterTop;
  25828. this.diameterBottom = diameterBottom;
  25829. this.tessellation = tessellation;
  25830. this.subdivisions = subdivisions;
  25831. this.side = side;
  25832. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25833. }
  25834. Cylinder.prototype._regenerateVertexData = function () {
  25835. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25836. };
  25837. Cylinder.prototype.copy = function (id) {
  25838. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25839. };
  25840. return Cylinder;
  25841. })(_Primitive);
  25842. Primitives.Cylinder = Cylinder;
  25843. var Torus = (function (_super) {
  25844. __extends(Torus, _super);
  25845. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25846. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25847. this.diameter = diameter;
  25848. this.thickness = thickness;
  25849. this.tessellation = tessellation;
  25850. this.side = side;
  25851. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25852. }
  25853. Torus.prototype._regenerateVertexData = function () {
  25854. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25855. };
  25856. Torus.prototype.copy = function (id) {
  25857. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25858. };
  25859. return Torus;
  25860. })(_Primitive);
  25861. Primitives.Torus = Torus;
  25862. var Ground = (function (_super) {
  25863. __extends(Ground, _super);
  25864. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25865. this.width = width;
  25866. this.height = height;
  25867. this.subdivisions = subdivisions;
  25868. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25869. }
  25870. Ground.prototype._regenerateVertexData = function () {
  25871. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25872. };
  25873. Ground.prototype.copy = function (id) {
  25874. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25875. };
  25876. return Ground;
  25877. })(_Primitive);
  25878. Primitives.Ground = Ground;
  25879. var TiledGround = (function (_super) {
  25880. __extends(TiledGround, _super);
  25881. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25882. this.xmin = xmin;
  25883. this.zmin = zmin;
  25884. this.xmax = xmax;
  25885. this.zmax = zmax;
  25886. this.subdivisions = subdivisions;
  25887. this.precision = precision;
  25888. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25889. }
  25890. TiledGround.prototype._regenerateVertexData = function () {
  25891. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25892. };
  25893. TiledGround.prototype.copy = function (id) {
  25894. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25895. };
  25896. return TiledGround;
  25897. })(_Primitive);
  25898. Primitives.TiledGround = TiledGround;
  25899. var Plane = (function (_super) {
  25900. __extends(Plane, _super);
  25901. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25902. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25903. this.size = size;
  25904. this.side = side;
  25905. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25906. }
  25907. Plane.prototype._regenerateVertexData = function () {
  25908. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25909. };
  25910. Plane.prototype.copy = function (id) {
  25911. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25912. };
  25913. return Plane;
  25914. })(_Primitive);
  25915. Primitives.Plane = Plane;
  25916. var TorusKnot = (function (_super) {
  25917. __extends(TorusKnot, _super);
  25918. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25919. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25920. this.radius = radius;
  25921. this.tube = tube;
  25922. this.radialSegments = radialSegments;
  25923. this.tubularSegments = tubularSegments;
  25924. this.p = p;
  25925. this.q = q;
  25926. this.side = side;
  25927. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25928. }
  25929. TorusKnot.prototype._regenerateVertexData = function () {
  25930. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25931. };
  25932. TorusKnot.prototype.copy = function (id) {
  25933. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25934. };
  25935. return TorusKnot;
  25936. })(_Primitive);
  25937. Primitives.TorusKnot = TorusKnot;
  25938. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25939. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25940. })(BABYLON || (BABYLON = {}));
  25941. //# sourceMappingURL=babylon.geometry.js.map
  25942. var BABYLON;
  25943. (function (BABYLON) {
  25944. var Gamepads = (function () {
  25945. function Gamepads(ongamedpadconnected) {
  25946. var _this = this;
  25947. this.babylonGamepads = [];
  25948. this.oneGamepadConnected = false;
  25949. this.isMonitoring = false;
  25950. this.gamepadEventSupported = 'GamepadEvent' in window;
  25951. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25952. 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=";
  25953. this._callbackGamepadConnected = ongamedpadconnected;
  25954. if (this.gamepadSupportAvailable) {
  25955. // Checking if the gamepad connected event is supported (like in Firefox)
  25956. if (this.gamepadEventSupported) {
  25957. window.addEventListener('gamepadconnected', function (evt) {
  25958. _this._onGamepadConnected(evt);
  25959. }, false);
  25960. window.addEventListener('gamepaddisconnected', function (evt) {
  25961. _this._onGamepadDisconnected(evt);
  25962. }, false);
  25963. }
  25964. else {
  25965. this._startMonitoringGamepads();
  25966. }
  25967. if (!this.oneGamepadConnected) {
  25968. this._insertGamepadDOMInstructions();
  25969. }
  25970. }
  25971. else {
  25972. this._insertGamepadDOMNotSupported();
  25973. }
  25974. }
  25975. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25976. Gamepads.gamepadDOMInfo = document.createElement("div");
  25977. var buttonAImage = document.createElement("img");
  25978. buttonAImage.src = this.buttonADataURL;
  25979. var spanMessage = document.createElement("span");
  25980. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25981. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25982. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25983. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25984. Gamepads.gamepadDOMInfo.style.width = "100%";
  25985. Gamepads.gamepadDOMInfo.style.height = "48px";
  25986. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25987. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25988. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25989. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25990. buttonAImage.style.position = "relative";
  25991. buttonAImage.style.bottom = "8px";
  25992. spanMessage.style.position = "relative";
  25993. spanMessage.style.fontSize = "32px";
  25994. spanMessage.style.bottom = "32px";
  25995. spanMessage.style.color = "green";
  25996. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25997. };
  25998. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25999. Gamepads.gamepadDOMInfo = document.createElement("div");
  26000. var spanMessage = document.createElement("span");
  26001. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  26002. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26003. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26004. Gamepads.gamepadDOMInfo.style.width = "100%";
  26005. Gamepads.gamepadDOMInfo.style.height = "40px";
  26006. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26007. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26008. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26009. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26010. spanMessage.style.position = "relative";
  26011. spanMessage.style.fontSize = "32px";
  26012. spanMessage.style.color = "red";
  26013. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26014. };
  26015. Gamepads.prototype.dispose = function () {
  26016. if (Gamepads.gamepadDOMInfo) {
  26017. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26018. }
  26019. };
  26020. Gamepads.prototype._onGamepadConnected = function (evt) {
  26021. var newGamepad = this._addNewGamepad(evt.gamepad);
  26022. if (this._callbackGamepadConnected)
  26023. this._callbackGamepadConnected(newGamepad);
  26024. this._startMonitoringGamepads();
  26025. };
  26026. Gamepads.prototype._addNewGamepad = function (gamepad) {
  26027. if (!this.oneGamepadConnected) {
  26028. this.oneGamepadConnected = true;
  26029. if (Gamepads.gamepadDOMInfo) {
  26030. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26031. Gamepads.gamepadDOMInfo = null;
  26032. }
  26033. }
  26034. var newGamepad;
  26035. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  26036. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  26037. }
  26038. else {
  26039. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  26040. }
  26041. this.babylonGamepads.push(newGamepad);
  26042. return newGamepad;
  26043. };
  26044. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  26045. for (var i in this.babylonGamepads) {
  26046. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  26047. this.babylonGamepads.splice(i, 1);
  26048. break;
  26049. }
  26050. }
  26051. // If no gamepads are left, stop the polling loop.
  26052. if (this.babylonGamepads.length == 0) {
  26053. this._stopMonitoringGamepads();
  26054. }
  26055. };
  26056. Gamepads.prototype._startMonitoringGamepads = function () {
  26057. if (!this.isMonitoring) {
  26058. this.isMonitoring = true;
  26059. this._checkGamepadsStatus();
  26060. }
  26061. };
  26062. Gamepads.prototype._stopMonitoringGamepads = function () {
  26063. this.isMonitoring = false;
  26064. };
  26065. Gamepads.prototype._checkGamepadsStatus = function () {
  26066. var _this = this;
  26067. // updating gamepad objects
  26068. this._updateGamepadObjects();
  26069. for (var i in this.babylonGamepads) {
  26070. this.babylonGamepads[i].update();
  26071. }
  26072. if (this.isMonitoring) {
  26073. if (window.requestAnimationFrame) {
  26074. window.requestAnimationFrame(function () {
  26075. _this._checkGamepadsStatus();
  26076. });
  26077. }
  26078. else if (window.mozRequestAnimationFrame) {
  26079. window.mozRequestAnimationFrame(function () {
  26080. _this._checkGamepadsStatus();
  26081. });
  26082. }
  26083. else if (window.webkitRequestAnimationFrame) {
  26084. window.webkitRequestAnimationFrame(function () {
  26085. _this._checkGamepadsStatus();
  26086. });
  26087. }
  26088. }
  26089. };
  26090. // This function is called only on Chrome, which does not yet support
  26091. // connection/disconnection events, but requires you to monitor
  26092. // an array for changes.
  26093. Gamepads.prototype._updateGamepadObjects = function () {
  26094. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  26095. for (var i = 0; i < gamepads.length; i++) {
  26096. if (gamepads[i]) {
  26097. if (!(gamepads[i].index in this.babylonGamepads)) {
  26098. var newGamepad = this._addNewGamepad(gamepads[i]);
  26099. if (this._callbackGamepadConnected) {
  26100. this._callbackGamepadConnected(newGamepad);
  26101. }
  26102. }
  26103. else {
  26104. this.babylonGamepads[i].browserGamepad = gamepads[i];
  26105. }
  26106. }
  26107. }
  26108. };
  26109. return Gamepads;
  26110. })();
  26111. BABYLON.Gamepads = Gamepads;
  26112. var StickValues = (function () {
  26113. function StickValues(x, y) {
  26114. this.x = x;
  26115. this.y = y;
  26116. }
  26117. return StickValues;
  26118. })();
  26119. BABYLON.StickValues = StickValues;
  26120. var Gamepad = (function () {
  26121. function Gamepad(id, index, browserGamepad) {
  26122. this.id = id;
  26123. this.index = index;
  26124. this.browserGamepad = browserGamepad;
  26125. if (this.browserGamepad.axes.length >= 2) {
  26126. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26127. }
  26128. if (this.browserGamepad.axes.length >= 4) {
  26129. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26130. }
  26131. }
  26132. Gamepad.prototype.onleftstickchanged = function (callback) {
  26133. this._onleftstickchanged = callback;
  26134. };
  26135. Gamepad.prototype.onrightstickchanged = function (callback) {
  26136. this._onrightstickchanged = callback;
  26137. };
  26138. Object.defineProperty(Gamepad.prototype, "leftStick", {
  26139. get: function () {
  26140. return this._leftStick;
  26141. },
  26142. set: function (newValues) {
  26143. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  26144. this._onleftstickchanged(newValues);
  26145. }
  26146. this._leftStick = newValues;
  26147. },
  26148. enumerable: true,
  26149. configurable: true
  26150. });
  26151. Object.defineProperty(Gamepad.prototype, "rightStick", {
  26152. get: function () {
  26153. return this._rightStick;
  26154. },
  26155. set: function (newValues) {
  26156. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  26157. this._onrightstickchanged(newValues);
  26158. }
  26159. this._rightStick = newValues;
  26160. },
  26161. enumerable: true,
  26162. configurable: true
  26163. });
  26164. Gamepad.prototype.update = function () {
  26165. if (this._leftStick) {
  26166. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26167. }
  26168. if (this._rightStick) {
  26169. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26170. }
  26171. };
  26172. return Gamepad;
  26173. })();
  26174. BABYLON.Gamepad = Gamepad;
  26175. var GenericPad = (function (_super) {
  26176. __extends(GenericPad, _super);
  26177. function GenericPad(id, index, gamepad) {
  26178. _super.call(this, id, index, gamepad);
  26179. this.id = id;
  26180. this.index = index;
  26181. this.gamepad = gamepad;
  26182. this._buttons = new Array(gamepad.buttons.length);
  26183. }
  26184. GenericPad.prototype.onbuttondown = function (callback) {
  26185. this._onbuttondown = callback;
  26186. };
  26187. GenericPad.prototype.onbuttonup = function (callback) {
  26188. this._onbuttonup = callback;
  26189. };
  26190. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  26191. if (newValue !== currentValue) {
  26192. if (this._onbuttondown && newValue === 1) {
  26193. this._onbuttondown(buttonIndex);
  26194. }
  26195. if (this._onbuttonup && newValue === 0) {
  26196. this._onbuttonup(buttonIndex);
  26197. }
  26198. }
  26199. return newValue;
  26200. };
  26201. GenericPad.prototype.update = function () {
  26202. _super.prototype.update.call(this);
  26203. for (var index = 0; index < this._buttons.length; index++) {
  26204. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  26205. }
  26206. };
  26207. return GenericPad;
  26208. })(Gamepad);
  26209. BABYLON.GenericPad = GenericPad;
  26210. (function (Xbox360Button) {
  26211. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  26212. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  26213. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  26214. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  26215. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  26216. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  26217. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  26218. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  26219. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  26220. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  26221. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  26222. var Xbox360Button = BABYLON.Xbox360Button;
  26223. (function (Xbox360Dpad) {
  26224. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  26225. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  26226. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  26227. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  26228. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  26229. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  26230. var Xbox360Pad = (function (_super) {
  26231. __extends(Xbox360Pad, _super);
  26232. function Xbox360Pad() {
  26233. _super.apply(this, arguments);
  26234. this._leftTrigger = 0;
  26235. this._rightTrigger = 0;
  26236. this._buttonA = 0;
  26237. this._buttonB = 0;
  26238. this._buttonX = 0;
  26239. this._buttonY = 0;
  26240. this._buttonBack = 0;
  26241. this._buttonStart = 0;
  26242. this._buttonLB = 0;
  26243. this._buttonRB = 0;
  26244. this._buttonLeftStick = 0;
  26245. this._buttonRightStick = 0;
  26246. this._dPadUp = 0;
  26247. this._dPadDown = 0;
  26248. this._dPadLeft = 0;
  26249. this._dPadRight = 0;
  26250. }
  26251. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  26252. this._onlefttriggerchanged = callback;
  26253. };
  26254. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  26255. this._onrighttriggerchanged = callback;
  26256. };
  26257. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  26258. get: function () {
  26259. return this._leftTrigger;
  26260. },
  26261. set: function (newValue) {
  26262. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  26263. this._onlefttriggerchanged(newValue);
  26264. }
  26265. this._leftTrigger = newValue;
  26266. },
  26267. enumerable: true,
  26268. configurable: true
  26269. });
  26270. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  26271. get: function () {
  26272. return this._rightTrigger;
  26273. },
  26274. set: function (newValue) {
  26275. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  26276. this._onrighttriggerchanged(newValue);
  26277. }
  26278. this._rightTrigger = newValue;
  26279. },
  26280. enumerable: true,
  26281. configurable: true
  26282. });
  26283. Xbox360Pad.prototype.onbuttondown = function (callback) {
  26284. this._onbuttondown = callback;
  26285. };
  26286. Xbox360Pad.prototype.onbuttonup = function (callback) {
  26287. this._onbuttonup = callback;
  26288. };
  26289. Xbox360Pad.prototype.ondpaddown = function (callback) {
  26290. this._ondpaddown = callback;
  26291. };
  26292. Xbox360Pad.prototype.ondpadup = function (callback) {
  26293. this._ondpadup = callback;
  26294. };
  26295. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  26296. if (newValue !== currentValue) {
  26297. if (this._onbuttondown && newValue === 1) {
  26298. this._onbuttondown(buttonType);
  26299. }
  26300. if (this._onbuttonup && newValue === 0) {
  26301. this._onbuttonup(buttonType);
  26302. }
  26303. }
  26304. return newValue;
  26305. };
  26306. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  26307. if (newValue !== currentValue) {
  26308. if (this._ondpaddown && newValue === 1) {
  26309. this._ondpaddown(buttonType);
  26310. }
  26311. if (this._ondpadup && newValue === 0) {
  26312. this._ondpadup(buttonType);
  26313. }
  26314. }
  26315. return newValue;
  26316. };
  26317. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  26318. get: function () {
  26319. return this._buttonA;
  26320. },
  26321. set: function (value) {
  26322. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  26323. },
  26324. enumerable: true,
  26325. configurable: true
  26326. });
  26327. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  26328. get: function () {
  26329. return this._buttonB;
  26330. },
  26331. set: function (value) {
  26332. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  26333. },
  26334. enumerable: true,
  26335. configurable: true
  26336. });
  26337. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  26338. get: function () {
  26339. return this._buttonX;
  26340. },
  26341. set: function (value) {
  26342. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  26343. },
  26344. enumerable: true,
  26345. configurable: true
  26346. });
  26347. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  26348. get: function () {
  26349. return this._buttonY;
  26350. },
  26351. set: function (value) {
  26352. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  26353. },
  26354. enumerable: true,
  26355. configurable: true
  26356. });
  26357. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  26358. get: function () {
  26359. return this._buttonStart;
  26360. },
  26361. set: function (value) {
  26362. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  26363. },
  26364. enumerable: true,
  26365. configurable: true
  26366. });
  26367. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  26368. get: function () {
  26369. return this._buttonBack;
  26370. },
  26371. set: function (value) {
  26372. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  26373. },
  26374. enumerable: true,
  26375. configurable: true
  26376. });
  26377. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  26378. get: function () {
  26379. return this._buttonLB;
  26380. },
  26381. set: function (value) {
  26382. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  26383. },
  26384. enumerable: true,
  26385. configurable: true
  26386. });
  26387. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  26388. get: function () {
  26389. return this._buttonRB;
  26390. },
  26391. set: function (value) {
  26392. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  26393. },
  26394. enumerable: true,
  26395. configurable: true
  26396. });
  26397. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  26398. get: function () {
  26399. return this._buttonLeftStick;
  26400. },
  26401. set: function (value) {
  26402. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  26403. },
  26404. enumerable: true,
  26405. configurable: true
  26406. });
  26407. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  26408. get: function () {
  26409. return this._buttonRightStick;
  26410. },
  26411. set: function (value) {
  26412. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  26413. },
  26414. enumerable: true,
  26415. configurable: true
  26416. });
  26417. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  26418. get: function () {
  26419. return this._dPadUp;
  26420. },
  26421. set: function (value) {
  26422. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  26423. },
  26424. enumerable: true,
  26425. configurable: true
  26426. });
  26427. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  26428. get: function () {
  26429. return this._dPadDown;
  26430. },
  26431. set: function (value) {
  26432. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  26433. },
  26434. enumerable: true,
  26435. configurable: true
  26436. });
  26437. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  26438. get: function () {
  26439. return this._dPadLeft;
  26440. },
  26441. set: function (value) {
  26442. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  26443. },
  26444. enumerable: true,
  26445. configurable: true
  26446. });
  26447. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  26448. get: function () {
  26449. return this._dPadRight;
  26450. },
  26451. set: function (value) {
  26452. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  26453. },
  26454. enumerable: true,
  26455. configurable: true
  26456. });
  26457. Xbox360Pad.prototype.update = function () {
  26458. _super.prototype.update.call(this);
  26459. this.buttonA = this.browserGamepad.buttons[0].value;
  26460. this.buttonB = this.browserGamepad.buttons[1].value;
  26461. this.buttonX = this.browserGamepad.buttons[2].value;
  26462. this.buttonY = this.browserGamepad.buttons[3].value;
  26463. this.buttonLB = this.browserGamepad.buttons[4].value;
  26464. this.buttonRB = this.browserGamepad.buttons[5].value;
  26465. this.leftTrigger = this.browserGamepad.buttons[6].value;
  26466. this.rightTrigger = this.browserGamepad.buttons[7].value;
  26467. this.buttonBack = this.browserGamepad.buttons[8].value;
  26468. this.buttonStart = this.browserGamepad.buttons[9].value;
  26469. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  26470. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  26471. this.dPadUp = this.browserGamepad.buttons[12].value;
  26472. this.dPadDown = this.browserGamepad.buttons[13].value;
  26473. this.dPadLeft = this.browserGamepad.buttons[14].value;
  26474. this.dPadRight = this.browserGamepad.buttons[15].value;
  26475. };
  26476. return Xbox360Pad;
  26477. })(Gamepad);
  26478. BABYLON.Xbox360Pad = Xbox360Pad;
  26479. })(BABYLON || (BABYLON = {}));
  26480. //# sourceMappingURL=babylon.gamepads.js.map
  26481. var BABYLON;
  26482. (function (BABYLON) {
  26483. // We're mainly based on the logic defined into the FreeCamera code
  26484. var GamepadCamera = (function (_super) {
  26485. __extends(GamepadCamera, _super);
  26486. function GamepadCamera(name, position, scene) {
  26487. var _this = this;
  26488. _super.call(this, name, position, scene);
  26489. this.angularSensibility = 200;
  26490. this.moveSensibility = 75;
  26491. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26492. _this._onNewGameConnected(gamepad);
  26493. });
  26494. }
  26495. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26496. // Only the first gamepad can control the camera
  26497. if (gamepad.index === 0) {
  26498. this._gamepad = gamepad;
  26499. }
  26500. };
  26501. GamepadCamera.prototype._checkInputs = function () {
  26502. if (!this._gamepad) {
  26503. return;
  26504. }
  26505. var LSValues = this._gamepad.leftStick;
  26506. var normalizedLX = LSValues.x / this.moveSensibility;
  26507. var normalizedLY = LSValues.y / this.moveSensibility;
  26508. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26509. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26510. var RSValues = this._gamepad.rightStick;
  26511. var normalizedRX = RSValues.x / this.angularSensibility;
  26512. var normalizedRY = RSValues.y / this.angularSensibility;
  26513. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26514. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26515. ;
  26516. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26517. var speed = this._computeLocalCameraSpeed() * 50.0;
  26518. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26519. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26520. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26521. };
  26522. GamepadCamera.prototype.dispose = function () {
  26523. this._gamepads.dispose();
  26524. _super.prototype.dispose.call(this);
  26525. };
  26526. return GamepadCamera;
  26527. })(BABYLON.FreeCamera);
  26528. BABYLON.GamepadCamera = GamepadCamera;
  26529. })(BABYLON || (BABYLON = {}));
  26530. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26531. var BABYLON;
  26532. (function (BABYLON) {
  26533. var LinesMesh = (function (_super) {
  26534. __extends(LinesMesh, _super);
  26535. function LinesMesh(name, scene, updatable) {
  26536. if (updatable === void 0) { updatable = false; }
  26537. _super.call(this, name, scene);
  26538. this.color = new BABYLON.Color3(1, 1, 1);
  26539. this.alpha = 1;
  26540. this._indices = new Array();
  26541. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26542. attributes: ["position"],
  26543. uniforms: ["worldViewProjection", "color"],
  26544. needAlphaBlending: true
  26545. });
  26546. }
  26547. Object.defineProperty(LinesMesh.prototype, "material", {
  26548. get: function () {
  26549. return this._colorShader;
  26550. },
  26551. enumerable: true,
  26552. configurable: true
  26553. });
  26554. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26555. get: function () {
  26556. return false;
  26557. },
  26558. enumerable: true,
  26559. configurable: true
  26560. });
  26561. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26562. get: function () {
  26563. return false;
  26564. },
  26565. enumerable: true,
  26566. configurable: true
  26567. });
  26568. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26569. var engine = this.getScene().getEngine();
  26570. var indexToBind = this._geometry.getIndexBuffer();
  26571. // VBOs
  26572. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26573. // Color
  26574. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26575. };
  26576. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26577. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26578. return;
  26579. }
  26580. var engine = this.getScene().getEngine();
  26581. // Draw order
  26582. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26583. };
  26584. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26585. return null;
  26586. };
  26587. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26588. this._colorShader.dispose();
  26589. _super.prototype.dispose.call(this, doNotRecurse);
  26590. };
  26591. return LinesMesh;
  26592. })(BABYLON.Mesh);
  26593. BABYLON.LinesMesh = LinesMesh;
  26594. })(BABYLON || (BABYLON = {}));
  26595. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26596. (function (BABYLON) {
  26597. var OutlineRenderer = (function () {
  26598. function OutlineRenderer(scene) {
  26599. this._scene = scene;
  26600. }
  26601. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26602. var _this = this;
  26603. if (useOverlay === void 0) { useOverlay = false; }
  26604. var scene = this._scene;
  26605. var engine = this._scene.getEngine();
  26606. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26607. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26608. return;
  26609. }
  26610. var mesh = subMesh.getRenderingMesh();
  26611. var material = subMesh.getMaterial();
  26612. engine.enableEffect(this._effect);
  26613. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26614. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26615. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26616. // Bones
  26617. if (mesh.useBones) {
  26618. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26619. }
  26620. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26621. // Alpha test
  26622. if (material && material.needAlphaTesting()) {
  26623. var alphaTexture = material.getAlphaTestTexture();
  26624. this._effect.setTexture("diffuseSampler", alphaTexture);
  26625. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26626. }
  26627. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26628. _this._effect.setMatrix("world", world);
  26629. });
  26630. };
  26631. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26632. var defines = [];
  26633. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26634. var mesh = subMesh.getMesh();
  26635. var material = subMesh.getMaterial();
  26636. // Alpha test
  26637. if (material && material.needAlphaTesting()) {
  26638. defines.push("#define ALPHATEST");
  26639. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26640. attribs.push(BABYLON.VertexBuffer.UVKind);
  26641. defines.push("#define UV1");
  26642. }
  26643. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26644. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26645. defines.push("#define UV2");
  26646. }
  26647. }
  26648. // Bones
  26649. if (mesh.useBones) {
  26650. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26651. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26652. defines.push("#define BONES");
  26653. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26654. }
  26655. // Instances
  26656. if (useInstances) {
  26657. defines.push("#define INSTANCES");
  26658. attribs.push("world0");
  26659. attribs.push("world1");
  26660. attribs.push("world2");
  26661. attribs.push("world3");
  26662. }
  26663. // Get correct effect
  26664. var join = defines.join("\n");
  26665. if (this._cachedDefines !== join) {
  26666. this._cachedDefines = join;
  26667. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26668. }
  26669. return this._effect.isReady();
  26670. };
  26671. return OutlineRenderer;
  26672. })();
  26673. BABYLON.OutlineRenderer = OutlineRenderer;
  26674. })(BABYLON || (BABYLON = {}));
  26675. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26676. (function (BABYLON) {
  26677. var MeshAssetTask = (function () {
  26678. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26679. this.name = name;
  26680. this.meshesNames = meshesNames;
  26681. this.rootUrl = rootUrl;
  26682. this.sceneFilename = sceneFilename;
  26683. this.isCompleted = false;
  26684. }
  26685. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26686. var _this = this;
  26687. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26688. _this.loadedMeshes = meshes;
  26689. _this.loadedParticleSystems = particleSystems;
  26690. _this.loadedSkeletons = skeletons;
  26691. _this.isCompleted = true;
  26692. if (_this.onSuccess) {
  26693. _this.onSuccess(_this);
  26694. }
  26695. onSuccess();
  26696. }, null, function () {
  26697. if (_this.onError) {
  26698. _this.onError(_this);
  26699. }
  26700. onError();
  26701. });
  26702. };
  26703. return MeshAssetTask;
  26704. })();
  26705. BABYLON.MeshAssetTask = MeshAssetTask;
  26706. var TextFileAssetTask = (function () {
  26707. function TextFileAssetTask(name, url) {
  26708. this.name = name;
  26709. this.url = url;
  26710. this.isCompleted = false;
  26711. }
  26712. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26713. var _this = this;
  26714. BABYLON.Tools.LoadFile(this.url, function (data) {
  26715. _this.text = data;
  26716. _this.isCompleted = true;
  26717. if (_this.onSuccess) {
  26718. _this.onSuccess(_this);
  26719. }
  26720. onSuccess();
  26721. }, null, scene.database, false, function () {
  26722. if (_this.onError) {
  26723. _this.onError(_this);
  26724. }
  26725. onError();
  26726. });
  26727. };
  26728. return TextFileAssetTask;
  26729. })();
  26730. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26731. var BinaryFileAssetTask = (function () {
  26732. function BinaryFileAssetTask(name, url) {
  26733. this.name = name;
  26734. this.url = url;
  26735. this.isCompleted = false;
  26736. }
  26737. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26738. var _this = this;
  26739. BABYLON.Tools.LoadFile(this.url, function (data) {
  26740. _this.data = data;
  26741. _this.isCompleted = true;
  26742. if (_this.onSuccess) {
  26743. _this.onSuccess(_this);
  26744. }
  26745. onSuccess();
  26746. }, null, scene.database, true, function () {
  26747. if (_this.onError) {
  26748. _this.onError(_this);
  26749. }
  26750. onError();
  26751. });
  26752. };
  26753. return BinaryFileAssetTask;
  26754. })();
  26755. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26756. var ImageAssetTask = (function () {
  26757. function ImageAssetTask(name, url) {
  26758. this.name = name;
  26759. this.url = url;
  26760. this.isCompleted = false;
  26761. }
  26762. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26763. var _this = this;
  26764. var img = new Image();
  26765. img.onload = function () {
  26766. _this.image = img;
  26767. _this.isCompleted = true;
  26768. if (_this.onSuccess) {
  26769. _this.onSuccess(_this);
  26770. }
  26771. onSuccess();
  26772. };
  26773. img.onerror = function () {
  26774. if (_this.onError) {
  26775. _this.onError(_this);
  26776. }
  26777. onError();
  26778. };
  26779. img.src = this.url;
  26780. };
  26781. return ImageAssetTask;
  26782. })();
  26783. BABYLON.ImageAssetTask = ImageAssetTask;
  26784. var TextureAssetTask = (function () {
  26785. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26786. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26787. this.name = name;
  26788. this.url = url;
  26789. this.noMipmap = noMipmap;
  26790. this.invertY = invertY;
  26791. this.samplingMode = samplingMode;
  26792. this.isCompleted = false;
  26793. }
  26794. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26795. var _this = this;
  26796. var onload = function () {
  26797. _this.isCompleted = true;
  26798. if (_this.onSuccess) {
  26799. _this.onSuccess(_this);
  26800. }
  26801. onSuccess();
  26802. };
  26803. var onerror = function () {
  26804. if (_this.onError) {
  26805. _this.onError(_this);
  26806. }
  26807. onError();
  26808. };
  26809. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26810. };
  26811. return TextureAssetTask;
  26812. })();
  26813. BABYLON.TextureAssetTask = TextureAssetTask;
  26814. var AssetsManager = (function () {
  26815. function AssetsManager(scene) {
  26816. this._tasks = new Array();
  26817. this._waitingTasksCount = 0;
  26818. this.useDefaultLoadingScreen = true;
  26819. this._scene = scene;
  26820. }
  26821. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26822. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26823. this._tasks.push(task);
  26824. return task;
  26825. };
  26826. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26827. var task = new TextFileAssetTask(taskName, url);
  26828. this._tasks.push(task);
  26829. return task;
  26830. };
  26831. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26832. var task = new BinaryFileAssetTask(taskName, url);
  26833. this._tasks.push(task);
  26834. return task;
  26835. };
  26836. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26837. var task = new ImageAssetTask(taskName, url);
  26838. this._tasks.push(task);
  26839. return task;
  26840. };
  26841. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26842. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26843. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26844. this._tasks.push(task);
  26845. return task;
  26846. };
  26847. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26848. this._waitingTasksCount--;
  26849. if (this._waitingTasksCount === 0) {
  26850. if (this.onFinish) {
  26851. this.onFinish(this._tasks);
  26852. }
  26853. this._scene.getEngine().hideLoadingUI();
  26854. }
  26855. };
  26856. AssetsManager.prototype._runTask = function (task) {
  26857. var _this = this;
  26858. task.run(this._scene, function () {
  26859. if (_this.onTaskSuccess) {
  26860. _this.onTaskSuccess(task);
  26861. }
  26862. _this._decreaseWaitingTasksCount();
  26863. }, function () {
  26864. if (_this.onTaskError) {
  26865. _this.onTaskError(task);
  26866. }
  26867. _this._decreaseWaitingTasksCount();
  26868. });
  26869. };
  26870. AssetsManager.prototype.reset = function () {
  26871. this._tasks = new Array();
  26872. return this;
  26873. };
  26874. AssetsManager.prototype.load = function () {
  26875. this._waitingTasksCount = this._tasks.length;
  26876. if (this._waitingTasksCount === 0) {
  26877. if (this.onFinish) {
  26878. this.onFinish(this._tasks);
  26879. }
  26880. return this;
  26881. }
  26882. if (this.useDefaultLoadingScreen) {
  26883. this._scene.getEngine().displayLoadingUI();
  26884. }
  26885. for (var index = 0; index < this._tasks.length; index++) {
  26886. var task = this._tasks[index];
  26887. this._runTask(task);
  26888. }
  26889. return this;
  26890. };
  26891. return AssetsManager;
  26892. })();
  26893. BABYLON.AssetsManager = AssetsManager;
  26894. })(BABYLON || (BABYLON = {}));
  26895. //# sourceMappingURL=babylon.assetsManager.js.map
  26896. var BABYLON;
  26897. (function (BABYLON) {
  26898. var VRDeviceOrientationCamera = (function (_super) {
  26899. __extends(VRDeviceOrientationCamera, _super);
  26900. function VRDeviceOrientationCamera(name, position, scene) {
  26901. _super.call(this, name, position, scene);
  26902. this._alpha = 0;
  26903. this._beta = 0;
  26904. this._gamma = 0;
  26905. }
  26906. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26907. this._alpha = +evt.alpha | 0;
  26908. this._beta = +evt.beta | 0;
  26909. this._gamma = +evt.gamma | 0;
  26910. if (this._gamma < 0) {
  26911. this._gamma = 90 + this._gamma;
  26912. }
  26913. else {
  26914. // Incline it in the correct angle.
  26915. this._gamma = 270 - this._gamma;
  26916. }
  26917. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26918. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26919. this.rotation.z = this._beta / 180.0 * Math.PI;
  26920. };
  26921. return VRDeviceOrientationCamera;
  26922. })(BABYLON.OculusCamera);
  26923. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26924. })(BABYLON || (BABYLON = {}));
  26925. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26926. var BABYLON;
  26927. (function (BABYLON) {
  26928. var WebVRCamera = (function (_super) {
  26929. __extends(WebVRCamera, _super);
  26930. function WebVRCamera(name, position, scene) {
  26931. _super.call(this, name, position, scene);
  26932. this._hmdDevice = null;
  26933. this._sensorDevice = null;
  26934. this._cacheState = null;
  26935. this._cacheQuaternion = new BABYLON.Quaternion();
  26936. this._cacheRotation = BABYLON.Vector3.Zero();
  26937. this._vrEnabled = false;
  26938. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26939. }
  26940. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26941. var size = devices.length;
  26942. var i = 0;
  26943. // Reset devices.
  26944. this._sensorDevice = null;
  26945. this._hmdDevice = null;
  26946. while (i < size && this._hmdDevice === null) {
  26947. if (devices[i] instanceof HMDVRDevice) {
  26948. this._hmdDevice = devices[i];
  26949. }
  26950. i++;
  26951. }
  26952. i = 0;
  26953. while (i < size && this._sensorDevice === null) {
  26954. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26955. this._sensorDevice = devices[i];
  26956. }
  26957. i++;
  26958. }
  26959. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26960. };
  26961. WebVRCamera.prototype._update = function () {
  26962. if (this._vrEnabled) {
  26963. this._cacheState = this._sensorDevice.getState();
  26964. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26965. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26966. this.rotation.x = -this._cacheRotation.z;
  26967. this.rotation.y = -this._cacheRotation.y;
  26968. this.rotation.z = this._cacheRotation.x;
  26969. }
  26970. _super.prototype._update.call(this);
  26971. };
  26972. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26973. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26974. if (navigator.getVRDevices) {
  26975. navigator.getVRDevices().then(this._getWebVRDevices);
  26976. }
  26977. else if (navigator.mozGetVRDevices) {
  26978. navigator.mozGetVRDevices(this._getWebVRDevices);
  26979. }
  26980. };
  26981. WebVRCamera.prototype.detachControl = function (element) {
  26982. _super.prototype.detachControl.call(this, element);
  26983. this._vrEnabled = false;
  26984. };
  26985. return WebVRCamera;
  26986. })(BABYLON.OculusCamera);
  26987. BABYLON.WebVRCamera = WebVRCamera;
  26988. })(BABYLON || (BABYLON = {}));
  26989. //# sourceMappingURL=babylon.webVRCamera.js.map
  26990. var BABYLON;
  26991. (function (BABYLON) {
  26992. // Standard optimizations
  26993. var SceneOptimization = (function () {
  26994. function SceneOptimization(priority) {
  26995. if (priority === void 0) { priority = 0; }
  26996. this.priority = priority;
  26997. this.apply = function (scene) {
  26998. return true; // Return true if everything that can be done was applied
  26999. };
  27000. }
  27001. return SceneOptimization;
  27002. })();
  27003. BABYLON.SceneOptimization = SceneOptimization;
  27004. var TextureOptimization = (function (_super) {
  27005. __extends(TextureOptimization, _super);
  27006. function TextureOptimization(priority, maximumSize) {
  27007. var _this = this;
  27008. if (priority === void 0) { priority = 0; }
  27009. if (maximumSize === void 0) { maximumSize = 1024; }
  27010. _super.call(this, priority);
  27011. this.priority = priority;
  27012. this.maximumSize = maximumSize;
  27013. this.apply = function (scene) {
  27014. var allDone = true;
  27015. for (var index = 0; index < scene.textures.length; index++) {
  27016. var texture = scene.textures[index];
  27017. if (!texture.canRescale) {
  27018. continue;
  27019. }
  27020. var currentSize = texture.getSize();
  27021. var maxDimension = Math.max(currentSize.width, currentSize.height);
  27022. if (maxDimension > _this.maximumSize) {
  27023. texture.scale(0.5);
  27024. allDone = false;
  27025. }
  27026. }
  27027. return allDone;
  27028. };
  27029. }
  27030. return TextureOptimization;
  27031. })(SceneOptimization);
  27032. BABYLON.TextureOptimization = TextureOptimization;
  27033. var HardwareScalingOptimization = (function (_super) {
  27034. __extends(HardwareScalingOptimization, _super);
  27035. function HardwareScalingOptimization(priority, maximumScale) {
  27036. var _this = this;
  27037. if (priority === void 0) { priority = 0; }
  27038. if (maximumScale === void 0) { maximumScale = 2; }
  27039. _super.call(this, priority);
  27040. this.priority = priority;
  27041. this.maximumScale = maximumScale;
  27042. this._currentScale = 1;
  27043. this.apply = function (scene) {
  27044. _this._currentScale++;
  27045. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  27046. return _this._currentScale >= _this.maximumScale;
  27047. };
  27048. }
  27049. return HardwareScalingOptimization;
  27050. })(SceneOptimization);
  27051. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  27052. var ShadowsOptimization = (function (_super) {
  27053. __extends(ShadowsOptimization, _super);
  27054. function ShadowsOptimization() {
  27055. _super.apply(this, arguments);
  27056. this.apply = function (scene) {
  27057. scene.shadowsEnabled = false;
  27058. return true;
  27059. };
  27060. }
  27061. return ShadowsOptimization;
  27062. })(SceneOptimization);
  27063. BABYLON.ShadowsOptimization = ShadowsOptimization;
  27064. var PostProcessesOptimization = (function (_super) {
  27065. __extends(PostProcessesOptimization, _super);
  27066. function PostProcessesOptimization() {
  27067. _super.apply(this, arguments);
  27068. this.apply = function (scene) {
  27069. scene.postProcessesEnabled = false;
  27070. return true;
  27071. };
  27072. }
  27073. return PostProcessesOptimization;
  27074. })(SceneOptimization);
  27075. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  27076. var LensFlaresOptimization = (function (_super) {
  27077. __extends(LensFlaresOptimization, _super);
  27078. function LensFlaresOptimization() {
  27079. _super.apply(this, arguments);
  27080. this.apply = function (scene) {
  27081. scene.lensFlaresEnabled = false;
  27082. return true;
  27083. };
  27084. }
  27085. return LensFlaresOptimization;
  27086. })(SceneOptimization);
  27087. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  27088. var ParticlesOptimization = (function (_super) {
  27089. __extends(ParticlesOptimization, _super);
  27090. function ParticlesOptimization() {
  27091. _super.apply(this, arguments);
  27092. this.apply = function (scene) {
  27093. scene.particlesEnabled = false;
  27094. return true;
  27095. };
  27096. }
  27097. return ParticlesOptimization;
  27098. })(SceneOptimization);
  27099. BABYLON.ParticlesOptimization = ParticlesOptimization;
  27100. var RenderTargetsOptimization = (function (_super) {
  27101. __extends(RenderTargetsOptimization, _super);
  27102. function RenderTargetsOptimization() {
  27103. _super.apply(this, arguments);
  27104. this.apply = function (scene) {
  27105. scene.renderTargetsEnabled = false;
  27106. return true;
  27107. };
  27108. }
  27109. return RenderTargetsOptimization;
  27110. })(SceneOptimization);
  27111. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  27112. var MergeMeshesOptimization = (function (_super) {
  27113. __extends(MergeMeshesOptimization, _super);
  27114. function MergeMeshesOptimization() {
  27115. var _this = this;
  27116. _super.apply(this, arguments);
  27117. this._canBeMerged = function (abstractMesh) {
  27118. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  27119. return false;
  27120. }
  27121. var mesh = abstractMesh;
  27122. if (!mesh.isVisible || !mesh.isEnabled()) {
  27123. return false;
  27124. }
  27125. if (mesh.instances.length > 0) {
  27126. return false;
  27127. }
  27128. if (mesh.skeleton || mesh.hasLODLevels) {
  27129. return false;
  27130. }
  27131. return true;
  27132. };
  27133. this.apply = function (scene) {
  27134. var globalPool = scene.meshes.slice(0);
  27135. var globalLength = globalPool.length;
  27136. for (var index = 0; index < globalLength; index++) {
  27137. var currentPool = new Array();
  27138. var current = globalPool[index];
  27139. // Checks
  27140. if (!_this._canBeMerged(current)) {
  27141. continue;
  27142. }
  27143. currentPool.push(current);
  27144. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  27145. var otherMesh = globalPool[subIndex];
  27146. if (!_this._canBeMerged(otherMesh)) {
  27147. continue;
  27148. }
  27149. if (otherMesh.material !== current.material) {
  27150. continue;
  27151. }
  27152. if (otherMesh.checkCollisions !== current.checkCollisions) {
  27153. continue;
  27154. }
  27155. currentPool.push(otherMesh);
  27156. globalLength--;
  27157. globalPool.splice(subIndex, 1);
  27158. subIndex--;
  27159. }
  27160. if (currentPool.length < 2) {
  27161. continue;
  27162. }
  27163. // Merge meshes
  27164. BABYLON.Mesh.MergeMeshes(currentPool);
  27165. }
  27166. return true;
  27167. };
  27168. }
  27169. return MergeMeshesOptimization;
  27170. })(SceneOptimization);
  27171. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  27172. // Options
  27173. var SceneOptimizerOptions = (function () {
  27174. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  27175. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  27176. if (trackerDuration === void 0) { trackerDuration = 2000; }
  27177. this.targetFrameRate = targetFrameRate;
  27178. this.trackerDuration = trackerDuration;
  27179. this.optimizations = new Array();
  27180. }
  27181. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  27182. var result = new SceneOptimizerOptions(targetFrameRate);
  27183. var priority = 0;
  27184. result.optimizations.push(new MergeMeshesOptimization(priority));
  27185. result.optimizations.push(new ShadowsOptimization(priority));
  27186. result.optimizations.push(new LensFlaresOptimization(priority));
  27187. // Next priority
  27188. priority++;
  27189. result.optimizations.push(new PostProcessesOptimization(priority));
  27190. result.optimizations.push(new ParticlesOptimization(priority));
  27191. // Next priority
  27192. priority++;
  27193. result.optimizations.push(new TextureOptimization(priority, 1024));
  27194. return result;
  27195. };
  27196. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  27197. var result = new SceneOptimizerOptions(targetFrameRate);
  27198. var priority = 0;
  27199. result.optimizations.push(new MergeMeshesOptimization(priority));
  27200. result.optimizations.push(new ShadowsOptimization(priority));
  27201. result.optimizations.push(new LensFlaresOptimization(priority));
  27202. // Next priority
  27203. priority++;
  27204. result.optimizations.push(new PostProcessesOptimization(priority));
  27205. result.optimizations.push(new ParticlesOptimization(priority));
  27206. // Next priority
  27207. priority++;
  27208. result.optimizations.push(new TextureOptimization(priority, 512));
  27209. // Next priority
  27210. priority++;
  27211. result.optimizations.push(new RenderTargetsOptimization(priority));
  27212. // Next priority
  27213. priority++;
  27214. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  27215. return result;
  27216. };
  27217. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  27218. var result = new SceneOptimizerOptions(targetFrameRate);
  27219. var priority = 0;
  27220. result.optimizations.push(new MergeMeshesOptimization(priority));
  27221. result.optimizations.push(new ShadowsOptimization(priority));
  27222. result.optimizations.push(new LensFlaresOptimization(priority));
  27223. // Next priority
  27224. priority++;
  27225. result.optimizations.push(new PostProcessesOptimization(priority));
  27226. result.optimizations.push(new ParticlesOptimization(priority));
  27227. // Next priority
  27228. priority++;
  27229. result.optimizations.push(new TextureOptimization(priority, 256));
  27230. // Next priority
  27231. priority++;
  27232. result.optimizations.push(new RenderTargetsOptimization(priority));
  27233. // Next priority
  27234. priority++;
  27235. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  27236. return result;
  27237. };
  27238. return SceneOptimizerOptions;
  27239. })();
  27240. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  27241. // Scene optimizer tool
  27242. var SceneOptimizer = (function () {
  27243. function SceneOptimizer() {
  27244. }
  27245. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  27246. // TODO: add an epsilon
  27247. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  27248. if (onSuccess) {
  27249. onSuccess();
  27250. }
  27251. return;
  27252. }
  27253. // Apply current level of optimizations
  27254. var allDone = true;
  27255. var noOptimizationApplied = true;
  27256. for (var index = 0; index < options.optimizations.length; index++) {
  27257. var optimization = options.optimizations[index];
  27258. if (optimization.priority === currentPriorityLevel) {
  27259. noOptimizationApplied = false;
  27260. allDone = allDone && optimization.apply(scene);
  27261. }
  27262. }
  27263. // If no optimization was applied, this is a failure :(
  27264. if (noOptimizationApplied) {
  27265. if (onFailure) {
  27266. onFailure();
  27267. }
  27268. return;
  27269. }
  27270. // If all optimizations were done, move to next level
  27271. if (allDone) {
  27272. currentPriorityLevel++;
  27273. }
  27274. // Let's the system running for a specific amount of time before checking FPS
  27275. scene.executeWhenReady(function () {
  27276. setTimeout(function () {
  27277. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  27278. }, options.trackerDuration);
  27279. });
  27280. };
  27281. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  27282. if (!options) {
  27283. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  27284. }
  27285. // Let's the system running for a specific amount of time before checking FPS
  27286. scene.executeWhenReady(function () {
  27287. setTimeout(function () {
  27288. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  27289. }, options.trackerDuration);
  27290. });
  27291. };
  27292. return SceneOptimizer;
  27293. })();
  27294. BABYLON.SceneOptimizer = SceneOptimizer;
  27295. })(BABYLON || (BABYLON = {}));
  27296. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  27297. (function (BABYLON) {
  27298. var Internals;
  27299. (function (Internals) {
  27300. var MeshLODLevel = (function () {
  27301. function MeshLODLevel(distance, mesh) {
  27302. this.distance = distance;
  27303. this.mesh = mesh;
  27304. }
  27305. return MeshLODLevel;
  27306. })();
  27307. Internals.MeshLODLevel = MeshLODLevel;
  27308. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27309. })(BABYLON || (BABYLON = {}));
  27310. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  27311. (function (BABYLON) {
  27312. var AudioEngine = (function () {
  27313. function AudioEngine() {
  27314. this._audioContext = null;
  27315. this._audioContextInitialized = false;
  27316. this.canUseWebAudio = false;
  27317. this.WarnedWebAudioUnsupported = false;
  27318. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  27319. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  27320. this.canUseWebAudio = true;
  27321. }
  27322. }
  27323. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  27324. get: function () {
  27325. if (!this._audioContextInitialized) {
  27326. this._initializeAudioContext();
  27327. }
  27328. return this._audioContext;
  27329. },
  27330. enumerable: true,
  27331. configurable: true
  27332. });
  27333. AudioEngine.prototype._initializeAudioContext = function () {
  27334. try {
  27335. if (this.canUseWebAudio) {
  27336. this._audioContext = new AudioContext();
  27337. // create a global volume gain node
  27338. this.masterGain = this._audioContext.createGain();
  27339. this.masterGain.gain.value = 1;
  27340. this.masterGain.connect(this._audioContext.destination);
  27341. this._audioContextInitialized = true;
  27342. }
  27343. }
  27344. catch (e) {
  27345. this.canUseWebAudio = false;
  27346. BABYLON.Tools.Error("Web Audio: " + e.message);
  27347. }
  27348. };
  27349. AudioEngine.prototype.dispose = function () {
  27350. if (this.canUseWebAudio && this._audioContextInitialized) {
  27351. if (this._connectedAnalyser) {
  27352. this._connectedAnalyser.stopDebugCanvas();
  27353. this._connectedAnalyser.dispose();
  27354. this.masterGain.disconnect();
  27355. this.masterGain.connect(this._audioContext.destination);
  27356. this._connectedAnalyser = null;
  27357. }
  27358. this.masterGain.gain.value = 1;
  27359. }
  27360. this.WarnedWebAudioUnsupported = false;
  27361. };
  27362. AudioEngine.prototype.getGlobalVolume = function () {
  27363. if (this.canUseWebAudio && this._audioContextInitialized) {
  27364. return this.masterGain.gain.value;
  27365. }
  27366. else {
  27367. return -1;
  27368. }
  27369. };
  27370. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  27371. if (this.canUseWebAudio && this._audioContextInitialized) {
  27372. this.masterGain.gain.value = newVolume;
  27373. }
  27374. };
  27375. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  27376. if (this._connectedAnalyser) {
  27377. this._connectedAnalyser.stopDebugCanvas();
  27378. }
  27379. if (this.canUseWebAudio && this._audioContextInitialized) {
  27380. this._connectedAnalyser = analyser;
  27381. this.masterGain.disconnect();
  27382. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  27383. }
  27384. };
  27385. return AudioEngine;
  27386. })();
  27387. BABYLON.AudioEngine = AudioEngine;
  27388. })(BABYLON || (BABYLON = {}));
  27389. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  27390. (function (BABYLON) {
  27391. var Sound = (function () {
  27392. /**
  27393. * Create a sound and attach it to a scene
  27394. * @param name Name of your sound
  27395. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  27396. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  27397. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  27398. */
  27399. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  27400. var _this = this;
  27401. this.autoplay = false;
  27402. this.loop = false;
  27403. this.useCustomAttenuation = false;
  27404. this.spatialSound = false;
  27405. this.refDistance = 1;
  27406. this.rolloffFactor = 1;
  27407. this.maxDistance = 100;
  27408. this.distanceModel = "linear";
  27409. this._panningModel = "equalpower";
  27410. this._playbackRate = 1;
  27411. this._startTime = 0;
  27412. this._startOffset = 0;
  27413. this._position = BABYLON.Vector3.Zero();
  27414. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27415. this._volume = 1;
  27416. this._isLoaded = false;
  27417. this._isReadyToPlay = false;
  27418. this.isPlaying = false;
  27419. this.isPaused = false;
  27420. this._isDirectional = false;
  27421. // Used if you'd like to create a directional sound.
  27422. // If not set, the sound will be omnidirectional
  27423. this._coneInnerAngle = 360;
  27424. this._coneOuterAngle = 360;
  27425. this._coneOuterGain = 0;
  27426. this.name = name;
  27427. this._scene = scene;
  27428. this._readyToPlayCallback = readyToPlayCallback;
  27429. // Default custom attenuation function is a linear attenuation
  27430. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  27431. if (currentDistance < maxDistance) {
  27432. return currentVolume * (1 - currentDistance / maxDistance);
  27433. }
  27434. else {
  27435. return 0;
  27436. }
  27437. };
  27438. if (options) {
  27439. this.autoplay = options.autoplay || false;
  27440. this.loop = options.loop || false;
  27441. // if volume === 0, we need another way to check this option
  27442. if (options.volume !== undefined) {
  27443. this._volume = options.volume;
  27444. }
  27445. this.spatialSound = options.spatialSound || false;
  27446. this.maxDistance = options.maxDistance || 100;
  27447. this.useCustomAttenuation = options.useCustomAttenuation || false;
  27448. this.rolloffFactor = options.rolloffFactor || 1;
  27449. this.refDistance = options.refDistance || 1;
  27450. this.distanceModel = options.distanceModel || "linear";
  27451. this._playbackRate = options.playbackRate || 1;
  27452. }
  27453. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27454. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  27455. this._soundGain.gain.value = this._volume;
  27456. this._inputAudioNode = this._soundGain;
  27457. this._ouputAudioNode = this._soundGain;
  27458. if (this.spatialSound) {
  27459. this._createSpatialParameters();
  27460. }
  27461. this._scene.mainSoundTrack.AddSound(this);
  27462. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  27463. if (urlOrArrayBuffer) {
  27464. // If it's an URL
  27465. if (typeof (urlOrArrayBuffer) === "string") {
  27466. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  27467. _this._soundLoaded(data);
  27468. }, null, null, true);
  27469. }
  27470. else {
  27471. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  27472. this._soundLoaded(urlOrArrayBuffer);
  27473. }
  27474. else {
  27475. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  27476. }
  27477. }
  27478. }
  27479. }
  27480. else {
  27481. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  27482. this._scene.mainSoundTrack.AddSound(this);
  27483. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  27484. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  27485. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  27486. }
  27487. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  27488. if (this._readyToPlayCallback) {
  27489. window.setTimeout(function () {
  27490. _this._readyToPlayCallback();
  27491. }, 1000);
  27492. }
  27493. }
  27494. }
  27495. Sound.prototype.dispose = function () {
  27496. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27497. if (this.isPlaying) {
  27498. this.stop();
  27499. }
  27500. this._isReadyToPlay = false;
  27501. if (this.soundTrackId === -1) {
  27502. this._scene.mainSoundTrack.RemoveSound(this);
  27503. }
  27504. else {
  27505. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27506. }
  27507. if (this._soundGain) {
  27508. this._soundGain.disconnect();
  27509. this._soundGain = null;
  27510. }
  27511. if (this._soundPanner) {
  27512. this._soundPanner.disconnect();
  27513. this._soundPanner = null;
  27514. }
  27515. if (this._soundSource) {
  27516. this._soundSource.disconnect();
  27517. this._soundSource = null;
  27518. }
  27519. this._audioBuffer = null;
  27520. if (this._connectedMesh) {
  27521. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27522. this._connectedMesh = null;
  27523. }
  27524. }
  27525. };
  27526. Sound.prototype._soundLoaded = function (audioData) {
  27527. var _this = this;
  27528. this._isLoaded = true;
  27529. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27530. _this._audioBuffer = buffer;
  27531. _this._isReadyToPlay = true;
  27532. if (_this.autoplay) {
  27533. _this.play();
  27534. }
  27535. if (_this._readyToPlayCallback) {
  27536. _this._readyToPlayCallback();
  27537. }
  27538. }, function (error) {
  27539. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27540. });
  27541. };
  27542. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27543. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27544. this._audioBuffer = audioBuffer;
  27545. this._isReadyToPlay = true;
  27546. }
  27547. };
  27548. Sound.prototype.updateOptions = function (options) {
  27549. if (options) {
  27550. this.loop = options.loop || this.loop;
  27551. this.maxDistance = options.maxDistance || this.maxDistance;
  27552. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27553. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27554. this.refDistance = options.refDistance || this.refDistance;
  27555. this.distanceModel = options.distanceModel || this.distanceModel;
  27556. this._playbackRate = options.playbackRate || this._playbackRate;
  27557. }
  27558. };
  27559. Sound.prototype._createSpatialParameters = function () {
  27560. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27561. if (this._scene.headphone) {
  27562. this._panningModel = "HRTF";
  27563. }
  27564. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27565. if (this.useCustomAttenuation) {
  27566. // Tricks to disable in a way embedded Web Audio attenuation
  27567. this._soundPanner.distanceModel = "linear";
  27568. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27569. this._soundPanner.refDistance = 1;
  27570. this._soundPanner.rolloffFactor = 1;
  27571. this._soundPanner.panningModel = this._panningModel;
  27572. }
  27573. else {
  27574. this._soundPanner.distanceModel = this.distanceModel;
  27575. this._soundPanner.maxDistance = this.maxDistance;
  27576. this._soundPanner.refDistance = this.refDistance;
  27577. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27578. this._soundPanner.panningModel = this._panningModel;
  27579. }
  27580. this._soundPanner.connect(this._ouputAudioNode);
  27581. this._inputAudioNode = this._soundPanner;
  27582. }
  27583. };
  27584. Sound.prototype.switchPanningModelToHRTF = function () {
  27585. this._panningModel = "HRTF";
  27586. this._switchPanningModel();
  27587. };
  27588. Sound.prototype.switchPanningModelToEqualPower = function () {
  27589. this._panningModel = "equalpower";
  27590. this._switchPanningModel();
  27591. };
  27592. Sound.prototype._switchPanningModel = function () {
  27593. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27594. this._soundPanner.panningModel = this._panningModel;
  27595. }
  27596. };
  27597. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27598. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27599. this._ouputAudioNode.disconnect();
  27600. this._ouputAudioNode.connect(soundTrackAudioNode);
  27601. }
  27602. };
  27603. /**
  27604. * Transform this sound into a directional source
  27605. * @param coneInnerAngle Size of the inner cone in degree
  27606. * @param coneOuterAngle Size of the outer cone in degree
  27607. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27608. */
  27609. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27610. if (coneOuterAngle < coneInnerAngle) {
  27611. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27612. return;
  27613. }
  27614. this._coneInnerAngle = coneInnerAngle;
  27615. this._coneOuterAngle = coneOuterAngle;
  27616. this._coneOuterGain = coneOuterGain;
  27617. this._isDirectional = true;
  27618. if (this.isPlaying && this.loop) {
  27619. this.stop();
  27620. this.play();
  27621. }
  27622. };
  27623. Sound.prototype.setPosition = function (newPosition) {
  27624. this._position = newPosition;
  27625. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27626. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27627. }
  27628. };
  27629. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27630. this._localDirection = newLocalDirection;
  27631. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27632. this._updateDirection();
  27633. }
  27634. };
  27635. Sound.prototype._updateDirection = function () {
  27636. var mat = this._connectedMesh.getWorldMatrix();
  27637. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27638. direction.normalize();
  27639. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27640. };
  27641. Sound.prototype.updateDistanceFromListener = function () {
  27642. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27643. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27644. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27645. }
  27646. };
  27647. Sound.prototype.setAttenuationFunction = function (callback) {
  27648. this._customAttenuationFunction = callback;
  27649. };
  27650. /**
  27651. * Play the sound
  27652. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27653. */
  27654. Sound.prototype.play = function (time) {
  27655. var _this = this;
  27656. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27657. try {
  27658. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27659. if (!this._soundSource) {
  27660. if (this.spatialSound) {
  27661. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27662. if (this._isDirectional) {
  27663. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27664. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27665. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27666. if (this._connectedMesh) {
  27667. this._updateDirection();
  27668. }
  27669. else {
  27670. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27671. }
  27672. }
  27673. }
  27674. }
  27675. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27676. this._soundSource.buffer = this._audioBuffer;
  27677. this._soundSource.connect(this._inputAudioNode);
  27678. this._soundSource.loop = this.loop;
  27679. this._soundSource.playbackRate.value = this._playbackRate;
  27680. this._startTime = startTime;
  27681. this._soundSource.onended = function () {
  27682. _this._onended();
  27683. };
  27684. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27685. this.isPlaying = true;
  27686. this.isPaused = false;
  27687. }
  27688. catch (ex) {
  27689. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27690. }
  27691. }
  27692. };
  27693. Sound.prototype._onended = function () {
  27694. this.isPlaying = false;
  27695. if (this.onended) {
  27696. this.onended();
  27697. }
  27698. };
  27699. /**
  27700. * Stop the sound
  27701. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27702. */
  27703. Sound.prototype.stop = function (time) {
  27704. if (this.isPlaying) {
  27705. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27706. this._soundSource.stop(stopTime);
  27707. this.isPlaying = false;
  27708. }
  27709. };
  27710. Sound.prototype.pause = function () {
  27711. if (this.isPlaying) {
  27712. this.stop(0);
  27713. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27714. this.isPaused = true;
  27715. }
  27716. };
  27717. Sound.prototype.setVolume = function (newVolume, time) {
  27718. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27719. if (time) {
  27720. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27721. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27722. }
  27723. else {
  27724. this._soundGain.gain.value = newVolume;
  27725. }
  27726. }
  27727. this._volume = newVolume;
  27728. };
  27729. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27730. this._playbackRate = newPlaybackRate;
  27731. if (this.isPlaying) {
  27732. this._soundSource.playbackRate.value = this._playbackRate;
  27733. }
  27734. };
  27735. Sound.prototype.getVolume = function () {
  27736. return this._volume;
  27737. };
  27738. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27739. var _this = this;
  27740. this._connectedMesh = meshToConnectTo;
  27741. if (!this.spatialSound) {
  27742. this._createSpatialParameters();
  27743. this.spatialSound = true;
  27744. if (this.isPlaying && this.loop) {
  27745. this.stop();
  27746. this.play();
  27747. }
  27748. }
  27749. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27750. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27751. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27752. };
  27753. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27754. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27755. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27756. this._updateDirection();
  27757. }
  27758. };
  27759. return Sound;
  27760. })();
  27761. BABYLON.Sound = Sound;
  27762. })(BABYLON || (BABYLON = {}));
  27763. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27764. (function (BABYLON) {
  27765. var SoundTrack = (function () {
  27766. function SoundTrack(scene, options) {
  27767. this.id = -1;
  27768. this._isMainTrack = false;
  27769. this._scene = scene;
  27770. this._audioEngine = BABYLON.Engine.audioEngine;
  27771. this.soundCollection = new Array();
  27772. if (this._audioEngine.canUseWebAudio) {
  27773. this._trackGain = this._audioEngine.audioContext.createGain();
  27774. this._trackGain.connect(this._audioEngine.masterGain);
  27775. if (options) {
  27776. if (options.volume) {
  27777. this._trackGain.gain.value = options.volume;
  27778. }
  27779. if (options.mainTrack) {
  27780. this._isMainTrack = options.mainTrack;
  27781. }
  27782. }
  27783. }
  27784. if (!this._isMainTrack) {
  27785. this._scene.soundTracks.push(this);
  27786. this.id = this._scene.soundTracks.length - 1;
  27787. }
  27788. }
  27789. SoundTrack.prototype.dispose = function () {
  27790. if (this._audioEngine.canUseWebAudio) {
  27791. if (this._connectedAnalyser) {
  27792. this._connectedAnalyser.stopDebugCanvas();
  27793. }
  27794. while (this.soundCollection.length) {
  27795. this.soundCollection[0].dispose();
  27796. }
  27797. this._trackGain.disconnect();
  27798. this._trackGain = null;
  27799. }
  27800. };
  27801. SoundTrack.prototype.AddSound = function (sound) {
  27802. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27803. sound.connectToSoundTrackAudioNode(this._trackGain);
  27804. }
  27805. if (sound.soundTrackId) {
  27806. if (sound.soundTrackId === -1) {
  27807. this._scene.mainSoundTrack.RemoveSound(sound);
  27808. }
  27809. else {
  27810. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27811. }
  27812. }
  27813. this.soundCollection.push(sound);
  27814. sound.soundTrackId = this.id;
  27815. };
  27816. SoundTrack.prototype.RemoveSound = function (sound) {
  27817. var index = this.soundCollection.indexOf(sound);
  27818. if (index !== -1) {
  27819. this.soundCollection.splice(index, 1);
  27820. }
  27821. };
  27822. SoundTrack.prototype.setVolume = function (newVolume) {
  27823. if (this._audioEngine.canUseWebAudio) {
  27824. this._trackGain.gain.value = newVolume;
  27825. }
  27826. };
  27827. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27828. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27829. for (var i = 0; i < this.soundCollection.length; i++) {
  27830. this.soundCollection[i].switchPanningModelToHRTF();
  27831. }
  27832. }
  27833. };
  27834. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27835. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27836. for (var i = 0; i < this.soundCollection.length; i++) {
  27837. this.soundCollection[i].switchPanningModelToEqualPower();
  27838. }
  27839. }
  27840. };
  27841. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27842. if (this._connectedAnalyser) {
  27843. this._connectedAnalyser.stopDebugCanvas();
  27844. }
  27845. this._connectedAnalyser = analyser;
  27846. if (this._audioEngine.canUseWebAudio) {
  27847. this._trackGain.disconnect();
  27848. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27849. }
  27850. };
  27851. return SoundTrack;
  27852. })();
  27853. BABYLON.SoundTrack = SoundTrack;
  27854. })(BABYLON || (BABYLON = {}));
  27855. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27856. (function (BABYLON) {
  27857. var DebugLayer = (function () {
  27858. function DebugLayer(scene) {
  27859. var _this = this;
  27860. this._transformationMatrix = BABYLON.Matrix.Identity();
  27861. this._enabled = false;
  27862. this._labelsEnabled = false;
  27863. this._displayStatistics = true;
  27864. this._displayTree = false;
  27865. this._displayLogs = false;
  27866. this._identityMatrix = BABYLON.Matrix.Identity();
  27867. this.axisRatio = 0.02;
  27868. this.accentColor = "orange";
  27869. this._scene = scene;
  27870. this._syncPositions = function () {
  27871. var engine = _this._scene.getEngine();
  27872. var canvasRect = engine.getRenderingCanvasClientRect();
  27873. if (_this._showUI) {
  27874. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27875. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27876. _this._statsDiv.style.width = "400px";
  27877. _this._statsDiv.style.height = "auto";
  27878. _this._statsSubsetDiv.style.maxHeight = "240px";
  27879. _this._optionsDiv.style.left = "0px";
  27880. _this._optionsDiv.style.top = "10px";
  27881. _this._optionsDiv.style.width = "200px";
  27882. _this._optionsDiv.style.height = "auto";
  27883. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27884. _this._logDiv.style.left = "0px";
  27885. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27886. _this._logDiv.style.width = "600px";
  27887. _this._logDiv.style.height = "160px";
  27888. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27889. _this._treeDiv.style.top = "10px";
  27890. _this._treeDiv.style.width = "300px";
  27891. _this._treeDiv.style.height = "auto";
  27892. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27893. }
  27894. _this._globalDiv.style.left = canvasRect.left + "px";
  27895. _this._globalDiv.style.top = canvasRect.top + "px";
  27896. _this._drawingCanvas.style.left = "0px";
  27897. _this._drawingCanvas.style.top = "0px";
  27898. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27899. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27900. var devicePixelRatio = window.devicePixelRatio || 1;
  27901. var context = _this._drawingContext;
  27902. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27903. _this._ratio = devicePixelRatio / backingStoreRatio;
  27904. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27905. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27906. };
  27907. this._onCanvasClick = function (evt) {
  27908. _this._clickPosition = {
  27909. x: evt.clientX * _this._ratio,
  27910. y: evt.clientY * _this._ratio
  27911. };
  27912. };
  27913. this._syncUI = function () {
  27914. if (_this._showUI) {
  27915. if (_this._displayStatistics) {
  27916. _this._displayStats();
  27917. _this._statsDiv.style.display = "";
  27918. }
  27919. else {
  27920. _this._statsDiv.style.display = "none";
  27921. }
  27922. if (_this._displayLogs) {
  27923. _this._logDiv.style.display = "";
  27924. }
  27925. else {
  27926. _this._logDiv.style.display = "none";
  27927. }
  27928. if (_this._displayTree) {
  27929. _this._treeDiv.style.display = "";
  27930. if (_this._needToRefreshMeshesTree) {
  27931. _this._needToRefreshMeshesTree = false;
  27932. _this._refreshMeshesTreeContent();
  27933. }
  27934. }
  27935. else {
  27936. _this._treeDiv.style.display = "none";
  27937. }
  27938. }
  27939. };
  27940. this._syncData = function () {
  27941. if (_this._labelsEnabled || !_this._showUI) {
  27942. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27943. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27944. var engine = _this._scene.getEngine();
  27945. var viewport = _this._camera.viewport;
  27946. var globalViewport = viewport.toGlobal(engine);
  27947. // Meshes
  27948. var meshes = _this._camera.getActiveMeshes();
  27949. for (var index = 0; index < meshes.length; index++) {
  27950. var mesh = meshes.data[index];
  27951. var position = mesh.getBoundingInfo().boundingSphere.center;
  27952. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27953. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27954. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27955. }
  27956. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27957. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27958. mesh.renderOverlay = !mesh.renderOverlay;
  27959. }, function () {
  27960. return mesh.renderOverlay ? 'red' : 'black';
  27961. });
  27962. }
  27963. }
  27964. // Cameras
  27965. var cameras = _this._scene.cameras;
  27966. for (index = 0; index < cameras.length; index++) {
  27967. var camera = cameras[index];
  27968. if (camera === _this._camera) {
  27969. continue;
  27970. }
  27971. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27972. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27973. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27974. _this._camera.detachControl(engine.getRenderingCanvas());
  27975. _this._camera = camera;
  27976. _this._camera.attachControl(engine.getRenderingCanvas());
  27977. }, function () {
  27978. return "purple";
  27979. });
  27980. }
  27981. }
  27982. // Lights
  27983. var lights = _this._scene.lights;
  27984. for (index = 0; index < lights.length; index++) {
  27985. var light = lights[index];
  27986. if (light.position) {
  27987. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27988. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27989. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27990. light.setEnabled(!light.isEnabled());
  27991. }, function () {
  27992. return light.isEnabled() ? "orange" : "gray";
  27993. });
  27994. }
  27995. }
  27996. }
  27997. }
  27998. _this._clickPosition = undefined;
  27999. };
  28000. }
  28001. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28002. while (this._treeSubsetDiv.hasChildNodes()) {
  28003. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28004. }
  28005. // Add meshes
  28006. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28007. sortedArray.sort(function (a, b) {
  28008. if (a.name === b.name) {
  28009. return 0;
  28010. }
  28011. return (a.name > b.name) ? 1 : -1;
  28012. });
  28013. for (var index = 0; index < sortedArray.length; index++) {
  28014. var mesh = sortedArray[index];
  28015. if (!mesh.isEnabled()) {
  28016. continue;
  28017. }
  28018. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28019. m.isVisible = element.checked;
  28020. }, mesh);
  28021. }
  28022. };
  28023. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28024. this._drawingContext.beginPath();
  28025. this._drawingContext.moveTo(zero.x, zero.y);
  28026. this._drawingContext.lineTo(unit.x, unit.y);
  28027. this._drawingContext.strokeStyle = color;
  28028. this._drawingContext.lineWidth = 4;
  28029. this._drawingContext.stroke();
  28030. this._drawingContext.font = "normal 14px Segoe UI";
  28031. this._drawingContext.fillStyle = color;
  28032. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28033. };
  28034. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28035. var position = mesh.getBoundingInfo().boundingSphere.center;
  28036. var worldMatrix = mesh.getWorldMatrix();
  28037. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28038. var unit = (unprojectedVector.subtract(position)).length();
  28039. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28040. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28041. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28042. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28043. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28044. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28045. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28046. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28047. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28048. };
  28049. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28050. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28051. this._drawingContext.font = "normal 12px Segoe UI";
  28052. var textMetrics = this._drawingContext.measureText(text);
  28053. var centerX = projectedPosition.x - textMetrics.width / 2;
  28054. var centerY = projectedPosition.y;
  28055. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28056. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28057. onClick();
  28058. }
  28059. this._drawingContext.beginPath();
  28060. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28061. this._drawingContext.fillStyle = getFillStyle();
  28062. this._drawingContext.globalAlpha = 0.5;
  28063. this._drawingContext.fill();
  28064. this._drawingContext.globalAlpha = 1.0;
  28065. this._drawingContext.strokeStyle = '#FFFFFF';
  28066. this._drawingContext.lineWidth = 1;
  28067. this._drawingContext.stroke();
  28068. this._drawingContext.fillStyle = "#FFFFFF";
  28069. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28070. this._drawingContext.beginPath();
  28071. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28072. this._drawingContext.fill();
  28073. }
  28074. };
  28075. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28076. if (!this._clickPosition) {
  28077. return false;
  28078. }
  28079. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28080. return false;
  28081. }
  28082. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28083. return false;
  28084. }
  28085. return true;
  28086. };
  28087. DebugLayer.prototype.isVisible = function () {
  28088. return this._enabled;
  28089. };
  28090. DebugLayer.prototype.hide = function () {
  28091. if (!this._enabled) {
  28092. return;
  28093. }
  28094. this._enabled = false;
  28095. var engine = this._scene.getEngine();
  28096. this._scene.unregisterBeforeRender(this._syncData);
  28097. this._scene.unregisterAfterRender(this._syncUI);
  28098. document.body.removeChild(this._globalDiv);
  28099. window.removeEventListener("resize", this._syncPositions);
  28100. this._scene.forceShowBoundingBoxes = false;
  28101. this._scene.forceWireframe = false;
  28102. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28103. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28104. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28105. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28106. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28107. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28108. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28109. this._scene.shadowsEnabled = true;
  28110. this._scene.particlesEnabled = true;
  28111. this._scene.postProcessesEnabled = true;
  28112. this._scene.collisionsEnabled = true;
  28113. this._scene.lightsEnabled = true;
  28114. this._scene.texturesEnabled = true;
  28115. this._scene.lensFlaresEnabled = true;
  28116. this._scene.proceduralTexturesEnabled = true;
  28117. this._scene.renderTargetsEnabled = true;
  28118. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28119. };
  28120. DebugLayer.prototype.show = function (showUI, camera) {
  28121. if (showUI === void 0) { showUI = true; }
  28122. if (camera === void 0) { camera = null; }
  28123. if (this._enabled) {
  28124. return;
  28125. }
  28126. this._enabled = true;
  28127. if (camera) {
  28128. this._camera = camera;
  28129. }
  28130. else {
  28131. this._camera = this._scene.activeCamera;
  28132. }
  28133. this._showUI = showUI;
  28134. var engine = this._scene.getEngine();
  28135. this._globalDiv = document.createElement("div");
  28136. document.body.appendChild(this._globalDiv);
  28137. this._generateDOMelements();
  28138. window.addEventListener("resize", this._syncPositions);
  28139. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28140. this._syncPositions();
  28141. this._scene.registerBeforeRender(this._syncData);
  28142. this._scene.registerAfterRender(this._syncUI);
  28143. };
  28144. DebugLayer.prototype._clearLabels = function () {
  28145. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28146. for (var index = 0; index < this._scene.meshes.length; index++) {
  28147. var mesh = this._scene.meshes[index];
  28148. mesh.renderOverlay = false;
  28149. }
  28150. };
  28151. DebugLayer.prototype._generateheader = function (root, text) {
  28152. var header = document.createElement("div");
  28153. header.innerHTML = text + "&nbsp;";
  28154. header.style.textAlign = "right";
  28155. header.style.width = "100%";
  28156. header.style.color = "white";
  28157. header.style.backgroundColor = "Black";
  28158. header.style.padding = "5px 5px 4px 0px";
  28159. header.style.marginLeft = "-5px";
  28160. header.style.fontWeight = "bold";
  28161. root.appendChild(header);
  28162. };
  28163. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28164. var label = document.createElement("label");
  28165. label.innerHTML = title;
  28166. label.style.color = color;
  28167. root.appendChild(label);
  28168. root.appendChild(document.createElement("br"));
  28169. };
  28170. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28171. if (tag === void 0) { tag = null; }
  28172. var label = document.createElement("label");
  28173. var boundingBoxesCheckbox = document.createElement("input");
  28174. boundingBoxesCheckbox.type = "checkbox";
  28175. boundingBoxesCheckbox.checked = initialState;
  28176. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28177. task(evt.target, tag);
  28178. });
  28179. label.appendChild(boundingBoxesCheckbox);
  28180. var container = document.createElement("span");
  28181. var leftPart = document.createElement("span");
  28182. var rightPart = document.createElement("span");
  28183. rightPart.style.cssFloat = "right";
  28184. leftPart.innerHTML = leftTitle;
  28185. rightPart.innerHTML = rightTitle;
  28186. rightPart.style.fontSize = "12px";
  28187. rightPart.style.maxWidth = "200px";
  28188. container.appendChild(leftPart);
  28189. container.appendChild(rightPart);
  28190. label.appendChild(container);
  28191. root.appendChild(label);
  28192. root.appendChild(document.createElement("br"));
  28193. };
  28194. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28195. if (tag === void 0) { tag = null; }
  28196. var label = document.createElement("label");
  28197. var checkBox = document.createElement("input");
  28198. checkBox.type = "checkbox";
  28199. checkBox.checked = initialState;
  28200. checkBox.addEventListener("change", function (evt) {
  28201. task(evt.target, tag);
  28202. });
  28203. label.appendChild(checkBox);
  28204. label.appendChild(document.createTextNode(title));
  28205. root.appendChild(label);
  28206. root.appendChild(document.createElement("br"));
  28207. };
  28208. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28209. if (tag === void 0) { tag = null; }
  28210. var button = document.createElement("button");
  28211. button.innerHTML = title;
  28212. button.style.height = "24px";
  28213. button.style.color = "#444444";
  28214. button.style.border = "1px solid white";
  28215. button.className = "debugLayerButton";
  28216. button.addEventListener("click", function (evt) {
  28217. task(evt.target, tag);
  28218. });
  28219. root.appendChild(button);
  28220. root.appendChild(document.createElement("br"));
  28221. };
  28222. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28223. if (tag === void 0) { tag = null; }
  28224. var label = document.createElement("label");
  28225. var boundingBoxesRadio = document.createElement("input");
  28226. boundingBoxesRadio.type = "radio";
  28227. boundingBoxesRadio.name = name;
  28228. boundingBoxesRadio.checked = initialState;
  28229. boundingBoxesRadio.addEventListener("change", function (evt) {
  28230. task(evt.target, tag);
  28231. });
  28232. label.appendChild(boundingBoxesRadio);
  28233. label.appendChild(document.createTextNode(title));
  28234. root.appendChild(label);
  28235. root.appendChild(document.createElement("br"));
  28236. };
  28237. DebugLayer.prototype._generateDOMelements = function () {
  28238. var _this = this;
  28239. this._globalDiv.id = "DebugLayer";
  28240. this._globalDiv.style.position = "absolute";
  28241. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28242. this._globalDiv.style.fontSize = "14px";
  28243. this._globalDiv.style.color = "white";
  28244. // Drawing canvas
  28245. this._drawingCanvas = document.createElement("canvas");
  28246. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28247. this._drawingCanvas.style.position = "absolute";
  28248. this._drawingCanvas.style.pointerEvents = "none";
  28249. this._drawingContext = this._drawingCanvas.getContext("2d");
  28250. this._globalDiv.appendChild(this._drawingCanvas);
  28251. if (this._showUI) {
  28252. var background = "rgba(128, 128, 128, 0.4)";
  28253. var border = "rgb(180, 180, 180) solid 1px";
  28254. // Stats
  28255. this._statsDiv = document.createElement("div");
  28256. this._statsDiv.id = "DebugLayerStats";
  28257. this._statsDiv.style.border = border;
  28258. this._statsDiv.style.position = "absolute";
  28259. this._statsDiv.style.background = background;
  28260. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28261. this._generateheader(this._statsDiv, "STATISTICS");
  28262. this._statsSubsetDiv = document.createElement("div");
  28263. this._statsSubsetDiv.style.paddingTop = "5px";
  28264. this._statsSubsetDiv.style.paddingBottom = "5px";
  28265. this._statsSubsetDiv.style.overflowY = "auto";
  28266. this._statsDiv.appendChild(this._statsSubsetDiv);
  28267. // Tree
  28268. this._treeDiv = document.createElement("div");
  28269. this._treeDiv.id = "DebugLayerTree";
  28270. this._treeDiv.style.border = border;
  28271. this._treeDiv.style.position = "absolute";
  28272. this._treeDiv.style.background = background;
  28273. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28274. this._treeDiv.style.display = "none";
  28275. this._generateheader(this._treeDiv, "MESHES TREE");
  28276. this._treeSubsetDiv = document.createElement("div");
  28277. this._treeSubsetDiv.style.paddingTop = "5px";
  28278. this._treeSubsetDiv.style.paddingRight = "5px";
  28279. this._treeSubsetDiv.style.overflowY = "auto";
  28280. this._treeSubsetDiv.style.maxHeight = "300px";
  28281. this._treeDiv.appendChild(this._treeSubsetDiv);
  28282. this._needToRefreshMeshesTree = true;
  28283. // Logs
  28284. this._logDiv = document.createElement("div");
  28285. this._logDiv.style.border = border;
  28286. this._logDiv.id = "DebugLayerLogs";
  28287. this._logDiv.style.position = "absolute";
  28288. this._logDiv.style.background = background;
  28289. this._logDiv.style.padding = "0px 0px 0px 5px";
  28290. this._logDiv.style.display = "none";
  28291. this._generateheader(this._logDiv, "LOGS");
  28292. this._logSubsetDiv = document.createElement("div");
  28293. this._logSubsetDiv.style.height = "127px";
  28294. this._logSubsetDiv.style.paddingTop = "5px";
  28295. this._logSubsetDiv.style.overflowY = "auto";
  28296. this._logSubsetDiv.style.fontSize = "12px";
  28297. this._logSubsetDiv.style.fontFamily = "consolas";
  28298. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28299. this._logDiv.appendChild(this._logSubsetDiv);
  28300. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28301. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28302. };
  28303. // Options
  28304. this._optionsDiv = document.createElement("div");
  28305. this._optionsDiv.id = "DebugLayerOptions";
  28306. this._optionsDiv.style.border = border;
  28307. this._optionsDiv.style.position = "absolute";
  28308. this._optionsDiv.style.background = background;
  28309. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28310. this._optionsDiv.style.overflowY = "auto";
  28311. this._generateheader(this._optionsDiv, "OPTIONS");
  28312. this._optionsSubsetDiv = document.createElement("div");
  28313. this._optionsSubsetDiv.style.paddingTop = "5px";
  28314. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28315. this._optionsSubsetDiv.style.overflowY = "auto";
  28316. this._optionsSubsetDiv.style.maxHeight = "200px";
  28317. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28318. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28319. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  28320. _this._displayStatistics = element.checked;
  28321. });
  28322. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  28323. _this._displayLogs = element.checked;
  28324. });
  28325. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28326. _this._displayTree = element.checked;
  28327. _this._needToRefreshMeshesTree = true;
  28328. });
  28329. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28330. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28331. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  28332. _this._scene.forceShowBoundingBoxes = element.checked;
  28333. });
  28334. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28335. _this._labelsEnabled = element.checked;
  28336. if (!_this._labelsEnabled) {
  28337. _this._clearLabels();
  28338. }
  28339. });
  28340. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28341. if (element.checked) {
  28342. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28343. }
  28344. else {
  28345. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28346. }
  28347. });
  28348. ;
  28349. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28350. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28351. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28352. if (element.checked) {
  28353. _this._scene.forceWireframe = false;
  28354. _this._scene.forcePointsCloud = false;
  28355. }
  28356. });
  28357. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28358. if (element.checked) {
  28359. _this._scene.forceWireframe = true;
  28360. _this._scene.forcePointsCloud = false;
  28361. }
  28362. });
  28363. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28364. if (element.checked) {
  28365. _this._scene.forceWireframe = false;
  28366. _this._scene.forcePointsCloud = true;
  28367. }
  28368. });
  28369. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28370. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28371. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  28372. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  28373. });
  28374. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  28375. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  28376. });
  28377. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  28378. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  28379. });
  28380. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  28381. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  28382. });
  28383. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  28384. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  28385. });
  28386. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  28387. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  28388. });
  28389. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  28390. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  28391. });
  28392. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  28393. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  28394. });
  28395. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28396. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28397. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  28398. _this._scene.animationsEnabled = element.checked;
  28399. });
  28400. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  28401. _this._scene.collisionsEnabled = element.checked;
  28402. });
  28403. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  28404. _this._scene.fogEnabled = element.checked;
  28405. });
  28406. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  28407. _this._scene.lensFlaresEnabled = element.checked;
  28408. });
  28409. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  28410. _this._scene.lightsEnabled = element.checked;
  28411. });
  28412. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  28413. _this._scene.particlesEnabled = element.checked;
  28414. });
  28415. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  28416. _this._scene.postProcessesEnabled = element.checked;
  28417. });
  28418. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  28419. _this._scene.proceduralTexturesEnabled = element.checked;
  28420. });
  28421. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  28422. _this._scene.renderTargetsEnabled = element.checked;
  28423. });
  28424. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  28425. _this._scene.shadowsEnabled = element.checked;
  28426. });
  28427. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  28428. _this._scene.skeletonsEnabled = element.checked;
  28429. });
  28430. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  28431. _this._scene.spritesEnabled = element.checked;
  28432. });
  28433. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  28434. _this._scene.texturesEnabled = element.checked;
  28435. });
  28436. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28437. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28438. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28439. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28440. if (element.checked) {
  28441. _this._scene.headphone = true;
  28442. }
  28443. });
  28444. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28445. if (element.checked) {
  28446. _this._scene.headphone = false;
  28447. }
  28448. });
  28449. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28450. _this._scene.audioEnabled = !element.checked;
  28451. });
  28452. }
  28453. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28454. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28455. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  28456. _this._scene.dumpNextRenderTargets = true;
  28457. });
  28458. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28459. this._globalDiv.appendChild(this._statsDiv);
  28460. this._globalDiv.appendChild(this._logDiv);
  28461. this._globalDiv.appendChild(this._optionsDiv);
  28462. this._globalDiv.appendChild(this._treeDiv);
  28463. }
  28464. };
  28465. DebugLayer.prototype._displayStats = function () {
  28466. var scene = this._scene;
  28467. var engine = scene.getEngine();
  28468. var glInfo = engine.getGlInfo();
  28469. 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>";
  28470. if (this.customStatsFunction) {
  28471. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28472. }
  28473. };
  28474. return DebugLayer;
  28475. })();
  28476. BABYLON.DebugLayer = DebugLayer;
  28477. })(BABYLON || (BABYLON = {}));
  28478. //# sourceMappingURL=babylon.debugLayer.js.map
  28479. var BABYLON;
  28480. (function (BABYLON) {
  28481. var RawTexture = (function (_super) {
  28482. __extends(RawTexture, _super);
  28483. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  28484. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28485. if (invertY === void 0) { invertY = false; }
  28486. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28487. _super.call(this, null, scene, !generateMipMaps, invertY);
  28488. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  28489. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28490. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28491. }
  28492. // Statics
  28493. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28494. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28495. if (invertY === void 0) { invertY = false; }
  28496. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28497. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  28498. };
  28499. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28500. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28501. if (invertY === void 0) { invertY = false; }
  28502. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28503. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28504. };
  28505. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28506. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28507. if (invertY === void 0) { invertY = false; }
  28508. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28509. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28510. };
  28511. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28512. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28513. if (invertY === void 0) { invertY = false; }
  28514. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28515. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28516. };
  28517. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28518. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28519. if (invertY === void 0) { invertY = false; }
  28520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28521. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28522. };
  28523. return RawTexture;
  28524. })(BABYLON.Texture);
  28525. BABYLON.RawTexture = RawTexture;
  28526. })(BABYLON || (BABYLON = {}));
  28527. //# sourceMappingURL=babylon.rawTexture.js.map
  28528. var BABYLON;
  28529. (function (BABYLON) {
  28530. var IndexedVector2 = (function (_super) {
  28531. __extends(IndexedVector2, _super);
  28532. function IndexedVector2(original, index) {
  28533. _super.call(this, original.x, original.y);
  28534. this.index = index;
  28535. }
  28536. return IndexedVector2;
  28537. })(BABYLON.Vector2);
  28538. var PolygonPoints = (function () {
  28539. function PolygonPoints() {
  28540. this.elements = new Array();
  28541. }
  28542. PolygonPoints.prototype.add = function (originalPoints) {
  28543. var _this = this;
  28544. var result = new Array();
  28545. originalPoints.forEach(function (point) {
  28546. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28547. var newPoint = new IndexedVector2(point, _this.elements.length);
  28548. result.push(newPoint);
  28549. _this.elements.push(newPoint);
  28550. }
  28551. });
  28552. return result;
  28553. };
  28554. PolygonPoints.prototype.computeBounds = function () {
  28555. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28556. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28557. this.elements.forEach(function (point) {
  28558. // x
  28559. if (point.x < lmin.x) {
  28560. lmin.x = point.x;
  28561. }
  28562. else if (point.x > lmax.x) {
  28563. lmax.x = point.x;
  28564. }
  28565. // y
  28566. if (point.y < lmin.y) {
  28567. lmin.y = point.y;
  28568. }
  28569. else if (point.y > lmax.y) {
  28570. lmax.y = point.y;
  28571. }
  28572. });
  28573. return {
  28574. min: lmin,
  28575. max: lmax,
  28576. width: lmax.x - lmin.x,
  28577. height: lmax.y - lmin.y
  28578. };
  28579. };
  28580. return PolygonPoints;
  28581. })();
  28582. var Polygon = (function () {
  28583. function Polygon() {
  28584. }
  28585. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28586. return [
  28587. new BABYLON.Vector2(xmin, ymin),
  28588. new BABYLON.Vector2(xmax, ymin),
  28589. new BABYLON.Vector2(xmax, ymax),
  28590. new BABYLON.Vector2(xmin, ymax)
  28591. ];
  28592. };
  28593. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28594. if (cx === void 0) { cx = 0; }
  28595. if (cy === void 0) { cy = 0; }
  28596. if (numberOfSides === void 0) { numberOfSides = 32; }
  28597. var result = new Array();
  28598. var angle = 0;
  28599. var increment = (Math.PI * 2) / numberOfSides;
  28600. for (var i = 0; i < numberOfSides; i++) {
  28601. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28602. angle -= increment;
  28603. }
  28604. return result;
  28605. };
  28606. Polygon.Parse = function (input) {
  28607. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28608. var i, result = [];
  28609. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28610. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28611. }
  28612. return result;
  28613. };
  28614. Polygon.StartingAt = function (x, y) {
  28615. return BABYLON.Path2.StartingAt(x, y);
  28616. };
  28617. return Polygon;
  28618. })();
  28619. BABYLON.Polygon = Polygon;
  28620. var PolygonMeshBuilder = (function () {
  28621. function PolygonMeshBuilder(name, contours, scene) {
  28622. this._points = new PolygonPoints();
  28623. if (!("poly2tri" in window)) {
  28624. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28625. }
  28626. this._name = name;
  28627. this._scene = scene;
  28628. var points;
  28629. if (contours instanceof BABYLON.Path2) {
  28630. points = contours.getPoints();
  28631. }
  28632. else {
  28633. points = contours;
  28634. }
  28635. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28636. }
  28637. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28638. this._swctx.addHole(this._points.add(hole));
  28639. return this;
  28640. };
  28641. PolygonMeshBuilder.prototype.build = function (updatable) {
  28642. if (updatable === void 0) { updatable = false; }
  28643. var result = new BABYLON.Mesh(this._name, this._scene);
  28644. var normals = [];
  28645. var positions = [];
  28646. var uvs = [];
  28647. var bounds = this._points.computeBounds();
  28648. this._points.elements.forEach(function (p) {
  28649. normals.push(0, 1.0, 0);
  28650. positions.push(p.x, 0, p.y);
  28651. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28652. });
  28653. var indices = [];
  28654. this._swctx.triangulate();
  28655. this._swctx.getTriangles().forEach(function (triangle) {
  28656. triangle.getPoints().forEach(function (point) {
  28657. indices.push(point.index);
  28658. });
  28659. });
  28660. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  28661. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  28662. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  28663. result.setIndices(indices);
  28664. return result;
  28665. };
  28666. return PolygonMeshBuilder;
  28667. })();
  28668. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28669. })(BABYLON || (BABYLON = {}));
  28670. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28671. (function (BABYLON) {
  28672. var SimplificationSettings = (function () {
  28673. function SimplificationSettings(quality, distance, optimizeMesh) {
  28674. this.quality = quality;
  28675. this.distance = distance;
  28676. this.optimizeMesh = optimizeMesh;
  28677. }
  28678. return SimplificationSettings;
  28679. })();
  28680. BABYLON.SimplificationSettings = SimplificationSettings;
  28681. var SimplificationQueue = (function () {
  28682. function SimplificationQueue() {
  28683. this.running = false;
  28684. this._simplificationArray = [];
  28685. }
  28686. SimplificationQueue.prototype.addTask = function (task) {
  28687. this._simplificationArray.push(task);
  28688. };
  28689. SimplificationQueue.prototype.executeNext = function () {
  28690. var task = this._simplificationArray.pop();
  28691. if (task) {
  28692. this.running = true;
  28693. this.runSimplification(task);
  28694. }
  28695. else {
  28696. this.running = false;
  28697. }
  28698. };
  28699. SimplificationQueue.prototype.runSimplification = function (task) {
  28700. var _this = this;
  28701. if (task.parallelProcessing) {
  28702. //parallel simplifier
  28703. task.settings.forEach(function (setting) {
  28704. var simplifier = _this.getSimplifier(task);
  28705. simplifier.simplify(setting, function (newMesh) {
  28706. task.mesh.addLODLevel(setting.distance, newMesh);
  28707. newMesh.isVisible = true;
  28708. //check if it is the last
  28709. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28710. //all done, run the success callback.
  28711. task.successCallback();
  28712. }
  28713. _this.executeNext();
  28714. });
  28715. });
  28716. }
  28717. else {
  28718. //single simplifier.
  28719. var simplifier = this.getSimplifier(task);
  28720. var runDecimation = function (setting, callback) {
  28721. simplifier.simplify(setting, function (newMesh) {
  28722. task.mesh.addLODLevel(setting.distance, newMesh);
  28723. newMesh.isVisible = true;
  28724. //run the next quality level
  28725. callback();
  28726. });
  28727. };
  28728. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28729. runDecimation(task.settings[loop.index], function () {
  28730. loop.executeNext();
  28731. });
  28732. }, function () {
  28733. //execution ended, run the success callback.
  28734. if (task.successCallback) {
  28735. task.successCallback();
  28736. }
  28737. _this.executeNext();
  28738. });
  28739. }
  28740. };
  28741. SimplificationQueue.prototype.getSimplifier = function (task) {
  28742. switch (task.simplificationType) {
  28743. case 0 /* QUADRATIC */:
  28744. default:
  28745. return new QuadraticErrorSimplification(task.mesh);
  28746. }
  28747. };
  28748. return SimplificationQueue;
  28749. })();
  28750. BABYLON.SimplificationQueue = SimplificationQueue;
  28751. /**
  28752. * The implemented types of simplification.
  28753. * At the moment only Quadratic Error Decimation is implemented.
  28754. */
  28755. (function (SimplificationType) {
  28756. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28757. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28758. var SimplificationType = BABYLON.SimplificationType;
  28759. var DecimationTriangle = (function () {
  28760. function DecimationTriangle(vertices) {
  28761. this.vertices = vertices;
  28762. this.error = new Array(4);
  28763. this.deleted = false;
  28764. this.isDirty = false;
  28765. this.deletePending = false;
  28766. this.borderFactor = 0;
  28767. }
  28768. return DecimationTriangle;
  28769. })();
  28770. BABYLON.DecimationTriangle = DecimationTriangle;
  28771. var DecimationVertex = (function () {
  28772. function DecimationVertex(position, id) {
  28773. this.position = position;
  28774. this.id = id;
  28775. this.isBorder = true;
  28776. this.q = new QuadraticMatrix();
  28777. this.triangleCount = 0;
  28778. this.triangleStart = 0;
  28779. this.originalOffsets = [];
  28780. }
  28781. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28782. this.position.copyFrom(newPosition);
  28783. };
  28784. return DecimationVertex;
  28785. })();
  28786. BABYLON.DecimationVertex = DecimationVertex;
  28787. var QuadraticMatrix = (function () {
  28788. function QuadraticMatrix(data) {
  28789. this.data = new Array(10);
  28790. for (var i = 0; i < 10; ++i) {
  28791. if (data && data[i]) {
  28792. this.data[i] = data[i];
  28793. }
  28794. else {
  28795. this.data[i] = 0;
  28796. }
  28797. }
  28798. }
  28799. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28800. 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];
  28801. return det;
  28802. };
  28803. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28804. for (var i = 0; i < 10; ++i) {
  28805. this.data[i] += matrix.data[i];
  28806. }
  28807. };
  28808. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28809. for (var i = 0; i < 10; ++i) {
  28810. this.data[i] += data[i];
  28811. }
  28812. };
  28813. QuadraticMatrix.prototype.add = function (matrix) {
  28814. var m = new QuadraticMatrix();
  28815. for (var i = 0; i < 10; ++i) {
  28816. m.data[i] = this.data[i] + matrix.data[i];
  28817. }
  28818. return m;
  28819. };
  28820. QuadraticMatrix.FromData = function (a, b, c, d) {
  28821. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28822. };
  28823. //returning an array to avoid garbage collection
  28824. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28825. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28826. };
  28827. return QuadraticMatrix;
  28828. })();
  28829. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28830. var Reference = (function () {
  28831. function Reference(vertexId, triangleId) {
  28832. this.vertexId = vertexId;
  28833. this.triangleId = triangleId;
  28834. }
  28835. return Reference;
  28836. })();
  28837. BABYLON.Reference = Reference;
  28838. /**
  28839. * An implementation of the Quadratic Error simplification algorithm.
  28840. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28841. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28842. * @author RaananW
  28843. */
  28844. var QuadraticErrorSimplification = (function () {
  28845. function QuadraticErrorSimplification(_mesh) {
  28846. this._mesh = _mesh;
  28847. this.initialized = false;
  28848. this.syncIterations = 5000;
  28849. this.aggressiveness = 7;
  28850. this.decimationIterations = 100;
  28851. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28852. }
  28853. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28854. var _this = this;
  28855. this.initDecimatedMesh();
  28856. //iterating through the submeshes array, one after the other.
  28857. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28858. _this.initWithMesh(loop.index, function () {
  28859. _this.runDecimation(settings, loop.index, function () {
  28860. loop.executeNext();
  28861. });
  28862. }, settings.optimizeMesh);
  28863. }, function () {
  28864. setTimeout(function () {
  28865. successCallback(_this._reconstructedMesh);
  28866. }, 0);
  28867. });
  28868. };
  28869. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28870. var _this = this;
  28871. var gCount = 0;
  28872. triangle.vertices.forEach(function (vertex) {
  28873. var count = 0;
  28874. var vPos = vertex.position;
  28875. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28876. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28877. ++count;
  28878. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28879. ++count;
  28880. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28881. ++count;
  28882. if (count > 1) {
  28883. ++gCount;
  28884. }
  28885. ;
  28886. });
  28887. if (gCount > 1) {
  28888. console.log(triangle, gCount);
  28889. }
  28890. return gCount > 1;
  28891. };
  28892. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28893. var _this = this;
  28894. var targetCount = ~~(this.triangles.length * settings.quality);
  28895. var deletedTriangles = 0;
  28896. var triangleCount = this.triangles.length;
  28897. var iterationFunction = function (iteration, callback) {
  28898. setTimeout(function () {
  28899. if (iteration % 5 === 0) {
  28900. _this.updateMesh(iteration === 0);
  28901. }
  28902. for (var i = 0; i < _this.triangles.length; ++i) {
  28903. _this.triangles[i].isDirty = false;
  28904. }
  28905. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28906. var trianglesIterator = function (i) {
  28907. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28908. var t = _this.triangles[tIdx];
  28909. if (!t)
  28910. return;
  28911. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28912. return;
  28913. }
  28914. for (var j = 0; j < 3; ++j) {
  28915. if (t.error[j] < threshold) {
  28916. var deleted0 = [];
  28917. var deleted1 = [];
  28918. var v0 = t.vertices[j];
  28919. var v1 = t.vertices[(j + 1) % 3];
  28920. if (v0.isBorder !== v1.isBorder)
  28921. continue;
  28922. var p = BABYLON.Vector3.Zero();
  28923. var n = BABYLON.Vector3.Zero();
  28924. var uv = BABYLON.Vector2.Zero();
  28925. var color = new BABYLON.Color4(0, 0, 0, 1);
  28926. _this.calculateError(v0, v1, p, n, uv, color);
  28927. var delTr = [];
  28928. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28929. continue;
  28930. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28931. continue;
  28932. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28933. continue;
  28934. var uniqueArray = [];
  28935. delTr.forEach(function (deletedT) {
  28936. if (uniqueArray.indexOf(deletedT) === -1) {
  28937. deletedT.deletePending = true;
  28938. uniqueArray.push(deletedT);
  28939. }
  28940. });
  28941. if (uniqueArray.length % 2 != 0) {
  28942. continue;
  28943. }
  28944. v0.q = v1.q.add(v0.q);
  28945. v0.updatePosition(p);
  28946. var tStart = _this.references.length;
  28947. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28948. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28949. var tCount = _this.references.length - tStart;
  28950. if (tCount <= v0.triangleCount) {
  28951. if (tCount) {
  28952. for (var c = 0; c < tCount; c++) {
  28953. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28954. }
  28955. }
  28956. }
  28957. else {
  28958. v0.triangleStart = tStart;
  28959. }
  28960. v0.triangleCount = tCount;
  28961. break;
  28962. }
  28963. }
  28964. };
  28965. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28966. return (triangleCount - deletedTriangles <= targetCount);
  28967. });
  28968. }, 0);
  28969. };
  28970. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28971. if (triangleCount - deletedTriangles <= targetCount)
  28972. loop.breakLoop();
  28973. else {
  28974. iterationFunction(loop.index, function () {
  28975. loop.executeNext();
  28976. });
  28977. }
  28978. }, function () {
  28979. setTimeout(function () {
  28980. //reconstruct this part of the mesh
  28981. _this.reconstructMesh(submeshIndex);
  28982. successCallback();
  28983. }, 0);
  28984. });
  28985. };
  28986. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  28987. var _this = this;
  28988. this.vertices = [];
  28989. this.triangles = [];
  28990. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28991. var indices = this._mesh.getIndices();
  28992. var submesh = this._mesh.subMeshes[submeshIndex];
  28993. var findInVertices = function (positionToSearch) {
  28994. if (optimizeMesh) {
  28995. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  28996. if (_this.vertices[ii].position.equals(positionToSearch)) {
  28997. return _this.vertices[ii];
  28998. }
  28999. }
  29000. }
  29001. return null;
  29002. };
  29003. var vertexReferences = [];
  29004. var vertexInit = function (i) {
  29005. var offset = i + submesh.verticesStart;
  29006. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29007. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29008. vertex.originalOffsets.push(offset);
  29009. if (vertex.id == _this.vertices.length) {
  29010. _this.vertices.push(vertex);
  29011. }
  29012. vertexReferences.push(vertex.id);
  29013. };
  29014. //var totalVertices = mesh.getTotalVertices();
  29015. var totalVertices = submesh.verticesCount;
  29016. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29017. var indicesInit = function (i) {
  29018. var offset = (submesh.indexStart / 3) + i;
  29019. var pos = (offset * 3);
  29020. var i0 = indices[pos + 0];
  29021. var i1 = indices[pos + 1];
  29022. var i2 = indices[pos + 2];
  29023. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29024. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29025. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29026. var triangle = new DecimationTriangle([v0, v1, v2]);
  29027. triangle.originalOffset = pos;
  29028. _this.triangles.push(triangle);
  29029. };
  29030. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29031. _this.init(callback);
  29032. });
  29033. });
  29034. };
  29035. QuadraticErrorSimplification.prototype.init = function (callback) {
  29036. var _this = this;
  29037. var triangleInit1 = function (i) {
  29038. var t = _this.triangles[i];
  29039. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29040. for (var j = 0; j < 3; j++) {
  29041. 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))));
  29042. }
  29043. };
  29044. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29045. var triangleInit2 = function (i) {
  29046. var t = _this.triangles[i];
  29047. for (var j = 0; j < 3; ++j) {
  29048. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29049. }
  29050. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29051. };
  29052. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29053. _this.initialized = true;
  29054. callback();
  29055. });
  29056. });
  29057. };
  29058. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29059. var newTriangles = [];
  29060. var i;
  29061. for (i = 0; i < this.vertices.length; ++i) {
  29062. this.vertices[i].triangleCount = 0;
  29063. }
  29064. var t;
  29065. var j;
  29066. for (i = 0; i < this.triangles.length; ++i) {
  29067. if (!this.triangles[i].deleted) {
  29068. t = this.triangles[i];
  29069. for (j = 0; j < 3; ++j) {
  29070. t.vertices[j].triangleCount = 1;
  29071. }
  29072. newTriangles.push(t);
  29073. }
  29074. }
  29075. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  29076. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  29077. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  29078. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  29079. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29080. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29081. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29082. var vertexCount = 0;
  29083. for (i = 0; i < this.vertices.length; ++i) {
  29084. var vertex = this.vertices[i];
  29085. vertex.id = vertexCount;
  29086. if (vertex.triangleCount) {
  29087. vertex.originalOffsets.forEach(function (originalOffset) {
  29088. newPositionData.push(vertex.position.x);
  29089. newPositionData.push(vertex.position.y);
  29090. newPositionData.push(vertex.position.z);
  29091. newNormalData.push(normalData[originalOffset * 3]);
  29092. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29093. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29094. if (uvs && uvs.length) {
  29095. newUVsData.push(uvs[(originalOffset * 2)]);
  29096. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29097. }
  29098. else if (colorsData && colorsData.length) {
  29099. newColorsData.push(colorsData[(originalOffset * 4)]);
  29100. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29101. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29102. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29103. }
  29104. ++vertexCount;
  29105. });
  29106. }
  29107. }
  29108. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29109. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29110. var submeshesArray = this._reconstructedMesh.subMeshes;
  29111. this._reconstructedMesh.subMeshes = [];
  29112. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29113. var originalIndices = this._mesh.getIndices();
  29114. for (i = 0; i < newTriangles.length; ++i) {
  29115. var t = newTriangles[i];
  29116. //now get the new referencing point for each vertex
  29117. [0, 1, 2].forEach(function (idx) {
  29118. var id = originalIndices[t.originalOffset + idx];
  29119. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29120. if (offset < 0)
  29121. offset = 0;
  29122. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29123. });
  29124. }
  29125. //overwriting the old vertex buffers and indices.
  29126. this._reconstructedMesh.setIndices(newIndicesArray);
  29127. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29128. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29129. if (newUVsData.length > 0)
  29130. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29131. if (newColorsData.length > 0)
  29132. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29133. //create submesh
  29134. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29135. if (submeshIndex > 0) {
  29136. this._reconstructedMesh.subMeshes = [];
  29137. submeshesArray.forEach(function (submesh) {
  29138. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29139. });
  29140. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29141. }
  29142. };
  29143. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29144. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29145. this._reconstructedMesh.material = this._mesh.material;
  29146. this._reconstructedMesh.parent = this._mesh.parent;
  29147. this._reconstructedMesh.isVisible = false;
  29148. };
  29149. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29150. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29151. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29152. if (t.deleted)
  29153. continue;
  29154. var s = this.references[vertex1.triangleStart + i].vertexId;
  29155. var v1 = t.vertices[(s + 1) % 3];
  29156. var v2 = t.vertices[(s + 2) % 3];
  29157. if ((v1 === vertex2 || v2 === vertex2)) {
  29158. deletedArray[i] = true;
  29159. delTr.push(t);
  29160. continue;
  29161. }
  29162. var d1 = v1.position.subtract(point);
  29163. d1 = d1.normalize();
  29164. var d2 = v2.position.subtract(point);
  29165. d2 = d2.normalize();
  29166. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29167. return true;
  29168. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29169. deletedArray[i] = false;
  29170. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29171. return true;
  29172. }
  29173. return false;
  29174. };
  29175. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29176. var newDeleted = deletedTriangles;
  29177. for (var i = 0; i < vertex.triangleCount; ++i) {
  29178. var ref = this.references[vertex.triangleStart + i];
  29179. var t = this.triangles[ref.triangleId];
  29180. if (t.deleted)
  29181. continue;
  29182. if (deletedArray[i] && t.deletePending) {
  29183. t.deleted = true;
  29184. newDeleted++;
  29185. continue;
  29186. }
  29187. t.vertices[ref.vertexId] = origVertex;
  29188. t.isDirty = true;
  29189. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29190. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29191. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29192. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29193. this.references.push(ref);
  29194. }
  29195. return newDeleted;
  29196. };
  29197. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29198. for (var i = 0; i < this.vertices.length; ++i) {
  29199. var vCount = [];
  29200. var vId = [];
  29201. var v = this.vertices[i];
  29202. var j;
  29203. for (j = 0; j < v.triangleCount; ++j) {
  29204. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29205. for (var ii = 0; ii < 3; ii++) {
  29206. var ofs = 0;
  29207. var vv = triangle.vertices[ii];
  29208. while (ofs < vCount.length) {
  29209. if (vId[ofs] === vv.id)
  29210. break;
  29211. ++ofs;
  29212. }
  29213. if (ofs === vCount.length) {
  29214. vCount.push(1);
  29215. vId.push(vv.id);
  29216. }
  29217. else {
  29218. vCount[ofs]++;
  29219. }
  29220. }
  29221. }
  29222. for (j = 0; j < vCount.length; ++j) {
  29223. if (vCount[j] === 1) {
  29224. this.vertices[vId[j]].isBorder = true;
  29225. }
  29226. else {
  29227. this.vertices[vId[j]].isBorder = false;
  29228. }
  29229. }
  29230. }
  29231. };
  29232. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29233. if (identifyBorders === void 0) { identifyBorders = false; }
  29234. var i;
  29235. if (!identifyBorders) {
  29236. var newTrianglesVector = [];
  29237. for (i = 0; i < this.triangles.length; ++i) {
  29238. if (!this.triangles[i].deleted) {
  29239. newTrianglesVector.push(this.triangles[i]);
  29240. }
  29241. }
  29242. this.triangles = newTrianglesVector;
  29243. }
  29244. for (i = 0; i < this.vertices.length; ++i) {
  29245. this.vertices[i].triangleCount = 0;
  29246. this.vertices[i].triangleStart = 0;
  29247. }
  29248. var t;
  29249. var j;
  29250. var v;
  29251. for (i = 0; i < this.triangles.length; ++i) {
  29252. t = this.triangles[i];
  29253. for (j = 0; j < 3; ++j) {
  29254. v = t.vertices[j];
  29255. v.triangleCount++;
  29256. }
  29257. }
  29258. var tStart = 0;
  29259. for (i = 0; i < this.vertices.length; ++i) {
  29260. this.vertices[i].triangleStart = tStart;
  29261. tStart += this.vertices[i].triangleCount;
  29262. this.vertices[i].triangleCount = 0;
  29263. }
  29264. var newReferences = new Array(this.triangles.length * 3);
  29265. for (i = 0; i < this.triangles.length; ++i) {
  29266. t = this.triangles[i];
  29267. for (j = 0; j < 3; ++j) {
  29268. v = t.vertices[j];
  29269. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29270. v.triangleCount++;
  29271. }
  29272. }
  29273. this.references = newReferences;
  29274. if (identifyBorders) {
  29275. this.identifyBorder();
  29276. }
  29277. };
  29278. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29279. var x = point.x;
  29280. var y = point.y;
  29281. var z = point.z;
  29282. 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];
  29283. };
  29284. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29285. var q = vertex1.q.add(vertex2.q);
  29286. var border = vertex1.isBorder && vertex2.isBorder;
  29287. var error = 0;
  29288. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29289. if (qDet !== 0 && !border) {
  29290. if (!pointResult) {
  29291. pointResult = BABYLON.Vector3.Zero();
  29292. }
  29293. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29294. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29295. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29296. error = this.vertexError(q, pointResult);
  29297. }
  29298. else {
  29299. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29300. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29301. var error1 = this.vertexError(q, vertex1.position);
  29302. var error2 = this.vertexError(q, vertex2.position);
  29303. var error3 = this.vertexError(q, p3);
  29304. error = Math.min(error1, error2, error3);
  29305. if (error === error1) {
  29306. if (pointResult) {
  29307. pointResult.copyFrom(vertex1.position);
  29308. }
  29309. }
  29310. else if (error === error2) {
  29311. if (pointResult) {
  29312. pointResult.copyFrom(vertex2.position);
  29313. }
  29314. }
  29315. else {
  29316. if (pointResult) {
  29317. pointResult.copyFrom(p3);
  29318. }
  29319. }
  29320. }
  29321. return error;
  29322. };
  29323. return QuadraticErrorSimplification;
  29324. })();
  29325. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29326. })(BABYLON || (BABYLON = {}));
  29327. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  29328. (function (BABYLON) {
  29329. var Analyser = (function () {
  29330. function Analyser(scene) {
  29331. this.SMOOTHING = 0.75;
  29332. this.FFT_SIZE = 512;
  29333. this.BARGRAPHAMPLITUDE = 256;
  29334. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  29335. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  29336. this._scene = scene;
  29337. this._audioEngine = BABYLON.Engine.audioEngine;
  29338. if (this._audioEngine.canUseWebAudio) {
  29339. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  29340. this._webAudioAnalyser.minDecibels = -140;
  29341. this._webAudioAnalyser.maxDecibels = 0;
  29342. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29343. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29344. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  29345. }
  29346. }
  29347. Analyser.prototype.getFrequencyBinCount = function () {
  29348. if (this._audioEngine.canUseWebAudio) {
  29349. return this._webAudioAnalyser.frequencyBinCount;
  29350. }
  29351. else {
  29352. return 0;
  29353. }
  29354. };
  29355. Analyser.prototype.getByteFrequencyData = function () {
  29356. if (this._audioEngine.canUseWebAudio) {
  29357. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29358. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29359. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  29360. }
  29361. return this._byteFreqs;
  29362. };
  29363. Analyser.prototype.getByteTimeDomainData = function () {
  29364. if (this._audioEngine.canUseWebAudio) {
  29365. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29366. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29367. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  29368. }
  29369. return this._byteTime;
  29370. };
  29371. Analyser.prototype.getFloatFrequencyData = function () {
  29372. if (this._audioEngine.canUseWebAudio) {
  29373. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29374. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29375. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  29376. }
  29377. return this._floatFreqs;
  29378. };
  29379. Analyser.prototype.drawDebugCanvas = function () {
  29380. var _this = this;
  29381. if (this._audioEngine.canUseWebAudio) {
  29382. if (!this._debugCanvas) {
  29383. this._debugCanvas = document.createElement("canvas");
  29384. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  29385. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  29386. this._debugCanvas.style.position = "absolute";
  29387. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  29388. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  29389. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  29390. document.body.appendChild(this._debugCanvas);
  29391. this._registerFunc = function () {
  29392. _this.drawDebugCanvas();
  29393. };
  29394. this._scene.registerBeforeRender(this._registerFunc);
  29395. }
  29396. if (this._registerFunc) {
  29397. var workingArray = this.getByteFrequencyData();
  29398. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  29399. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  29400. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  29401. var value = workingArray[i];
  29402. var percent = value / this.BARGRAPHAMPLITUDE;
  29403. var height = this.DEBUGCANVASSIZE.height * percent;
  29404. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  29405. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  29406. var hue = i / this.getFrequencyBinCount() * 360;
  29407. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  29408. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  29409. }
  29410. }
  29411. }
  29412. };
  29413. Analyser.prototype.stopDebugCanvas = function () {
  29414. if (this._debugCanvas) {
  29415. this._scene.unregisterBeforeRender(this._registerFunc);
  29416. this._registerFunc = null;
  29417. document.body.removeChild(this._debugCanvas);
  29418. this._debugCanvas = null;
  29419. this._debugCanvasContext = null;
  29420. }
  29421. };
  29422. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  29423. if (this._audioEngine.canUseWebAudio) {
  29424. inputAudioNode.connect(this._webAudioAnalyser);
  29425. this._webAudioAnalyser.connect(outputAudioNode);
  29426. }
  29427. };
  29428. Analyser.prototype.dispose = function () {
  29429. if (this._audioEngine.canUseWebAudio) {
  29430. this._webAudioAnalyser.disconnect();
  29431. }
  29432. };
  29433. return Analyser;
  29434. })();
  29435. BABYLON.Analyser = Analyser;
  29436. })(BABYLON || (BABYLON = {}));
  29437. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  29438. (function (BABYLON) {
  29439. var DepthRenderer = (function () {
  29440. function DepthRenderer(scene, type) {
  29441. var _this = this;
  29442. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  29443. this._viewMatrix = BABYLON.Matrix.Zero();
  29444. this._projectionMatrix = BABYLON.Matrix.Zero();
  29445. this._transformMatrix = BABYLON.Matrix.Zero();
  29446. this._worldViewProjection = BABYLON.Matrix.Zero();
  29447. this._scene = scene;
  29448. var engine = scene.getEngine();
  29449. // Render target
  29450. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  29451. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29452. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29453. this._depthMap.refreshRate = 1;
  29454. this._depthMap.renderParticles = false;
  29455. this._depthMap.renderList = null;
  29456. // Custom render function
  29457. var renderSubMesh = function (subMesh) {
  29458. var mesh = subMesh.getRenderingMesh();
  29459. var scene = _this._scene;
  29460. var engine = scene.getEngine();
  29461. // Culling
  29462. engine.setState(subMesh.getMaterial().backFaceCulling);
  29463. // Managing instances
  29464. var batch = mesh._getInstancesRenderList(subMesh._id);
  29465. if (batch.mustReturn) {
  29466. return;
  29467. }
  29468. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29469. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29470. engine.enableEffect(_this._effect);
  29471. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  29472. var material = subMesh.getMaterial();
  29473. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29474. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  29475. // Alpha test
  29476. if (material && material.needAlphaTesting()) {
  29477. var alphaTexture = material.getAlphaTestTexture();
  29478. _this._effect.setTexture("diffuseSampler", alphaTexture);
  29479. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29480. }
  29481. // Bones
  29482. if (mesh.useBones) {
  29483. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29484. }
  29485. // Draw
  29486. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  29487. }
  29488. };
  29489. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  29490. var index;
  29491. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29492. renderSubMesh(opaqueSubMeshes.data[index]);
  29493. }
  29494. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29495. renderSubMesh(alphaTestSubMeshes.data[index]);
  29496. }
  29497. };
  29498. }
  29499. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29500. var defines = [];
  29501. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29502. var mesh = subMesh.getMesh();
  29503. var scene = mesh.getScene();
  29504. var material = subMesh.getMaterial();
  29505. // Alpha test
  29506. if (material && material.needAlphaTesting()) {
  29507. defines.push("#define ALPHATEST");
  29508. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29509. attribs.push(BABYLON.VertexBuffer.UVKind);
  29510. defines.push("#define UV1");
  29511. }
  29512. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29513. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29514. defines.push("#define UV2");
  29515. }
  29516. }
  29517. // Bones
  29518. if (mesh.useBones) {
  29519. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29520. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29521. defines.push("#define BONES");
  29522. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29523. }
  29524. // Instances
  29525. if (useInstances) {
  29526. defines.push("#define INSTANCES");
  29527. attribs.push("world0");
  29528. attribs.push("world1");
  29529. attribs.push("world2");
  29530. attribs.push("world3");
  29531. }
  29532. // Get correct effect
  29533. var join = defines.join("\n");
  29534. if (this._cachedDefines !== join) {
  29535. this._cachedDefines = join;
  29536. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29537. }
  29538. return this._effect.isReady();
  29539. };
  29540. DepthRenderer.prototype.getDepthMap = function () {
  29541. return this._depthMap;
  29542. };
  29543. // Methods
  29544. DepthRenderer.prototype.dispose = function () {
  29545. this._depthMap.dispose();
  29546. };
  29547. return DepthRenderer;
  29548. })();
  29549. BABYLON.DepthRenderer = DepthRenderer;
  29550. })(BABYLON || (BABYLON = {}));
  29551. //# sourceMappingURL=babylon.depthRenderer.js.map
  29552. var BABYLON;
  29553. (function (BABYLON) {
  29554. var SSAORenderingPipeline = (function (_super) {
  29555. __extends(SSAORenderingPipeline, _super);
  29556. /**
  29557. * @constructor
  29558. * @param {string} name - The rendering pipeline name
  29559. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29560. * @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 }
  29561. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29562. */
  29563. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29564. var _this = this;
  29565. _super.call(this, scene.getEngine(), name);
  29566. // Members
  29567. /**
  29568. * The PassPostProcess id in the pipeline that contains the original scene color
  29569. * @type {string}
  29570. */
  29571. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29572. /**
  29573. * The SSAO PostProcess id in the pipeline
  29574. * @type {string}
  29575. */
  29576. this.SSAORenderEffect = "SSAORenderEffect";
  29577. /**
  29578. * The horizontal blur PostProcess id in the pipeline
  29579. * @type {string}
  29580. */
  29581. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29582. /**
  29583. * The vertical blur PostProcess id in the pipeline
  29584. * @type {string}
  29585. */
  29586. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29587. /**
  29588. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29589. * @type {string}
  29590. */
  29591. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29592. /**
  29593. * The output strength of the SSAO post-process. Default value is 1.0.
  29594. * @type {number}
  29595. */
  29596. this.totalStrength = 1.0;
  29597. /**
  29598. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  29599. * @type {number}
  29600. */
  29601. this.radius = 0.0002;
  29602. /**
  29603. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29604. * Must not be equal to fallOff and superior to fallOff.
  29605. * Default value is 0.0075
  29606. * @type {number}
  29607. */
  29608. this.area = 0.0075;
  29609. /**
  29610. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29611. * Must not be equal to area and inferior to area.
  29612. * Default value is 0.0002
  29613. * @type {number}
  29614. */
  29615. this.fallOff = 0.0002;
  29616. this._firstUpdate = true;
  29617. this._scene = scene;
  29618. // Set up assets
  29619. this._createRandomTexture();
  29620. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29621. var ssaoRatio = ratio.ssaoRatio || ratio;
  29622. var combineRatio = ratio.combineRatio || ratio;
  29623. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29624. this._createSSAOPostProcess(ssaoRatio);
  29625. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29626. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29627. this._createSSAOCombinePostProcess(combineRatio);
  29628. // Set up pipeline
  29629. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29630. return _this._originalColorPostProcess;
  29631. }, true));
  29632. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29633. return _this._ssaoPostProcess;
  29634. }, true));
  29635. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29636. return _this._blurHPostProcess;
  29637. }, true));
  29638. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29639. return _this._blurVPostProcess;
  29640. }, true));
  29641. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29642. return _this._ssaoCombinePostProcess;
  29643. }, true));
  29644. // Finish
  29645. scene.postProcessRenderPipelineManager.addPipeline(this);
  29646. if (cameras)
  29647. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29648. }
  29649. // Public Methods
  29650. /**
  29651. * Returns the horizontal blur PostProcess
  29652. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29653. */
  29654. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29655. return this._blurHPostProcess;
  29656. };
  29657. /**
  29658. * Returns the vertical blur PostProcess
  29659. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29660. */
  29661. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29662. return this._blurVPostProcess;
  29663. };
  29664. /**
  29665. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29666. */
  29667. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29668. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29669. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29670. this._originalColorPostProcess = undefined;
  29671. this._ssaoPostProcess = undefined;
  29672. this._blurHPostProcess = undefined;
  29673. this._blurVPostProcess = undefined;
  29674. this._ssaoCombinePostProcess = undefined;
  29675. this._randomTexture.dispose();
  29676. if (disableDepthRender)
  29677. this._scene.disableDepthRenderer();
  29678. };
  29679. // Private Methods
  29680. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29681. var _this = this;
  29682. var sampleSphere = [
  29683. 0.5381,
  29684. 0.1856,
  29685. -0.4319,
  29686. 0.1379,
  29687. 0.2486,
  29688. 0.4430,
  29689. 0.3371,
  29690. 0.5679,
  29691. -0.0057,
  29692. -0.6999,
  29693. -0.0451,
  29694. -0.0019,
  29695. 0.0689,
  29696. -0.1598,
  29697. -0.8547,
  29698. 0.0560,
  29699. 0.0069,
  29700. -0.1843,
  29701. -0.0146,
  29702. 0.1402,
  29703. 0.0762,
  29704. 0.0100,
  29705. -0.1924,
  29706. -0.0344,
  29707. -0.3577,
  29708. -0.5301,
  29709. -0.4358,
  29710. -0.3169,
  29711. 0.1063,
  29712. 0.0158,
  29713. 0.0103,
  29714. -0.5869,
  29715. 0.0046,
  29716. -0.0897,
  29717. -0.4940,
  29718. 0.3287,
  29719. 0.7119,
  29720. -0.0154,
  29721. -0.0918,
  29722. -0.0533,
  29723. 0.0596,
  29724. -0.5411,
  29725. 0.0352,
  29726. -0.0631,
  29727. 0.5460,
  29728. -0.4776,
  29729. 0.2847,
  29730. -0.0271
  29731. ];
  29732. var samplesFactor = 1.0 / 16.0;
  29733. 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);
  29734. this._ssaoPostProcess.onApply = function (effect) {
  29735. if (_this._firstUpdate) {
  29736. effect.setArray3("sampleSphere", sampleSphere);
  29737. effect.setFloat("samplesFactor", samplesFactor);
  29738. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29739. _this._firstUpdate = false;
  29740. }
  29741. effect.setFloat("totalStrength", _this.totalStrength);
  29742. effect.setFloat("radius", _this.radius);
  29743. effect.setFloat("area", _this.area);
  29744. effect.setFloat("fallOff", _this.fallOff);
  29745. effect.setTexture("textureSampler", _this._depthTexture);
  29746. effect.setTexture("randomSampler", _this._randomTexture);
  29747. };
  29748. };
  29749. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29750. var _this = this;
  29751. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29752. this._ssaoCombinePostProcess.onApply = function (effect) {
  29753. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29754. };
  29755. };
  29756. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29757. var size = 512;
  29758. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29759. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29760. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29761. var context = this._randomTexture.getContext();
  29762. var rand = function (min, max) {
  29763. return Math.random() * (max - min) + min;
  29764. };
  29765. for (var x = 0; x < size; x++) {
  29766. for (var y = 0; y < size; y++) {
  29767. var randVector = BABYLON.Vector3.Zero();
  29768. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29769. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29770. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29771. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29772. context.fillRect(x, y, 1, 1);
  29773. }
  29774. }
  29775. this._randomTexture.update(false);
  29776. };
  29777. return SSAORenderingPipeline;
  29778. })(BABYLON.PostProcessRenderPipeline);
  29779. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29780. })(BABYLON || (BABYLON = {}));
  29781. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29782. var BABYLON;
  29783. (function (BABYLON) {
  29784. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29785. var VolumetricLightScatteringPostProcess = (function (_super) {
  29786. __extends(VolumetricLightScatteringPostProcess, _super);
  29787. /**
  29788. * @constructor
  29789. * @param {string} name - The post-process name
  29790. * @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)
  29791. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29792. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29793. * @param {number} samples - The post-process quality, default 100
  29794. * @param {number} samplingMode - The post-process filtering mode
  29795. * @param {BABYLON.Engine} engine - The babylon engine
  29796. * @param {boolean} reusable - If the post-process is reusable
  29797. */
  29798. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29799. var _this = this;
  29800. if (samples === void 0) { samples = 100; }
  29801. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29802. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29803. this._screenCoordinates = BABYLON.Vector2.Zero();
  29804. /**
  29805. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29806. * @type {boolean}
  29807. */
  29808. this.useCustomMeshPosition = false;
  29809. /**
  29810. * If the post-process should inverse the light scattering direction
  29811. * @type {boolean}
  29812. */
  29813. this.invert = true;
  29814. /**
  29815. * Array containing the excluded meshes not rendered in the internal pass
  29816. */
  29817. this.excludedMeshes = new Array();
  29818. this.exposure = 0.3;
  29819. this.decay = 0.96815;
  29820. this.weight = 0.58767;
  29821. this.density = 0.926;
  29822. var scene = camera.getScene();
  29823. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29824. // Configure mesh
  29825. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29826. // Configure
  29827. this._createPass(scene, ratio.passRatio || ratio);
  29828. this.onApply = function (effect) {
  29829. _this._updateMeshScreenCoordinates(scene);
  29830. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29831. effect.setFloat("exposure", _this.exposure);
  29832. effect.setFloat("decay", _this.decay);
  29833. effect.setFloat("weight", _this.weight);
  29834. effect.setFloat("density", _this.density);
  29835. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29836. };
  29837. }
  29838. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29839. var mesh = subMesh.getMesh();
  29840. var defines = [];
  29841. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29842. var material = subMesh.getMaterial();
  29843. var needUV = false;
  29844. // Render this.mesh as default
  29845. if (mesh === this.mesh) {
  29846. defines.push("#define BASIC_RENDER");
  29847. defines.push("#define NEED_UV");
  29848. needUV = true;
  29849. }
  29850. // Alpha test
  29851. if (material) {
  29852. if (material.needAlphaTesting() || mesh === this.mesh)
  29853. defines.push("#define ALPHATEST");
  29854. if (material.opacityTexture !== undefined) {
  29855. defines.push("#define OPACITY");
  29856. if (material.opacityTexture.getAlphaFromRGB)
  29857. defines.push("#define OPACITYRGB");
  29858. if (!needUV)
  29859. defines.push("#define NEED_UV");
  29860. }
  29861. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29862. attribs.push(BABYLON.VertexBuffer.UVKind);
  29863. defines.push("#define UV1");
  29864. }
  29865. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29866. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29867. defines.push("#define UV2");
  29868. }
  29869. }
  29870. // Bones
  29871. if (mesh.useBones) {
  29872. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29873. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29874. defines.push("#define BONES");
  29875. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29876. }
  29877. // Instances
  29878. if (useInstances) {
  29879. defines.push("#define INSTANCES");
  29880. attribs.push("world0");
  29881. attribs.push("world1");
  29882. attribs.push("world2");
  29883. attribs.push("world3");
  29884. }
  29885. // Get correct effect
  29886. var join = defines.join("\n");
  29887. if (this._cachedDefines !== join) {
  29888. this._cachedDefines = join;
  29889. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29890. }
  29891. return this._volumetricLightScatteringPass.isReady();
  29892. };
  29893. /**
  29894. * Sets the new light position for light scattering effect
  29895. * @param {BABYLON.Vector3} The new custom light position
  29896. */
  29897. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29898. this._customMeshPosition = position;
  29899. };
  29900. /**
  29901. * Returns the light position for light scattering effect
  29902. * @return {BABYLON.Vector3} The custom light position
  29903. */
  29904. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29905. return this._customMeshPosition;
  29906. };
  29907. /**
  29908. * Disposes the internal assets and detaches the post-process from the camera
  29909. */
  29910. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29911. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29912. if (rttIndex !== -1) {
  29913. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29914. }
  29915. this._volumetricLightScatteringRTT.dispose();
  29916. _super.prototype.dispose.call(this, camera);
  29917. };
  29918. /**
  29919. * Returns the render target texture used by the post-process
  29920. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29921. */
  29922. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29923. return this._volumetricLightScatteringRTT;
  29924. };
  29925. // Private methods
  29926. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29927. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29928. return true;
  29929. }
  29930. return false;
  29931. };
  29932. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29933. var _this = this;
  29934. var engine = scene.getEngine();
  29935. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29936. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29937. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29938. this._volumetricLightScatteringRTT.renderList = null;
  29939. this._volumetricLightScatteringRTT.renderParticles = false;
  29940. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29941. // Custom render function for submeshes
  29942. var renderSubMesh = function (subMesh) {
  29943. var mesh = subMesh.getRenderingMesh();
  29944. if (_this._meshExcluded(mesh)) {
  29945. return;
  29946. }
  29947. var scene = mesh.getScene();
  29948. var engine = scene.getEngine();
  29949. // Culling
  29950. engine.setState(subMesh.getMaterial().backFaceCulling);
  29951. // Managing instances
  29952. var batch = mesh._getInstancesRenderList(subMesh._id);
  29953. if (batch.mustReturn) {
  29954. return;
  29955. }
  29956. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29957. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29958. engine.enableEffect(_this._volumetricLightScatteringPass);
  29959. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29960. var material = subMesh.getMaterial();
  29961. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29962. // Alpha test
  29963. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29964. var alphaTexture = material.getAlphaTestTexture();
  29965. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29966. if (alphaTexture) {
  29967. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29968. }
  29969. if (material.opacityTexture !== undefined) {
  29970. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29971. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  29972. }
  29973. }
  29974. // Bones
  29975. if (mesh.useBones) {
  29976. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29977. }
  29978. // Draw
  29979. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29980. }
  29981. };
  29982. // Render target texture callbacks
  29983. var savedSceneClearColor;
  29984. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  29985. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29986. savedSceneClearColor = scene.clearColor;
  29987. scene.clearColor = sceneClearColor;
  29988. };
  29989. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29990. scene.clearColor = savedSceneClearColor;
  29991. };
  29992. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29993. var engine = scene.getEngine();
  29994. var index;
  29995. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29996. renderSubMesh(opaqueSubMeshes.data[index]);
  29997. }
  29998. engine.setAlphaTesting(true);
  29999. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30000. renderSubMesh(alphaTestSubMeshes.data[index]);
  30001. }
  30002. engine.setAlphaTesting(false);
  30003. if (transparentSubMeshes.length) {
  30004. for (index = 0; index < transparentSubMeshes.length; index++) {
  30005. var submesh = transparentSubMeshes.data[index];
  30006. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  30007. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  30008. }
  30009. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  30010. sortedArray.sort(function (a, b) {
  30011. // Alpha index first
  30012. if (a._alphaIndex > b._alphaIndex) {
  30013. return 1;
  30014. }
  30015. if (a._alphaIndex < b._alphaIndex) {
  30016. return -1;
  30017. }
  30018. // Then distance to camera
  30019. if (a._distanceToCamera < b._distanceToCamera) {
  30020. return 1;
  30021. }
  30022. if (a._distanceToCamera > b._distanceToCamera) {
  30023. return -1;
  30024. }
  30025. return 0;
  30026. });
  30027. // Render sub meshes
  30028. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  30029. for (index = 0; index < sortedArray.length; index++) {
  30030. renderSubMesh(sortedArray[index]);
  30031. }
  30032. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30033. }
  30034. };
  30035. };
  30036. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  30037. var transform = scene.getTransformMatrix();
  30038. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  30039. this._screenCoordinates.x = pos.x / this._viewPort.width;
  30040. this._screenCoordinates.y = pos.y / this._viewPort.height;
  30041. if (this.invert)
  30042. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  30043. };
  30044. // Static methods
  30045. /**
  30046. * Creates a default mesh for the Volumeric Light Scattering post-process
  30047. * @param {string} The mesh name
  30048. * @param {BABYLON.Scene} The scene where to create the mesh
  30049. * @return {BABYLON.Mesh} the default mesh
  30050. */
  30051. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  30052. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  30053. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  30054. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  30055. return mesh;
  30056. };
  30057. return VolumetricLightScatteringPostProcess;
  30058. })(BABYLON.PostProcess);
  30059. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  30060. })(BABYLON || (BABYLON = {}));
  30061. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  30062. var BABYLON;
  30063. (function (BABYLON) {
  30064. var LensRenderingPipeline = (function (_super) {
  30065. __extends(LensRenderingPipeline, _super);
  30066. /**
  30067. * @constructor
  30068. *
  30069. * Effect parameters are as follow:
  30070. * {
  30071. * chromatic_aberration: number; // from 0 to x (1 for realism)
  30072. * edge_blur: number; // from 0 to x (1 for realism)
  30073. * distortion: number; // from 0 to x (1 for realism)
  30074. * grain_amount: number; // from 0 to 1
  30075. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  30076. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  30077. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  30078. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  30079. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  30080. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  30081. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  30082. * }
  30083. * Note: if an effect parameter is unset, effect is disabled
  30084. *
  30085. * @param {string} name - The rendering pipeline name
  30086. * @param {object} parameters - An object containing all parameters (see above)
  30087. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30088. * @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)
  30089. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30090. */
  30091. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  30092. var _this = this;
  30093. if (ratio === void 0) { ratio = 1.0; }
  30094. _super.call(this, scene.getEngine(), name);
  30095. // Lens effects can be of the following:
  30096. // - chromatic aberration (slight shift of RGB colors)
  30097. // - blur on the edge of the lens
  30098. // - lens distortion
  30099. // - depth-of-field blur & highlights enhancing
  30100. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  30101. // - grain effect (noise or custom texture)
  30102. // Two additional texture samplers are needed:
  30103. // - depth map (for depth-of-field)
  30104. // - grain texture
  30105. /**
  30106. * The chromatic aberration PostProcess id in the pipeline
  30107. * @type {string}
  30108. */
  30109. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  30110. /**
  30111. * The highlights enhancing PostProcess id in the pipeline
  30112. * @type {string}
  30113. */
  30114. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  30115. /**
  30116. * The depth-of-field PostProcess id in the pipeline
  30117. * @type {string}
  30118. */
  30119. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  30120. this._scene = scene;
  30121. // Fetch texture samplers
  30122. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30123. if (parameters.grain_texture) {
  30124. this._grainTexture = parameters.grain_texture;
  30125. }
  30126. else {
  30127. this._createGrainTexture();
  30128. }
  30129. // save parameters
  30130. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  30131. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  30132. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  30133. this._distortion = parameters.distortion ? parameters.distortion : 0;
  30134. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  30135. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  30136. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  30137. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  30138. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  30139. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  30140. // Create effects
  30141. this._createChromaticAberrationPostProcess(ratio);
  30142. this._createHighlightsPostProcess(ratio);
  30143. this._createDepthOfFieldPostProcess(ratio);
  30144. // Set up pipeline
  30145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  30146. return _this._chromaticAberrationPostProcess;
  30147. }, true));
  30148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  30149. return _this._highlightsPostProcess;
  30150. }, true));
  30151. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  30152. return _this._depthOfFieldPostProcess;
  30153. }, true));
  30154. if (this._highlightsGain == -1) {
  30155. this._disableEffect(this.HighlightsEnhancingEffect, null);
  30156. }
  30157. // Finish
  30158. scene.postProcessRenderPipelineManager.addPipeline(this);
  30159. if (cameras) {
  30160. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30161. }
  30162. }
  30163. // public methods (self explanatory)
  30164. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  30165. this._edgeBlur = amount;
  30166. };
  30167. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  30168. this._edgeBlur = 0;
  30169. };
  30170. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  30171. this._grainAmount = amount;
  30172. };
  30173. LensRenderingPipeline.prototype.disableGrain = function () {
  30174. this._grainAmount = 0;
  30175. };
  30176. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  30177. this._chromaticAberration = amount;
  30178. };
  30179. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  30180. this._chromaticAberration = 0;
  30181. };
  30182. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  30183. this._distortion = amount;
  30184. };
  30185. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  30186. this._distortion = 0;
  30187. };
  30188. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  30189. this._dofDepth = amount;
  30190. };
  30191. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  30192. this._dofDepth = -1;
  30193. };
  30194. LensRenderingPipeline.prototype.setAperture = function (amount) {
  30195. this._dofAperture = amount;
  30196. };
  30197. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  30198. this._dofPentagon = true;
  30199. };
  30200. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  30201. this._dofPentagon = false;
  30202. };
  30203. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  30204. this._blurNoise = true;
  30205. };
  30206. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  30207. this._blurNoise = false;
  30208. };
  30209. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  30210. this._highlightsGain = amount;
  30211. };
  30212. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  30213. if (this._highlightsGain == -1) {
  30214. this._highlightsGain = 1.0;
  30215. }
  30216. this._highlightsThreshold = amount;
  30217. };
  30218. LensRenderingPipeline.prototype.disableHighlights = function () {
  30219. this._highlightsGain = -1;
  30220. };
  30221. /**
  30222. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  30223. */
  30224. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30225. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30226. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30227. this._chromaticAberrationPostProcess = undefined;
  30228. this._highlightsPostProcess = undefined;
  30229. this._depthOfFieldPostProcess = undefined;
  30230. this._grainTexture.dispose();
  30231. if (disableDepthRender)
  30232. this._scene.disableDepthRenderer();
  30233. };
  30234. // colors shifting and distortion
  30235. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  30236. var _this = this;
  30237. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30238. this._chromaticAberrationPostProcess.onApply = function (effect) {
  30239. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  30240. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30241. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30242. };
  30243. };
  30244. // highlights enhancing
  30245. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  30246. var _this = this;
  30247. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30248. this._highlightsPostProcess.onApply = function (effect) {
  30249. effect.setFloat('gain', _this._highlightsGain);
  30250. effect.setFloat('threshold', _this._highlightsThreshold);
  30251. effect.setBool('pentagon', _this._dofPentagon);
  30252. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  30253. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30254. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30255. };
  30256. };
  30257. // colors shifting and distortion
  30258. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  30259. var _this = this;
  30260. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  30261. "focus_depth",
  30262. "aperture",
  30263. "pentagon",
  30264. "maxZ",
  30265. "edge_blur",
  30266. "chromatic_aberration",
  30267. "distortion",
  30268. "blur_noise",
  30269. "grain_amount",
  30270. "screen_width",
  30271. "screen_height",
  30272. "highlights"
  30273. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30274. this._depthOfFieldPostProcess.onApply = function (effect) {
  30275. effect.setBool('blur_noise', _this._blurNoise);
  30276. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  30277. effect.setFloat('grain_amount', _this._grainAmount);
  30278. effect.setTexture("depthSampler", _this._depthTexture);
  30279. effect.setTexture("grainSampler", _this._grainTexture);
  30280. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  30281. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  30282. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30283. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30284. effect.setFloat('distortion', _this._distortion);
  30285. effect.setFloat('focus_depth', _this._dofDepth);
  30286. effect.setFloat('aperture', _this._dofAperture);
  30287. effect.setFloat('edge_blur', _this._edgeBlur);
  30288. effect.setBool('highlights', (_this._highlightsGain != -1));
  30289. };
  30290. };
  30291. // creates a black and white random noise texture, 512x512
  30292. LensRenderingPipeline.prototype._createGrainTexture = function () {
  30293. var size = 512;
  30294. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30295. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30296. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30297. var context = this._grainTexture.getContext();
  30298. var rand = function (min, max) {
  30299. return Math.random() * (max - min) + min;
  30300. };
  30301. var value;
  30302. for (var x = 0; x < size; x++) {
  30303. for (var y = 0; y < size; y++) {
  30304. value = Math.floor(rand(0.42, 0.58) * 255);
  30305. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  30306. context.fillRect(x, y, 1, 1);
  30307. }
  30308. }
  30309. this._grainTexture.update(false);
  30310. };
  30311. return LensRenderingPipeline;
  30312. })(BABYLON.PostProcessRenderPipeline);
  30313. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  30314. })(BABYLON || (BABYLON = {}));
  30315. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  30316. // This post-process allows the modification of rendered colors by using
  30317. // a 'look-up table' (LUT). This effect is also called Color Grading.
  30318. //
  30319. // The object needs to be provided an url to a texture containing the color
  30320. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  30321. // Use an image editing software to tweak the LUT to match your needs.
  30322. //
  30323. // For an example of a color LUT, see here:
  30324. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  30325. // For explanations on color grading, see here:
  30326. // http://udn.epicgames.com/Three/ColorGrading.html
  30327. //
  30328. var BABYLON;
  30329. (function (BABYLON) {
  30330. var ColorCorrectionPostProcess = (function (_super) {
  30331. __extends(ColorCorrectionPostProcess, _super);
  30332. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  30333. var _this = this;
  30334. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  30335. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  30336. this._colorTableTexture.anisotropicFilteringLevel = 1;
  30337. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30338. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30339. this.onApply = function (effect) {
  30340. effect.setTexture("colorTable", _this._colorTableTexture);
  30341. };
  30342. }
  30343. return ColorCorrectionPostProcess;
  30344. })(BABYLON.PostProcess);
  30345. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  30346. })(BABYLON || (BABYLON = {}));
  30347. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  30348. (function (BABYLON) {
  30349. var SmartCollection = (function () {
  30350. function SmartCollection(capacity) {
  30351. if (capacity === void 0) { capacity = 10; }
  30352. this.count = 0;
  30353. this._initialCapacity = capacity;
  30354. this.items = {};
  30355. this._keys = new Array(this._initialCapacity);
  30356. }
  30357. SmartCollection.prototype.add = function (key, item) {
  30358. if (this.items[key] != undefined) {
  30359. return -1;
  30360. }
  30361. this.items[key] = item;
  30362. //literal keys are always strings, but we keep source type of key in _keys array
  30363. this._keys[this.count++] = key;
  30364. if (this.count > this._keys.length) {
  30365. this._keys.length *= 2;
  30366. }
  30367. return this.count;
  30368. };
  30369. SmartCollection.prototype.remove = function (key) {
  30370. if (this.items[key] == undefined) {
  30371. return -1;
  30372. }
  30373. return this.removeItemOfIndex(this.indexOf(key));
  30374. };
  30375. SmartCollection.prototype.removeItemOfIndex = function (index) {
  30376. if (index < this.count && index > -1) {
  30377. delete this.items[this._keys[index]];
  30378. while (index < this.count) {
  30379. this._keys[index] = this._keys[index + 1];
  30380. index++;
  30381. }
  30382. }
  30383. else {
  30384. return -1;
  30385. }
  30386. return --this.count;
  30387. };
  30388. SmartCollection.prototype.indexOf = function (key) {
  30389. for (var i = 0; i !== this.count; i++) {
  30390. if (this._keys[i] === key) {
  30391. return i;
  30392. }
  30393. }
  30394. return -1;
  30395. };
  30396. SmartCollection.prototype.item = function (key) {
  30397. return this.items[key];
  30398. };
  30399. SmartCollection.prototype.getAllKeys = function () {
  30400. if (this.count > 0) {
  30401. var keys = new Array(this.count);
  30402. for (var i = 0; i < this.count; i++) {
  30403. keys[i] = this._keys[i];
  30404. }
  30405. return keys;
  30406. }
  30407. else {
  30408. return undefined;
  30409. }
  30410. };
  30411. SmartCollection.prototype.getKeyByIndex = function (index) {
  30412. if (index < this.count && index > -1) {
  30413. return this._keys[index];
  30414. }
  30415. else {
  30416. return undefined;
  30417. }
  30418. };
  30419. SmartCollection.prototype.getItemByIndex = function (index) {
  30420. if (index < this.count && index > -1) {
  30421. return this.items[this._keys[index]];
  30422. }
  30423. else {
  30424. return undefined;
  30425. }
  30426. };
  30427. SmartCollection.prototype.empty = function () {
  30428. if (this.count > 0) {
  30429. this.count = 0;
  30430. this.items = {};
  30431. this._keys = new Array(this._initialCapacity);
  30432. }
  30433. };
  30434. SmartCollection.prototype.forEach = function (block) {
  30435. var key;
  30436. for (key in this.items) {
  30437. if (this.items.hasOwnProperty(key)) {
  30438. block(this.items[key]);
  30439. }
  30440. }
  30441. };
  30442. return SmartCollection;
  30443. })();
  30444. BABYLON.SmartCollection = SmartCollection;
  30445. })(BABYLON || (BABYLON = {}));
  30446. //# sourceMappingURL=babylon.smartCollection.js.map