babylon.max.js 1.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443
  1. var __extends = (this && 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. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  680. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  681. var m0 = SIMD.float32x4.load(transformation.m, 0);
  682. var m1 = SIMD.float32x4.load(transformation.m, 4);
  683. var m2 = SIMD.float32x4.load(transformation.m, 8);
  684. var m3 = SIMD.float32x4.load(transformation.m, 12);
  685. 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));
  686. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  687. SIMD.float32x4.storeXYZ(result._data, 0, r);
  688. };
  689. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  690. var v0 = SIMD.float32x4.splat(x);
  691. var v1 = SIMD.float32x4.splat(y);
  692. var v2 = SIMD.float32x4.splat(z);
  693. var m0 = SIMD.float32x4.load(transformation.m, 0);
  694. var m1 = SIMD.float32x4.load(transformation.m, 4);
  695. var m2 = SIMD.float32x4.load(transformation.m, 8);
  696. var m3 = SIMD.float32x4.load(transformation.m, 12);
  697. 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));
  698. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  699. SIMD.float32x4.storeXYZ(result._data, 0, r);
  700. };
  701. Vector3.TransformNormal = function (vector, transformation) {
  702. var result = Vector3.Zero();
  703. Vector3.TransformNormalToRef(vector, transformation, result);
  704. return result;
  705. };
  706. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  707. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  708. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  709. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  710. };
  711. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  712. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  713. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  714. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  715. };
  716. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  717. var squared = amount * amount;
  718. var cubed = amount * squared;
  719. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  720. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  721. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  722. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  723. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  724. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  725. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  726. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  727. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  728. return new Vector3(x, y, z);
  729. };
  730. Vector3.Clamp = function (value, min, max) {
  731. var x = value.x;
  732. x = (x > max.x) ? max.x : x;
  733. x = (x < min.x) ? min.x : x;
  734. var y = value.y;
  735. y = (y > max.y) ? max.y : y;
  736. y = (y < min.y) ? min.y : y;
  737. var z = value.z;
  738. z = (z > max.z) ? max.z : z;
  739. z = (z < min.z) ? min.z : z;
  740. return new Vector3(x, y, z);
  741. };
  742. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  743. var squared = amount * amount;
  744. var cubed = amount * squared;
  745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  747. var part3 = (cubed - (2.0 * squared)) + amount;
  748. var part4 = cubed - squared;
  749. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  750. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  751. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  752. return new Vector3(x, y, z);
  753. };
  754. Vector3.Lerp = function (start, end, amount) {
  755. var x = start.x + ((end.x - start.x) * amount);
  756. var y = start.y + ((end.y - start.y) * amount);
  757. var z = start.z + ((end.z - start.z) * amount);
  758. return new Vector3(x, y, z);
  759. };
  760. Vector3.Dot = function (left, right) {
  761. return (left.x * right.x + left.y * right.y + left.z * right.z);
  762. };
  763. Vector3.Cross = function (left, right) {
  764. var result = Vector3.Zero();
  765. Vector3.CrossToRef(left, right, result);
  766. return result;
  767. };
  768. Vector3.CrossToRef = function (left, right, result) {
  769. result.x = left.y * right.z - left.z * right.y;
  770. result.y = left.z * right.x - left.x * right.z;
  771. result.z = left.x * right.y - left.y * right.x;
  772. };
  773. Vector3.Normalize = function (vector) {
  774. var result = Vector3.Zero();
  775. Vector3.NormalizeToRef(vector, result);
  776. return result;
  777. };
  778. Vector3.NormalizeToRef = function (vector, result) {
  779. result.copyFrom(vector);
  780. result.normalize();
  781. };
  782. Vector3.Project = function (vector, world, transform, viewport) {
  783. var cw = viewport.width;
  784. var ch = viewport.height;
  785. var cx = viewport.x;
  786. var cy = viewport.y;
  787. 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);
  788. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  789. return Vector3.TransformCoordinates(vector, finalMatrix);
  790. };
  791. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  792. var matrix = world.multiply(transform);
  793. matrix.invert();
  794. source.x = source.x / viewportWidth * 2 - 1;
  795. source.y = -(source.y / viewportHeight * 2 - 1);
  796. var vector = Vector3.TransformCoordinates(source, matrix);
  797. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  798. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  799. vector = vector.scale(1.0 / num);
  800. }
  801. return vector;
  802. };
  803. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  804. var matrix = world.multiply(view).multiply(projection);
  805. matrix.invert();
  806. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  807. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  808. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  809. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  810. vector = vector.scale(1.0 / num);
  811. }
  812. return vector;
  813. };
  814. Vector3.Minimize = function (left, right) {
  815. var min = left.clone();
  816. min.MinimizeInPlace(right);
  817. return min;
  818. };
  819. Vector3.Maximize = function (left, right) {
  820. var max = left.clone();
  821. max.MaximizeInPlace(right);
  822. return max;
  823. };
  824. Vector3.Distance = function (value1, value2) {
  825. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  826. };
  827. Vector3.DistanceSquared = function (value1, value2) {
  828. var x = value1.x - value2.x;
  829. var y = value1.y - value2.y;
  830. var z = value1.z - value2.z;
  831. return (x * x) + (y * y) + (z * z);
  832. };
  833. Vector3.Center = function (value1, value2) {
  834. var center = value1.add(value2);
  835. center.scaleInPlace(0.5);
  836. return center;
  837. };
  838. /**
  839. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  840. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  841. * to something in order to rotate it from its local system to the given target system.
  842. */
  843. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  844. var rotation = Vector3.Zero();
  845. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  846. return rotation;
  847. };
  848. /**
  849. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  850. */
  851. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  852. var u = Vector3.Normalize(axis1);
  853. var w = Vector3.Normalize(axis3);
  854. // world axis
  855. var X = Axis.X;
  856. var Y = Axis.Y;
  857. // equation unknowns and vars
  858. var yaw = 0.0;
  859. var pitch = 0.0;
  860. var roll = 0.0;
  861. var x = 0.0;
  862. var y = 0.0;
  863. var z = 0.0;
  864. var t = 0.0;
  865. var sign = -1.0;
  866. var nbRevert = 0;
  867. var cross;
  868. var dot = 0.0;
  869. // step 1 : rotation around w
  870. // Rv3(u) = u1, and u1 belongs to plane xOz
  871. // Rv3(w) = w1 = w invariant
  872. var u1;
  873. var v1;
  874. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  875. z = 1.0;
  876. }
  877. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  878. x = 1.0;
  879. }
  880. else {
  881. t = w.z / w.x;
  882. x = -t * Math.sqrt(1 / (1 + t * t));
  883. z = Math.sqrt(1 / (1 + t * t));
  884. }
  885. u1 = new Vector3(x, y, z);
  886. u1.normalize();
  887. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  888. v1.normalize();
  889. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  890. cross.normalize();
  891. if (Vector3.Dot(w, cross) < 0) {
  892. sign = 1.0;
  893. }
  894. dot = Vector3.Dot(u, u1);
  895. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  896. roll = Math.acos(dot) * sign;
  897. if (Vector3.Dot(u1, X) < 0) {
  898. roll = Math.PI + roll;
  899. u1 = u1.scaleInPlace(-1);
  900. v1 = v1.scaleInPlace(-1);
  901. nbRevert++;
  902. }
  903. // step 2 : rotate around u1
  904. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  905. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  906. var w2;
  907. var v2;
  908. x = 0.0;
  909. y = 0.0;
  910. z = 0.0;
  911. sign = -1;
  912. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  913. x = 1.0;
  914. }
  915. else {
  916. t = u1.z / u1.x;
  917. x = -t * Math.sqrt(1 / (1 + t * t));
  918. z = Math.sqrt(1 / (1 + t * t));
  919. }
  920. w2 = new Vector3(x, y, z);
  921. w2.normalize();
  922. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  923. v2.normalize();
  924. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  925. cross.normalize();
  926. if (Vector3.Dot(u1, cross) < 0) {
  927. sign = 1.0;
  928. }
  929. dot = Vector3.Dot(w, w2);
  930. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  931. pitch = Math.acos(dot) * sign;
  932. if (Vector3.Dot(v2, Y) < 0) {
  933. pitch = Math.PI + pitch;
  934. v2 = v2.scaleInPlace(-1);
  935. w2 = w2.scaleInPlace(-1);
  936. nbRevert++;
  937. }
  938. // step 3 : rotate around v2
  939. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  940. sign = -1;
  941. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(cross, Y) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(u1, X);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  949. if (dot < 0 && nbRevert < 2) {
  950. yaw = Math.PI + yaw;
  951. }
  952. ref.x = pitch;
  953. ref.y = yaw;
  954. ref.z = roll;
  955. };
  956. return Vector3;
  957. })();
  958. BABYLON.Vector3 = Vector3;
  959. //Vector4 class created for EulerAngle class conversion to Quaternion
  960. var Vector4 = (function () {
  961. function Vector4(x, y, z, w) {
  962. this.x = x;
  963. this.y = y;
  964. this.z = z;
  965. this.w = w;
  966. }
  967. Vector4.prototype.toString = function () {
  968. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  969. };
  970. // Operators
  971. Vector4.prototype.asArray = function () {
  972. var result = [];
  973. this.toArray(result, 0);
  974. return result;
  975. };
  976. Vector4.prototype.toArray = function (array, index) {
  977. if (index === undefined) {
  978. index = 0;
  979. }
  980. array[index] = this.x;
  981. array[index + 1] = this.y;
  982. array[index + 2] = this.z;
  983. array[index + 3] = this.w;
  984. return this;
  985. };
  986. Vector4.prototype.addInPlace = function (otherVector) {
  987. this.x += otherVector.x;
  988. this.y += otherVector.y;
  989. this.z += otherVector.z;
  990. this.w += otherVector.w;
  991. return this;
  992. };
  993. Vector4.prototype.add = function (otherVector) {
  994. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  995. };
  996. Vector4.prototype.addToRef = function (otherVector, result) {
  997. result.x = this.x + otherVector.x;
  998. result.y = this.y + otherVector.y;
  999. result.z = this.z + otherVector.z;
  1000. result.w = this.w + otherVector.w;
  1001. return this;
  1002. };
  1003. Vector4.prototype.subtractInPlace = function (otherVector) {
  1004. this.x -= otherVector.x;
  1005. this.y -= otherVector.y;
  1006. this.z -= otherVector.z;
  1007. this.w -= otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.subtract = function (otherVector) {
  1011. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1012. };
  1013. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1014. result.x = this.x - otherVector.x;
  1015. result.y = this.y - otherVector.y;
  1016. result.z = this.z - otherVector.z;
  1017. result.w = this.w - otherVector.w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1021. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1022. };
  1023. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1024. result.x = this.x - x;
  1025. result.y = this.y - y;
  1026. result.z = this.z - z;
  1027. result.w = this.w - w;
  1028. return this;
  1029. };
  1030. Vector4.prototype.negate = function () {
  1031. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1032. };
  1033. Vector4.prototype.scaleInPlace = function (scale) {
  1034. this.x *= scale;
  1035. this.y *= scale;
  1036. this.z *= scale;
  1037. this.w *= scale;
  1038. return this;
  1039. };
  1040. Vector4.prototype.scale = function (scale) {
  1041. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1042. };
  1043. Vector4.prototype.scaleToRef = function (scale, result) {
  1044. result.x = this.x * scale;
  1045. result.y = this.y * scale;
  1046. result.z = this.z * scale;
  1047. result.w = this.w * scale;
  1048. };
  1049. Vector4.prototype.equals = function (otherVector) {
  1050. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1051. };
  1052. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1053. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1054. return otherVector
  1055. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1056. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1057. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1058. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1059. };
  1060. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1061. return this.x === x && this.y === y && this.z === z && this.w === w;
  1062. };
  1063. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1064. this.x *= otherVector.x;
  1065. this.y *= otherVector.y;
  1066. this.z *= otherVector.z;
  1067. this.w *= otherVector.w;
  1068. return this;
  1069. };
  1070. Vector4.prototype.multiply = function (otherVector) {
  1071. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1072. };
  1073. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1074. result.x = this.x * otherVector.x;
  1075. result.y = this.y * otherVector.y;
  1076. result.z = this.z * otherVector.z;
  1077. result.w = this.w * otherVector.w;
  1078. return this;
  1079. };
  1080. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1081. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1082. };
  1083. Vector4.prototype.divide = function (otherVector) {
  1084. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1085. };
  1086. Vector4.prototype.divideToRef = function (otherVector, result) {
  1087. result.x = this.x / otherVector.x;
  1088. result.y = this.y / otherVector.y;
  1089. result.z = this.z / otherVector.z;
  1090. result.w = this.w / otherVector.w;
  1091. return this;
  1092. };
  1093. Vector4.prototype.MinimizeInPlace = function (other) {
  1094. if (other.x < this.x)
  1095. this.x = other.x;
  1096. if (other.y < this.y)
  1097. this.y = other.y;
  1098. if (other.z < this.z)
  1099. this.z = other.z;
  1100. if (other.w < this.w)
  1101. this.w = other.w;
  1102. return this;
  1103. };
  1104. Vector4.prototype.MaximizeInPlace = function (other) {
  1105. if (other.x > this.x)
  1106. this.x = other.x;
  1107. if (other.y > this.y)
  1108. this.y = other.y;
  1109. if (other.z > this.z)
  1110. this.z = other.z;
  1111. if (other.w > this.w)
  1112. this.w = other.w;
  1113. return this;
  1114. };
  1115. // Properties
  1116. Vector4.prototype.length = function () {
  1117. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1118. };
  1119. Vector4.prototype.lengthSquared = function () {
  1120. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1121. };
  1122. // Methods
  1123. Vector4.prototype.normalize = function () {
  1124. var len = this.length();
  1125. if (len === 0)
  1126. return this;
  1127. var num = 1.0 / len;
  1128. this.x *= num;
  1129. this.y *= num;
  1130. this.z *= num;
  1131. this.w *= num;
  1132. return this;
  1133. };
  1134. Vector4.prototype.clone = function () {
  1135. return new Vector4(this.x, this.y, this.z, this.w);
  1136. };
  1137. Vector4.prototype.copyFrom = function (source) {
  1138. this.x = source.x;
  1139. this.y = source.y;
  1140. this.z = source.z;
  1141. this.w = source.w;
  1142. return this;
  1143. };
  1144. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1145. this.x = x;
  1146. this.y = y;
  1147. this.z = z;
  1148. this.w = w;
  1149. return this;
  1150. };
  1151. // Statics
  1152. Vector4.FromArray = function (array, offset) {
  1153. if (!offset) {
  1154. offset = 0;
  1155. }
  1156. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1157. };
  1158. Vector4.FromArrayToRef = function (array, offset, result) {
  1159. result.x = array[offset];
  1160. result.y = array[offset + 1];
  1161. result.z = array[offset + 2];
  1162. result.w = array[offset + 3];
  1163. };
  1164. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1165. result.x = array[offset];
  1166. result.y = array[offset + 1];
  1167. result.z = array[offset + 2];
  1168. result.w = array[offset + 3];
  1169. };
  1170. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1171. result.x = x;
  1172. result.y = y;
  1173. result.z = z;
  1174. result.w = w;
  1175. };
  1176. Vector4.Zero = function () {
  1177. return new Vector4(0, 0, 0, 0);
  1178. };
  1179. Vector4.Normalize = function (vector) {
  1180. var result = Vector4.Zero();
  1181. Vector4.NormalizeToRef(vector, result);
  1182. return result;
  1183. };
  1184. Vector4.NormalizeToRef = function (vector, result) {
  1185. result.copyFrom(vector);
  1186. result.normalize();
  1187. };
  1188. Vector4.Minimize = function (left, right) {
  1189. var min = left.clone();
  1190. min.MinimizeInPlace(right);
  1191. return min;
  1192. };
  1193. Vector4.Maximize = function (left, right) {
  1194. var max = left.clone();
  1195. max.MaximizeInPlace(right);
  1196. return max;
  1197. };
  1198. Vector4.Distance = function (value1, value2) {
  1199. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1200. };
  1201. Vector4.DistanceSquared = function (value1, value2) {
  1202. var x = value1.x - value2.x;
  1203. var y = value1.y - value2.y;
  1204. var z = value1.z - value2.z;
  1205. var w = value1.w - value2.w;
  1206. return (x * x) + (y * y) + (z * z) + (w * w);
  1207. };
  1208. Vector4.Center = function (value1, value2) {
  1209. var center = value1.add(value2);
  1210. center.scaleInPlace(0.5);
  1211. return center;
  1212. };
  1213. return Vector4;
  1214. })();
  1215. BABYLON.Vector4 = Vector4;
  1216. var Quaternion = (function () {
  1217. function Quaternion(x, y, z, w) {
  1218. if (x === void 0) { x = 0; }
  1219. if (y === void 0) { y = 0; }
  1220. if (z === void 0) { z = 0; }
  1221. if (w === void 0) { w = 1; }
  1222. this.x = x;
  1223. this.y = y;
  1224. this.z = z;
  1225. this.w = w;
  1226. }
  1227. Quaternion.prototype.toString = function () {
  1228. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1229. };
  1230. Quaternion.prototype.asArray = function () {
  1231. return [this.x, this.y, this.z, this.w];
  1232. };
  1233. Quaternion.prototype.equals = function (otherQuaternion) {
  1234. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1235. };
  1236. Quaternion.prototype.clone = function () {
  1237. return new Quaternion(this.x, this.y, this.z, this.w);
  1238. };
  1239. Quaternion.prototype.copyFrom = function (other) {
  1240. this.x = other.x;
  1241. this.y = other.y;
  1242. this.z = other.z;
  1243. this.w = other.w;
  1244. return this;
  1245. };
  1246. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1247. this.x = x;
  1248. this.y = y;
  1249. this.z = z;
  1250. this.w = w;
  1251. return this;
  1252. };
  1253. Quaternion.prototype.add = function (other) {
  1254. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1255. };
  1256. Quaternion.prototype.subtract = function (other) {
  1257. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1258. };
  1259. Quaternion.prototype.scale = function (value) {
  1260. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1261. };
  1262. Quaternion.prototype.multiply = function (q1) {
  1263. var result = new Quaternion(0, 0, 0, 1.0);
  1264. this.multiplyToRef(q1, result);
  1265. return result;
  1266. };
  1267. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1268. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1269. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1270. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1271. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1272. result.copyFromFloats(x, y, z, w);
  1273. return this;
  1274. };
  1275. Quaternion.prototype.length = function () {
  1276. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1277. };
  1278. Quaternion.prototype.normalize = function () {
  1279. var length = 1.0 / this.length();
  1280. this.x *= length;
  1281. this.y *= length;
  1282. this.z *= length;
  1283. this.w *= length;
  1284. return this;
  1285. };
  1286. Quaternion.prototype.toEulerAngles = function () {
  1287. var result = Vector3.Zero();
  1288. this.toEulerAnglesToRef(result);
  1289. return result;
  1290. };
  1291. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1292. //result is an EulerAngles in the in the z-x-z convention
  1293. var qx = this.x;
  1294. var qy = this.y;
  1295. var qz = this.z;
  1296. var qw = this.w;
  1297. var qxy = qx * qy;
  1298. var qxz = qx * qz;
  1299. var qwy = qw * qy;
  1300. var qwz = qw * qz;
  1301. var qwx = qw * qx;
  1302. var qyz = qy * qz;
  1303. var sqx = qx * qx;
  1304. var sqy = qy * qy;
  1305. var determinant = sqx + sqy;
  1306. if (determinant !== 0.000 && determinant !== 1.000) {
  1307. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1308. result.y = Math.acos(1 - 2 * determinant);
  1309. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1310. }
  1311. else {
  1312. if (determinant === 0.0) {
  1313. result.x = 0.0;
  1314. result.y = 0.0;
  1315. 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)
  1316. }
  1317. else {
  1318. 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)
  1319. result.y = Math.PI;
  1320. result.z = 0.0;
  1321. }
  1322. }
  1323. return this;
  1324. };
  1325. Quaternion.prototype.toRotationMatrix = function (result) {
  1326. var xx = this.x * this.x;
  1327. var yy = this.y * this.y;
  1328. var zz = this.z * this.z;
  1329. var xy = this.x * this.y;
  1330. var zw = this.z * this.w;
  1331. var zx = this.z * this.x;
  1332. var yw = this.y * this.w;
  1333. var yz = this.y * this.z;
  1334. var xw = this.x * this.w;
  1335. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1336. result.m[1] = 2.0 * (xy + zw);
  1337. result.m[2] = 2.0 * (zx - yw);
  1338. result.m[3] = 0;
  1339. result.m[4] = 2.0 * (xy - zw);
  1340. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1341. result.m[6] = 2.0 * (yz + xw);
  1342. result.m[7] = 0;
  1343. result.m[8] = 2.0 * (zx + yw);
  1344. result.m[9] = 2.0 * (yz - xw);
  1345. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1346. result.m[11] = 0;
  1347. result.m[12] = 0;
  1348. result.m[13] = 0;
  1349. result.m[14] = 0;
  1350. result.m[15] = 1.0;
  1351. return this;
  1352. };
  1353. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1354. Quaternion.FromRotationMatrixToRef(matrix, this);
  1355. return this;
  1356. };
  1357. // Statics
  1358. Quaternion.FromRotationMatrix = function (matrix) {
  1359. var result = new Quaternion();
  1360. Quaternion.FromRotationMatrixToRef(matrix, result);
  1361. return result;
  1362. };
  1363. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1364. var data = matrix.m;
  1365. var m11 = data[0], m12 = data[4], m13 = data[8];
  1366. var m21 = data[1], m22 = data[5], m23 = data[9];
  1367. var m31 = data[2], m32 = data[6], m33 = data[10];
  1368. var trace = m11 + m22 + m33;
  1369. var s;
  1370. if (trace > 0) {
  1371. s = 0.5 / Math.sqrt(trace + 1.0);
  1372. result.w = 0.25 / s;
  1373. result.x = (m32 - m23) * s;
  1374. result.y = (m13 - m31) * s;
  1375. result.z = (m21 - m12) * s;
  1376. }
  1377. else if (m11 > m22 && m11 > m33) {
  1378. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1379. result.w = (m32 - m23) / s;
  1380. result.x = 0.25 * s;
  1381. result.y = (m12 + m21) / s;
  1382. result.z = (m13 + m31) / s;
  1383. }
  1384. else if (m22 > m33) {
  1385. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1386. result.w = (m13 - m31) / s;
  1387. result.x = (m12 + m21) / s;
  1388. result.y = 0.25 * s;
  1389. result.z = (m23 + m32) / s;
  1390. }
  1391. else {
  1392. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1393. result.w = (m21 - m12) / s;
  1394. result.x = (m13 + m31) / s;
  1395. result.y = (m23 + m32) / s;
  1396. result.z = 0.25 * s;
  1397. }
  1398. };
  1399. Quaternion.Inverse = function (q) {
  1400. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1401. };
  1402. Quaternion.Identity = function () {
  1403. return new Quaternion(0, 0, 0, 1);
  1404. };
  1405. Quaternion.RotationAxis = function (axis, angle) {
  1406. var result = new Quaternion();
  1407. var sin = Math.sin(angle / 2);
  1408. axis.normalize();
  1409. result.w = Math.cos(angle / 2);
  1410. result.x = axis.x * sin;
  1411. result.y = axis.y * sin;
  1412. result.z = axis.z * sin;
  1413. return result;
  1414. };
  1415. Quaternion.FromArray = function (array, offset) {
  1416. if (!offset) {
  1417. offset = 0;
  1418. }
  1419. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1420. };
  1421. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1422. var result = new Quaternion();
  1423. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1424. return result;
  1425. };
  1426. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1427. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1428. var halfRoll = roll * 0.5;
  1429. var halfPitch = pitch * 0.5;
  1430. var halfYaw = yaw * 0.5;
  1431. var sinRoll = Math.sin(halfRoll);
  1432. var cosRoll = Math.cos(halfRoll);
  1433. var sinPitch = Math.sin(halfPitch);
  1434. var cosPitch = Math.cos(halfPitch);
  1435. var sinYaw = Math.sin(halfYaw);
  1436. var cosYaw = Math.cos(halfYaw);
  1437. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1438. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1439. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1440. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1441. };
  1442. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1448. // Produces a quaternion from Euler angles in the z-x-z orientation
  1449. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1450. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1451. var halfBeta = beta * 0.5;
  1452. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1453. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1454. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1455. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1456. };
  1457. Quaternion.Slerp = function (left, right, amount) {
  1458. var num2;
  1459. var num3;
  1460. var num = amount;
  1461. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1462. var flag = false;
  1463. if (num4 < 0) {
  1464. flag = true;
  1465. num4 = -num4;
  1466. }
  1467. if (num4 > 0.999999) {
  1468. num3 = 1 - num;
  1469. num2 = flag ? -num : num;
  1470. }
  1471. else {
  1472. var num5 = Math.acos(num4);
  1473. var num6 = (1.0 / Math.sin(num5));
  1474. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1475. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1476. }
  1477. 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));
  1478. };
  1479. return Quaternion;
  1480. })();
  1481. BABYLON.Quaternion = Quaternion;
  1482. var Matrix = (function () {
  1483. function Matrix() {
  1484. this.m = new Float32Array(16);
  1485. }
  1486. // Properties
  1487. Matrix.prototype.isIdentity = function () {
  1488. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1489. return false;
  1490. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1491. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1492. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1493. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1494. return false;
  1495. return true;
  1496. };
  1497. Matrix.prototype.determinant = function () {
  1498. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1499. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1500. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1501. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1502. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1503. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1504. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1505. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1506. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1507. };
  1508. // Methods
  1509. Matrix.prototype.toArray = function () {
  1510. return this.m;
  1511. };
  1512. Matrix.prototype.asArray = function () {
  1513. return this.toArray();
  1514. };
  1515. Matrix.prototype.invert = function () {
  1516. this.invertToRef(this);
  1517. return this;
  1518. };
  1519. Matrix.prototype.reset = function () {
  1520. for (var index = 0; index < 16; index++) {
  1521. this.m[index] = 0;
  1522. }
  1523. return this;
  1524. };
  1525. Matrix.prototype.add = function (other) {
  1526. var result = new Matrix();
  1527. this.addToRef(other, result);
  1528. return result;
  1529. };
  1530. Matrix.prototype.addToRef = function (other, result) {
  1531. for (var index = 0; index < 16; index++) {
  1532. result.m[index] = this.m[index] + other.m[index];
  1533. }
  1534. return this;
  1535. };
  1536. Matrix.prototype.addToSelf = function (other) {
  1537. for (var index = 0; index < 16; index++) {
  1538. this.m[index] += other.m[index];
  1539. }
  1540. return this;
  1541. };
  1542. Matrix.prototype.invertToRef = function (other) {
  1543. var l1 = this.m[0];
  1544. var l2 = this.m[1];
  1545. var l3 = this.m[2];
  1546. var l4 = this.m[3];
  1547. var l5 = this.m[4];
  1548. var l6 = this.m[5];
  1549. var l7 = this.m[6];
  1550. var l8 = this.m[7];
  1551. var l9 = this.m[8];
  1552. var l10 = this.m[9];
  1553. var l11 = this.m[10];
  1554. var l12 = this.m[11];
  1555. var l13 = this.m[12];
  1556. var l14 = this.m[13];
  1557. var l15 = this.m[14];
  1558. var l16 = this.m[15];
  1559. var l17 = (l11 * l16) - (l12 * l15);
  1560. var l18 = (l10 * l16) - (l12 * l14);
  1561. var l19 = (l10 * l15) - (l11 * l14);
  1562. var l20 = (l9 * l16) - (l12 * l13);
  1563. var l21 = (l9 * l15) - (l11 * l13);
  1564. var l22 = (l9 * l14) - (l10 * l13);
  1565. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1566. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1567. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1568. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1569. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1570. var l28 = (l7 * l16) - (l8 * l15);
  1571. var l29 = (l6 * l16) - (l8 * l14);
  1572. var l30 = (l6 * l15) - (l7 * l14);
  1573. var l31 = (l5 * l16) - (l8 * l13);
  1574. var l32 = (l5 * l15) - (l7 * l13);
  1575. var l33 = (l5 * l14) - (l6 * l13);
  1576. var l34 = (l7 * l12) - (l8 * l11);
  1577. var l35 = (l6 * l12) - (l8 * l10);
  1578. var l36 = (l6 * l11) - (l7 * l10);
  1579. var l37 = (l5 * l12) - (l8 * l9);
  1580. var l38 = (l5 * l11) - (l7 * l9);
  1581. var l39 = (l5 * l10) - (l6 * l9);
  1582. other.m[0] = l23 * l27;
  1583. other.m[4] = l24 * l27;
  1584. other.m[8] = l25 * l27;
  1585. other.m[12] = l26 * l27;
  1586. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1587. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1588. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1589. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1590. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1591. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1592. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1593. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1594. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1595. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1596. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1597. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1598. return this;
  1599. };
  1600. Matrix.prototype.invertToRefSIMD = function (other) {
  1601. var src = this.m;
  1602. var dest = other.m;
  1603. var row0, row1, row2, row3;
  1604. var tmp1;
  1605. var minor0, minor1, minor2, minor3;
  1606. var det;
  1607. // Load the 4 rows
  1608. var src0 = SIMD.float32x4.load(src, 0);
  1609. var src1 = SIMD.float32x4.load(src, 4);
  1610. var src2 = SIMD.float32x4.load(src, 8);
  1611. var src3 = SIMD.float32x4.load(src, 12);
  1612. // Transpose the source matrix. Sort of. Not a true transpose operation
  1613. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1614. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1615. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1616. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1617. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1618. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1619. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1620. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1621. // This is a true transposition, but it will lead to an incorrect result
  1622. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1623. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1624. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1625. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1626. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1627. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1628. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1629. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1630. // ----
  1631. tmp1 = SIMD.float32x4.mul(row2, row3);
  1632. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1633. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1634. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1635. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1636. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1637. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1638. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1639. // ----
  1640. tmp1 = SIMD.float32x4.mul(row1, row2);
  1641. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1642. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1643. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1644. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1645. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1646. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1647. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1648. // ----
  1649. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1650. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1651. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1652. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1653. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1654. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1655. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1656. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1657. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1658. // ----
  1659. tmp1 = SIMD.float32x4.mul(row0, row1);
  1660. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1661. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1662. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1663. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1664. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1665. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1666. // ----
  1667. tmp1 = SIMD.float32x4.mul(row0, row3);
  1668. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1669. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1670. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1671. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1672. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1673. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1674. // ----
  1675. tmp1 = SIMD.float32x4.mul(row0, row2);
  1676. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1677. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1678. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1679. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1680. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1681. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1682. // Compute determinant
  1683. det = SIMD.float32x4.mul(row0, minor0);
  1684. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1685. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1686. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1687. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1688. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1689. // These shuffles aren't necessary if the faulty transposition is done
  1690. // up at the top of this function.
  1691. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1692. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1693. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1694. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1695. // Compute final values by multiplying with 1/det
  1696. minor0 = SIMD.float32x4.mul(det, minor0);
  1697. minor1 = SIMD.float32x4.mul(det, minor1);
  1698. minor2 = SIMD.float32x4.mul(det, minor2);
  1699. minor3 = SIMD.float32x4.mul(det, minor3);
  1700. SIMD.float32x4.store(dest, 0, minor0);
  1701. SIMD.float32x4.store(dest, 4, minor1);
  1702. SIMD.float32x4.store(dest, 8, minor2);
  1703. SIMD.float32x4.store(dest, 12, minor3);
  1704. return this;
  1705. };
  1706. Matrix.prototype.setTranslation = function (vector3) {
  1707. this.m[12] = vector3.x;
  1708. this.m[13] = vector3.y;
  1709. this.m[14] = vector3.z;
  1710. return this;
  1711. };
  1712. Matrix.prototype.multiply = function (other) {
  1713. var result = new Matrix();
  1714. this.multiplyToRef(other, result);
  1715. return result;
  1716. };
  1717. Matrix.prototype.copyFrom = function (other) {
  1718. for (var index = 0; index < 16; index++) {
  1719. this.m[index] = other.m[index];
  1720. }
  1721. return this;
  1722. };
  1723. Matrix.prototype.copyToArray = function (array, offset) {
  1724. if (offset === void 0) { offset = 0; }
  1725. for (var index = 0; index < 16; index++) {
  1726. array[offset + index] = this.m[index];
  1727. }
  1728. return this;
  1729. };
  1730. Matrix.prototype.multiplyToRef = function (other, result) {
  1731. this.multiplyToArray(other, result.m, 0);
  1732. return this;
  1733. };
  1734. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1735. var tm0 = this.m[0];
  1736. var tm1 = this.m[1];
  1737. var tm2 = this.m[2];
  1738. var tm3 = this.m[3];
  1739. var tm4 = this.m[4];
  1740. var tm5 = this.m[5];
  1741. var tm6 = this.m[6];
  1742. var tm7 = this.m[7];
  1743. var tm8 = this.m[8];
  1744. var tm9 = this.m[9];
  1745. var tm10 = this.m[10];
  1746. var tm11 = this.m[11];
  1747. var tm12 = this.m[12];
  1748. var tm13 = this.m[13];
  1749. var tm14 = this.m[14];
  1750. var tm15 = this.m[15];
  1751. var om0 = other.m[0];
  1752. var om1 = other.m[1];
  1753. var om2 = other.m[2];
  1754. var om3 = other.m[3];
  1755. var om4 = other.m[4];
  1756. var om5 = other.m[5];
  1757. var om6 = other.m[6];
  1758. var om7 = other.m[7];
  1759. var om8 = other.m[8];
  1760. var om9 = other.m[9];
  1761. var om10 = other.m[10];
  1762. var om11 = other.m[11];
  1763. var om12 = other.m[12];
  1764. var om13 = other.m[13];
  1765. var om14 = other.m[14];
  1766. var om15 = other.m[15];
  1767. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1768. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1769. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1770. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1771. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1772. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1773. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1774. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1775. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1776. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1777. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1778. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1779. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1780. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1781. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1782. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1783. return this;
  1784. };
  1785. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1786. if (offset === void 0) { offset = 0; }
  1787. var tm = this.m;
  1788. var om = other.m;
  1789. var om0 = SIMD.float32x4.load(om, 0);
  1790. var om1 = SIMD.float32x4.load(om, 4);
  1791. var om2 = SIMD.float32x4.load(om, 8);
  1792. var om3 = SIMD.float32x4.load(om, 12);
  1793. var tm0 = SIMD.float32x4.load(tm, 0);
  1794. 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)))));
  1795. var tm1 = SIMD.float32x4.load(tm, 4);
  1796. 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)))));
  1797. var tm2 = SIMD.float32x4.load(tm, 8);
  1798. 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)))));
  1799. var tm3 = SIMD.float32x4.load(tm, 12);
  1800. 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)))));
  1801. };
  1802. Matrix.prototype.equals = function (value) {
  1803. return value &&
  1804. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1805. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1806. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1807. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1808. };
  1809. Matrix.prototype.clone = function () {
  1810. 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]);
  1811. };
  1812. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1813. translation.x = this.m[12];
  1814. translation.y = this.m[13];
  1815. translation.z = this.m[14];
  1816. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1817. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1818. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1819. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1820. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1821. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1822. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1823. rotation.x = 0;
  1824. rotation.y = 0;
  1825. rotation.z = 0;
  1826. rotation.w = 1;
  1827. return false;
  1828. }
  1829. 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);
  1830. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1831. return true;
  1832. };
  1833. // Statics
  1834. Matrix.FromArray = function (array, offset) {
  1835. var result = new Matrix();
  1836. if (!offset) {
  1837. offset = 0;
  1838. }
  1839. Matrix.FromArrayToRef(array, offset, result);
  1840. return result;
  1841. };
  1842. Matrix.FromArrayToRef = function (array, offset, result) {
  1843. for (var index = 0; index < 16; index++) {
  1844. result.m[index] = array[index + offset];
  1845. }
  1846. };
  1847. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1848. for (var index = 0; index < 16; index++) {
  1849. result.m[index] = array[index + offset] * scale;
  1850. }
  1851. };
  1852. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1853. result.m[0] = initialM11;
  1854. result.m[1] = initialM12;
  1855. result.m[2] = initialM13;
  1856. result.m[3] = initialM14;
  1857. result.m[4] = initialM21;
  1858. result.m[5] = initialM22;
  1859. result.m[6] = initialM23;
  1860. result.m[7] = initialM24;
  1861. result.m[8] = initialM31;
  1862. result.m[9] = initialM32;
  1863. result.m[10] = initialM33;
  1864. result.m[11] = initialM34;
  1865. result.m[12] = initialM41;
  1866. result.m[13] = initialM42;
  1867. result.m[14] = initialM43;
  1868. result.m[15] = initialM44;
  1869. };
  1870. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1871. var result = new Matrix();
  1872. result.m[0] = initialM11;
  1873. result.m[1] = initialM12;
  1874. result.m[2] = initialM13;
  1875. result.m[3] = initialM14;
  1876. result.m[4] = initialM21;
  1877. result.m[5] = initialM22;
  1878. result.m[6] = initialM23;
  1879. result.m[7] = initialM24;
  1880. result.m[8] = initialM31;
  1881. result.m[9] = initialM32;
  1882. result.m[10] = initialM33;
  1883. result.m[11] = initialM34;
  1884. result.m[12] = initialM41;
  1885. result.m[13] = initialM42;
  1886. result.m[14] = initialM43;
  1887. result.m[15] = initialM44;
  1888. return result;
  1889. };
  1890. Matrix.Compose = function (scale, rotation, translation) {
  1891. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1892. var rotationMatrix = Matrix.Identity();
  1893. rotation.toRotationMatrix(rotationMatrix);
  1894. result = result.multiply(rotationMatrix);
  1895. result.setTranslation(translation);
  1896. return result;
  1897. };
  1898. Matrix.Identity = function () {
  1899. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1900. };
  1901. Matrix.IdentityToRef = function (result) {
  1902. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1903. };
  1904. Matrix.Zero = function () {
  1905. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1906. };
  1907. Matrix.RotationX = function (angle) {
  1908. var result = new Matrix();
  1909. Matrix.RotationXToRef(angle, result);
  1910. return result;
  1911. };
  1912. Matrix.Invert = function (source) {
  1913. var result = new Matrix();
  1914. source.invertToRef(result);
  1915. return result;
  1916. };
  1917. Matrix.RotationXToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[0] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[5] = c;
  1923. result.m[10] = c;
  1924. result.m[9] = -s;
  1925. result.m[6] = s;
  1926. result.m[1] = 0;
  1927. result.m[2] = 0;
  1928. result.m[3] = 0;
  1929. result.m[4] = 0;
  1930. result.m[7] = 0;
  1931. result.m[8] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationY = function (angle) {
  1938. var result = new Matrix();
  1939. Matrix.RotationYToRef(angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationYToRef = function (angle, result) {
  1943. var s = Math.sin(angle);
  1944. var c = Math.cos(angle);
  1945. result.m[5] = 1.0;
  1946. result.m[15] = 1.0;
  1947. result.m[0] = c;
  1948. result.m[2] = -s;
  1949. result.m[8] = s;
  1950. result.m[10] = c;
  1951. result.m[1] = 0;
  1952. result.m[3] = 0;
  1953. result.m[4] = 0;
  1954. result.m[6] = 0;
  1955. result.m[7] = 0;
  1956. result.m[9] = 0;
  1957. result.m[11] = 0;
  1958. result.m[12] = 0;
  1959. result.m[13] = 0;
  1960. result.m[14] = 0;
  1961. };
  1962. Matrix.RotationZ = function (angle) {
  1963. var result = new Matrix();
  1964. Matrix.RotationZToRef(angle, result);
  1965. return result;
  1966. };
  1967. Matrix.RotationZToRef = function (angle, result) {
  1968. var s = Math.sin(angle);
  1969. var c = Math.cos(angle);
  1970. result.m[10] = 1.0;
  1971. result.m[15] = 1.0;
  1972. result.m[0] = c;
  1973. result.m[1] = s;
  1974. result.m[4] = -s;
  1975. result.m[5] = c;
  1976. result.m[2] = 0;
  1977. result.m[3] = 0;
  1978. result.m[6] = 0;
  1979. result.m[7] = 0;
  1980. result.m[8] = 0;
  1981. result.m[9] = 0;
  1982. result.m[11] = 0;
  1983. result.m[12] = 0;
  1984. result.m[13] = 0;
  1985. result.m[14] = 0;
  1986. };
  1987. Matrix.RotationAxis = function (axis, angle) {
  1988. var result = Matrix.Zero();
  1989. Matrix.RotationAxisToRef(axis, angle, result);
  1990. return result;
  1991. };
  1992. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1993. var s = Math.sin(-angle);
  1994. var c = Math.cos(-angle);
  1995. var c1 = 1 - c;
  1996. axis.normalize();
  1997. result.m[0] = (axis.x * axis.x) * c1 + c;
  1998. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1999. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2000. result.m[3] = 0.0;
  2001. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2002. result.m[5] = (axis.y * axis.y) * c1 + c;
  2003. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2004. result.m[7] = 0.0;
  2005. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2006. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2007. result.m[10] = (axis.z * axis.z) * c1 + c;
  2008. result.m[11] = 0.0;
  2009. result.m[15] = 1.0;
  2010. };
  2011. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2012. var result = new Matrix();
  2013. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2014. return result;
  2015. };
  2016. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2017. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2018. this._tempQuaternion.toRotationMatrix(result);
  2019. };
  2020. Matrix.Scaling = function (x, y, z) {
  2021. var result = Matrix.Zero();
  2022. Matrix.ScalingToRef(x, y, z, result);
  2023. return result;
  2024. };
  2025. Matrix.ScalingToRef = function (x, y, z, result) {
  2026. result.m[0] = x;
  2027. result.m[1] = 0;
  2028. result.m[2] = 0;
  2029. result.m[3] = 0;
  2030. result.m[4] = 0;
  2031. result.m[5] = y;
  2032. result.m[6] = 0;
  2033. result.m[7] = 0;
  2034. result.m[8] = 0;
  2035. result.m[9] = 0;
  2036. result.m[10] = z;
  2037. result.m[11] = 0;
  2038. result.m[12] = 0;
  2039. result.m[13] = 0;
  2040. result.m[14] = 0;
  2041. result.m[15] = 1.0;
  2042. };
  2043. Matrix.Translation = function (x, y, z) {
  2044. var result = Matrix.Identity();
  2045. Matrix.TranslationToRef(x, y, z, result);
  2046. return result;
  2047. };
  2048. Matrix.TranslationToRef = function (x, y, z, result) {
  2049. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2050. };
  2051. Matrix.LookAtLH = function (eye, target, up) {
  2052. var result = Matrix.Zero();
  2053. Matrix.LookAtLHToRef(eye, target, up, result);
  2054. return result;
  2055. };
  2056. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2057. // Z axis
  2058. target.subtractToRef(eye, this._zAxis);
  2059. this._zAxis.normalize();
  2060. // X axis
  2061. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2062. if (this._xAxis.lengthSquared() === 0) {
  2063. this._xAxis.x = 1.0;
  2064. }
  2065. else {
  2066. this._xAxis.normalize();
  2067. }
  2068. // Y axis
  2069. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2070. this._yAxis.normalize();
  2071. // Eye angles
  2072. var ex = -Vector3.Dot(this._xAxis, eye);
  2073. var ey = -Vector3.Dot(this._yAxis, eye);
  2074. var ez = -Vector3.Dot(this._zAxis, eye);
  2075. 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);
  2076. };
  2077. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2078. var out = result.m;
  2079. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2080. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2081. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2082. // cc.kmVec3Subtract(f, pCenter, pEye);
  2083. var f = SIMD.float32x4.sub(center, eye);
  2084. // cc.kmVec3Normalize(f, f);
  2085. var tmp = SIMD.float32x4.mul(f, f);
  2086. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2087. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2088. // cc.kmVec3Assign(up, pUp);
  2089. // cc.kmVec3Normalize(up, up);
  2090. tmp = SIMD.float32x4.mul(up, up);
  2091. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2092. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2093. // cc.kmVec3Cross(s, f, up);
  2094. 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)));
  2095. // cc.kmVec3Normalize(s, s);
  2096. tmp = SIMD.float32x4.mul(s, s);
  2097. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2098. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2099. // cc.kmVec3Cross(u, s, f);
  2100. 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)));
  2101. // cc.kmVec3Normalize(s, s);
  2102. tmp = SIMD.float32x4.mul(s, s);
  2103. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2104. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2105. var zero = SIMD.float32x4.splat(0.0);
  2106. s = SIMD.float32x4.neg(s);
  2107. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2108. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2109. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2110. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2111. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2112. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2113. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2114. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2115. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2116. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2117. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2118. var b3 = SIMD.float32x4.neg(eye);
  2119. b3 = SIMD.float32x4.withW(b3, 1.0);
  2120. 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)))));
  2121. 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)))));
  2122. 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)))));
  2123. 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)))));
  2124. };
  2125. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2126. var matrix = Matrix.Zero();
  2127. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2128. return matrix;
  2129. };
  2130. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2131. var hw = 2.0 / width;
  2132. var hh = 2.0 / height;
  2133. var id = 1.0 / (zfar - znear);
  2134. var nid = znear / (znear - zfar);
  2135. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2136. };
  2137. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2138. var matrix = Matrix.Zero();
  2139. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2140. return matrix;
  2141. };
  2142. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2143. result.m[0] = 2.0 / (right - left);
  2144. result.m[1] = result.m[2] = result.m[3] = 0;
  2145. result.m[5] = 2.0 / (top - bottom);
  2146. result.m[4] = result.m[6] = result.m[7] = 0;
  2147. result.m[10] = -1.0 / (znear - zfar);
  2148. result.m[8] = result.m[9] = result.m[11] = 0;
  2149. result.m[12] = (left + right) / (left - right);
  2150. result.m[13] = (top + bottom) / (bottom - top);
  2151. result.m[14] = znear / (znear - zfar);
  2152. result.m[15] = 1.0;
  2153. };
  2154. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2155. var matrix = Matrix.Zero();
  2156. matrix.m[0] = (2.0 * znear) / width;
  2157. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2158. matrix.m[5] = (2.0 * znear) / height;
  2159. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2160. matrix.m[10] = -zfar / (znear - zfar);
  2161. matrix.m[8] = matrix.m[9] = 0.0;
  2162. matrix.m[11] = 1.0;
  2163. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2164. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2165. return matrix;
  2166. };
  2167. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2168. var matrix = Matrix.Zero();
  2169. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2170. return matrix;
  2171. };
  2172. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2173. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2174. var tan = 1.0 / (Math.tan(fov * 0.5));
  2175. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2176. if (v_fixed) {
  2177. result.m[0] = tan / aspect;
  2178. }
  2179. else {
  2180. result.m[0] = tan;
  2181. }
  2182. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2183. if (v_fixed) {
  2184. result.m[5] = tan;
  2185. }
  2186. else {
  2187. result.m[5] = tan * aspect;
  2188. }
  2189. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2190. result.m[8] = result.m[9] = 0.0;
  2191. result.m[10] = -zfar / (znear - zfar);
  2192. result.m[11] = 1.0;
  2193. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2194. result.m[14] = (znear * zfar) / (znear - zfar);
  2195. };
  2196. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2197. var cw = viewport.width;
  2198. var ch = viewport.height;
  2199. var cx = viewport.x;
  2200. var cy = viewport.y;
  2201. 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);
  2202. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2203. };
  2204. Matrix.GetAsMatrix2x2 = function (matrix) {
  2205. return new Float32Array([
  2206. matrix.m[0], matrix.m[1],
  2207. matrix.m[4], matrix.m[5]
  2208. ]);
  2209. };
  2210. Matrix.GetAsMatrix3x3 = function (matrix) {
  2211. return new Float32Array([
  2212. matrix.m[0], matrix.m[1], matrix.m[2],
  2213. matrix.m[4], matrix.m[5], matrix.m[6],
  2214. matrix.m[8], matrix.m[9], matrix.m[10]
  2215. ]);
  2216. };
  2217. Matrix.Transpose = function (matrix) {
  2218. var result = new Matrix();
  2219. result.m[0] = matrix.m[0];
  2220. result.m[1] = matrix.m[4];
  2221. result.m[2] = matrix.m[8];
  2222. result.m[3] = matrix.m[12];
  2223. result.m[4] = matrix.m[1];
  2224. result.m[5] = matrix.m[5];
  2225. result.m[6] = matrix.m[9];
  2226. result.m[7] = matrix.m[13];
  2227. result.m[8] = matrix.m[2];
  2228. result.m[9] = matrix.m[6];
  2229. result.m[10] = matrix.m[10];
  2230. result.m[11] = matrix.m[14];
  2231. result.m[12] = matrix.m[3];
  2232. result.m[13] = matrix.m[7];
  2233. result.m[14] = matrix.m[11];
  2234. result.m[15] = matrix.m[15];
  2235. return result;
  2236. };
  2237. Matrix.Reflection = function (plane) {
  2238. var matrix = new Matrix();
  2239. Matrix.ReflectionToRef(plane, matrix);
  2240. return matrix;
  2241. };
  2242. Matrix.ReflectionToRef = function (plane, result) {
  2243. plane.normalize();
  2244. var x = plane.normal.x;
  2245. var y = plane.normal.y;
  2246. var z = plane.normal.z;
  2247. var temp = -2 * x;
  2248. var temp2 = -2 * y;
  2249. var temp3 = -2 * z;
  2250. result.m[0] = (temp * x) + 1;
  2251. result.m[1] = temp2 * x;
  2252. result.m[2] = temp3 * x;
  2253. result.m[3] = 0.0;
  2254. result.m[4] = temp * y;
  2255. result.m[5] = (temp2 * y) + 1;
  2256. result.m[6] = temp3 * y;
  2257. result.m[7] = 0.0;
  2258. result.m[8] = temp * z;
  2259. result.m[9] = temp2 * z;
  2260. result.m[10] = (temp3 * z) + 1;
  2261. result.m[11] = 0.0;
  2262. result.m[12] = temp * plane.d;
  2263. result.m[13] = temp2 * plane.d;
  2264. result.m[14] = temp3 * plane.d;
  2265. result.m[15] = 1.0;
  2266. };
  2267. Matrix._tempQuaternion = new Quaternion();
  2268. Matrix._xAxis = Vector3.Zero();
  2269. Matrix._yAxis = Vector3.Zero();
  2270. Matrix._zAxis = Vector3.Zero();
  2271. return Matrix;
  2272. })();
  2273. BABYLON.Matrix = Matrix;
  2274. var Plane = (function () {
  2275. function Plane(a, b, c, d) {
  2276. this.normal = new Vector3(a, b, c);
  2277. this.d = d;
  2278. }
  2279. Plane.prototype.asArray = function () {
  2280. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2281. };
  2282. // Methods
  2283. Plane.prototype.clone = function () {
  2284. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2285. };
  2286. Plane.prototype.normalize = function () {
  2287. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2288. var magnitude = 0;
  2289. if (norm !== 0) {
  2290. magnitude = 1.0 / norm;
  2291. }
  2292. this.normal.x *= magnitude;
  2293. this.normal.y *= magnitude;
  2294. this.normal.z *= magnitude;
  2295. this.d *= magnitude;
  2296. return this;
  2297. };
  2298. Plane.prototype.transform = function (transformation) {
  2299. var transposedMatrix = Matrix.Transpose(transformation);
  2300. var x = this.normal.x;
  2301. var y = this.normal.y;
  2302. var z = this.normal.z;
  2303. var d = this.d;
  2304. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2305. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2306. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2307. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2308. return new Plane(normalX, normalY, normalZ, finalD);
  2309. };
  2310. Plane.prototype.dotCoordinate = function (point) {
  2311. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2312. };
  2313. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2314. var x1 = point2.x - point1.x;
  2315. var y1 = point2.y - point1.y;
  2316. var z1 = point2.z - point1.z;
  2317. var x2 = point3.x - point1.x;
  2318. var y2 = point3.y - point1.y;
  2319. var z2 = point3.z - point1.z;
  2320. var yz = (y1 * z2) - (z1 * y2);
  2321. var xz = (z1 * x2) - (x1 * z2);
  2322. var xy = (x1 * y2) - (y1 * x2);
  2323. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2324. var invPyth;
  2325. if (pyth !== 0) {
  2326. invPyth = 1.0 / pyth;
  2327. }
  2328. else {
  2329. invPyth = 0;
  2330. }
  2331. this.normal.x = yz * invPyth;
  2332. this.normal.y = xz * invPyth;
  2333. this.normal.z = xy * invPyth;
  2334. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2335. return this;
  2336. };
  2337. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2338. var dot = Vector3.Dot(this.normal, direction);
  2339. return (dot <= epsilon);
  2340. };
  2341. Plane.prototype.signedDistanceTo = function (point) {
  2342. return Vector3.Dot(point, this.normal) + this.d;
  2343. };
  2344. // Statics
  2345. Plane.FromArray = function (array) {
  2346. return new Plane(array[0], array[1], array[2], array[3]);
  2347. };
  2348. Plane.FromPoints = function (point1, point2, point3) {
  2349. var result = new Plane(0, 0, 0, 0);
  2350. result.copyFromPoints(point1, point2, point3);
  2351. return result;
  2352. };
  2353. Plane.FromPositionAndNormal = function (origin, normal) {
  2354. var result = new Plane(0, 0, 0, 0);
  2355. normal.normalize();
  2356. result.normal = normal;
  2357. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2358. return result;
  2359. };
  2360. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2361. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2362. return Vector3.Dot(point, normal) + d;
  2363. };
  2364. return Plane;
  2365. })();
  2366. BABYLON.Plane = Plane;
  2367. var Viewport = (function () {
  2368. function Viewport(x, y, width, height) {
  2369. this.x = x;
  2370. this.y = y;
  2371. this.width = width;
  2372. this.height = height;
  2373. }
  2374. Viewport.prototype.toGlobal = function (engine) {
  2375. var width = engine.getRenderWidth();
  2376. var height = engine.getRenderHeight();
  2377. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2378. };
  2379. return Viewport;
  2380. })();
  2381. BABYLON.Viewport = Viewport;
  2382. var Frustum = (function () {
  2383. function Frustum() {
  2384. }
  2385. Frustum.GetPlanes = function (transform) {
  2386. var frustumPlanes = [];
  2387. for (var index = 0; index < 6; index++) {
  2388. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2389. }
  2390. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2391. return frustumPlanes;
  2392. };
  2393. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2394. // Near
  2395. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2396. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2397. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2398. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2399. frustumPlanes[0].normalize();
  2400. // Far
  2401. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2402. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2403. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2404. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2405. frustumPlanes[1].normalize();
  2406. // Left
  2407. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2408. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2409. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2410. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2411. frustumPlanes[2].normalize();
  2412. // Right
  2413. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2414. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2415. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2416. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2417. frustumPlanes[3].normalize();
  2418. // Top
  2419. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2420. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2421. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2422. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2423. frustumPlanes[4].normalize();
  2424. // Bottom
  2425. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2426. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2427. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2428. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2429. frustumPlanes[5].normalize();
  2430. };
  2431. return Frustum;
  2432. })();
  2433. BABYLON.Frustum = Frustum;
  2434. var Ray = (function () {
  2435. function Ray(origin, direction, length) {
  2436. if (length === void 0) { length = Number.MAX_VALUE; }
  2437. this.origin = origin;
  2438. this.direction = direction;
  2439. this.length = length;
  2440. }
  2441. // Methods
  2442. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2443. var d = 0.0;
  2444. var maxValue = Number.MAX_VALUE;
  2445. var inv;
  2446. var min;
  2447. var max;
  2448. var temp;
  2449. if (Math.abs(this.direction.x) < 0.0000001) {
  2450. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2451. return false;
  2452. }
  2453. }
  2454. else {
  2455. inv = 1.0 / this.direction.x;
  2456. min = (minimum.x - this.origin.x) * inv;
  2457. max = (maximum.x - this.origin.x) * inv;
  2458. if (max === -Infinity) {
  2459. max = Infinity;
  2460. }
  2461. if (min > max) {
  2462. temp = min;
  2463. min = max;
  2464. max = temp;
  2465. }
  2466. d = Math.max(min, d);
  2467. maxValue = Math.min(max, maxValue);
  2468. if (d > maxValue) {
  2469. return false;
  2470. }
  2471. }
  2472. if (Math.abs(this.direction.y) < 0.0000001) {
  2473. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2474. return false;
  2475. }
  2476. }
  2477. else {
  2478. inv = 1.0 / this.direction.y;
  2479. min = (minimum.y - this.origin.y) * inv;
  2480. max = (maximum.y - this.origin.y) * inv;
  2481. if (max === -Infinity) {
  2482. max = Infinity;
  2483. }
  2484. if (min > max) {
  2485. temp = min;
  2486. min = max;
  2487. max = temp;
  2488. }
  2489. d = Math.max(min, d);
  2490. maxValue = Math.min(max, maxValue);
  2491. if (d > maxValue) {
  2492. return false;
  2493. }
  2494. }
  2495. if (Math.abs(this.direction.z) < 0.0000001) {
  2496. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2497. return false;
  2498. }
  2499. }
  2500. else {
  2501. inv = 1.0 / this.direction.z;
  2502. min = (minimum.z - this.origin.z) * inv;
  2503. max = (maximum.z - this.origin.z) * inv;
  2504. if (max === -Infinity) {
  2505. max = Infinity;
  2506. }
  2507. if (min > max) {
  2508. temp = min;
  2509. min = max;
  2510. max = temp;
  2511. }
  2512. d = Math.max(min, d);
  2513. maxValue = Math.min(max, maxValue);
  2514. if (d > maxValue) {
  2515. return false;
  2516. }
  2517. }
  2518. return true;
  2519. };
  2520. Ray.prototype.intersectsBox = function (box) {
  2521. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2522. };
  2523. Ray.prototype.intersectsSphere = function (sphere) {
  2524. var x = sphere.center.x - this.origin.x;
  2525. var y = sphere.center.y - this.origin.y;
  2526. var z = sphere.center.z - this.origin.z;
  2527. var pyth = (x * x) + (y * y) + (z * z);
  2528. var rr = sphere.radius * sphere.radius;
  2529. if (pyth <= rr) {
  2530. return true;
  2531. }
  2532. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2533. if (dot < 0.0) {
  2534. return false;
  2535. }
  2536. var temp = pyth - (dot * dot);
  2537. return temp <= rr;
  2538. };
  2539. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2540. if (!this._edge1) {
  2541. this._edge1 = Vector3.Zero();
  2542. this._edge2 = Vector3.Zero();
  2543. this._pvec = Vector3.Zero();
  2544. this._tvec = Vector3.Zero();
  2545. this._qvec = Vector3.Zero();
  2546. }
  2547. vertex1.subtractToRef(vertex0, this._edge1);
  2548. vertex2.subtractToRef(vertex0, this._edge2);
  2549. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2550. var det = Vector3.Dot(this._edge1, this._pvec);
  2551. if (det === 0) {
  2552. return null;
  2553. }
  2554. var invdet = 1 / det;
  2555. this.origin.subtractToRef(vertex0, this._tvec);
  2556. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2557. if (bu < 0 || bu > 1.0) {
  2558. return null;
  2559. }
  2560. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2561. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2562. if (bv < 0 || bu + bv > 1.0) {
  2563. return null;
  2564. }
  2565. //check if the distance is longer than the predefined length.
  2566. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2567. if (distance > this.length) {
  2568. return null;
  2569. }
  2570. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2571. };
  2572. // Statics
  2573. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2574. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2575. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2576. var direction = end.subtract(start);
  2577. direction.normalize();
  2578. return new Ray(start, direction);
  2579. };
  2580. /**
  2581. * 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
  2582. * transformed to the given world matrix.
  2583. * @param origin The origin point
  2584. * @param end The end point
  2585. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2586. */
  2587. Ray.CreateNewFromTo = function (origin, end, world) {
  2588. if (world === void 0) { world = Matrix.Identity(); }
  2589. var direction = end.subtract(origin);
  2590. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2591. direction.normalize();
  2592. return Ray.Transform(new Ray(origin, direction, length), world);
  2593. };
  2594. Ray.Transform = function (ray, matrix) {
  2595. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2596. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2597. return new Ray(newOrigin, newDirection, ray.length);
  2598. };
  2599. return Ray;
  2600. })();
  2601. BABYLON.Ray = Ray;
  2602. (function (Space) {
  2603. Space[Space["LOCAL"] = 0] = "LOCAL";
  2604. Space[Space["WORLD"] = 1] = "WORLD";
  2605. })(BABYLON.Space || (BABYLON.Space = {}));
  2606. var Space = BABYLON.Space;
  2607. var Axis = (function () {
  2608. function Axis() {
  2609. }
  2610. Axis.X = new Vector3(1, 0, 0);
  2611. Axis.Y = new Vector3(0, 1, 0);
  2612. Axis.Z = new Vector3(0, 0, 1);
  2613. return Axis;
  2614. })();
  2615. BABYLON.Axis = Axis;
  2616. ;
  2617. var BezierCurve = (function () {
  2618. function BezierCurve() {
  2619. }
  2620. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2621. // Extract X (which is equal to time here)
  2622. var f0 = 1 - 3 * x2 + 3 * x1;
  2623. var f1 = 3 * x2 - 6 * x1;
  2624. var f2 = 3 * x1;
  2625. var refinedT = t;
  2626. for (var i = 0; i < 5; i++) {
  2627. var refinedT2 = refinedT * refinedT;
  2628. var refinedT3 = refinedT2 * refinedT;
  2629. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2630. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2631. refinedT -= (x - t) * slope;
  2632. refinedT = Math.min(1, Math.max(0, refinedT));
  2633. }
  2634. // Resolve cubic bezier for the given x
  2635. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2636. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2637. Math.pow(refinedT, 3);
  2638. };
  2639. return BezierCurve;
  2640. })();
  2641. BABYLON.BezierCurve = BezierCurve;
  2642. (function (Orientation) {
  2643. Orientation[Orientation["CW"] = 0] = "CW";
  2644. Orientation[Orientation["CCW"] = 1] = "CCW";
  2645. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2646. var Orientation = BABYLON.Orientation;
  2647. var Angle = (function () {
  2648. function Angle(radians) {
  2649. var _this = this;
  2650. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2651. this.radians = function () { return _this._radians; };
  2652. this._radians = radians;
  2653. if (this._radians < 0)
  2654. this._radians += (2 * Math.PI);
  2655. }
  2656. Angle.BetweenTwoPoints = function (a, b) {
  2657. var delta = b.subtract(a);
  2658. var theta = Math.atan2(delta.y, delta.x);
  2659. return new Angle(theta);
  2660. };
  2661. Angle.FromRadians = function (radians) {
  2662. return new Angle(radians);
  2663. };
  2664. Angle.FromDegrees = function (degrees) {
  2665. return new Angle(degrees * Math.PI / 180);
  2666. };
  2667. return Angle;
  2668. })();
  2669. BABYLON.Angle = Angle;
  2670. var Arc2 = (function () {
  2671. function Arc2(startPoint, midPoint, endPoint) {
  2672. this.startPoint = startPoint;
  2673. this.midPoint = midPoint;
  2674. this.endPoint = endPoint;
  2675. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2676. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2677. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2678. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2679. 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);
  2680. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2681. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2682. var a1 = this.startAngle.degrees();
  2683. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2684. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2685. // angles correction
  2686. if (a2 - a1 > +180.0)
  2687. a2 -= 360.0;
  2688. if (a2 - a1 < -180.0)
  2689. a2 += 360.0;
  2690. if (a3 - a2 > +180.0)
  2691. a3 -= 360.0;
  2692. if (a3 - a2 < -180.0)
  2693. a3 += 360.0;
  2694. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2695. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2696. }
  2697. return Arc2;
  2698. })();
  2699. BABYLON.Arc2 = Arc2;
  2700. var PathCursor = (function () {
  2701. function PathCursor(path) {
  2702. this.path = path;
  2703. this._onchange = new Array();
  2704. this.value = 0;
  2705. this.animations = new Array();
  2706. }
  2707. PathCursor.prototype.getPoint = function () {
  2708. var point = this.path.getPointAtLengthPosition(this.value);
  2709. return new Vector3(point.x, 0, point.y);
  2710. };
  2711. PathCursor.prototype.moveAhead = function (step) {
  2712. if (step === void 0) { step = 0.002; }
  2713. this.move(step);
  2714. return this;
  2715. };
  2716. PathCursor.prototype.moveBack = function (step) {
  2717. if (step === void 0) { step = 0.002; }
  2718. this.move(-step);
  2719. return this;
  2720. };
  2721. PathCursor.prototype.move = function (step) {
  2722. if (Math.abs(step) > 1) {
  2723. throw "step size should be less than 1.";
  2724. }
  2725. this.value += step;
  2726. this.ensureLimits();
  2727. this.raiseOnChange();
  2728. return this;
  2729. };
  2730. PathCursor.prototype.ensureLimits = function () {
  2731. while (this.value > 1) {
  2732. this.value -= 1;
  2733. }
  2734. while (this.value < 0) {
  2735. this.value += 1;
  2736. }
  2737. return this;
  2738. };
  2739. // used by animation engine
  2740. PathCursor.prototype.markAsDirty = function (propertyName) {
  2741. this.ensureLimits();
  2742. this.raiseOnChange();
  2743. return this;
  2744. };
  2745. PathCursor.prototype.raiseOnChange = function () {
  2746. var _this = this;
  2747. this._onchange.forEach(function (f) { return f(_this); });
  2748. return this;
  2749. };
  2750. PathCursor.prototype.onchange = function (f) {
  2751. this._onchange.push(f);
  2752. return this;
  2753. };
  2754. return PathCursor;
  2755. })();
  2756. BABYLON.PathCursor = PathCursor;
  2757. var Path2 = (function () {
  2758. function Path2(x, y) {
  2759. this._points = new Array();
  2760. this._length = 0;
  2761. this.closed = false;
  2762. this._points.push(new Vector2(x, y));
  2763. }
  2764. Path2.prototype.addLineTo = function (x, y) {
  2765. if (closed) {
  2766. BABYLON.Tools.Error("cannot add lines to closed paths");
  2767. return this;
  2768. }
  2769. var newPoint = new Vector2(x, y);
  2770. var previousPoint = this._points[this._points.length - 1];
  2771. this._points.push(newPoint);
  2772. this._length += newPoint.subtract(previousPoint).length();
  2773. return this;
  2774. };
  2775. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2776. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2777. if (closed) {
  2778. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2779. return this;
  2780. }
  2781. var startPoint = this._points[this._points.length - 1];
  2782. var midPoint = new Vector2(midX, midY);
  2783. var endPoint = new Vector2(endX, endY);
  2784. var arc = new Arc2(startPoint, midPoint, endPoint);
  2785. var increment = arc.angle.radians() / numberOfSegments;
  2786. if (arc.orientation === Orientation.CW)
  2787. increment *= -1;
  2788. var currentAngle = arc.startAngle.radians() + increment;
  2789. for (var i = 0; i < numberOfSegments; i++) {
  2790. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2791. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2792. this.addLineTo(x, y);
  2793. currentAngle += increment;
  2794. }
  2795. return this;
  2796. };
  2797. Path2.prototype.close = function () {
  2798. this.closed = true;
  2799. return this;
  2800. };
  2801. Path2.prototype.length = function () {
  2802. var result = this._length;
  2803. if (!this.closed) {
  2804. var lastPoint = this._points[this._points.length - 1];
  2805. var firstPoint = this._points[0];
  2806. result += (firstPoint.subtract(lastPoint).length());
  2807. }
  2808. return result;
  2809. };
  2810. Path2.prototype.getPoints = function () {
  2811. return this._points;
  2812. };
  2813. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2814. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2815. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2816. return Vector2.Zero();
  2817. }
  2818. var lengthPosition = normalizedLengthPosition * this.length();
  2819. var previousOffset = 0;
  2820. for (var i = 0; i < this._points.length; i++) {
  2821. var j = (i + 1) % this._points.length;
  2822. var a = this._points[i];
  2823. var b = this._points[j];
  2824. var bToA = b.subtract(a);
  2825. var nextOffset = (bToA.length() + previousOffset);
  2826. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2827. var dir = bToA.normalize();
  2828. var localOffset = lengthPosition - previousOffset;
  2829. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2830. }
  2831. previousOffset = nextOffset;
  2832. }
  2833. BABYLON.Tools.Error("internal error");
  2834. return Vector2.Zero();
  2835. };
  2836. Path2.StartingAt = function (x, y) {
  2837. return new Path2(x, y);
  2838. };
  2839. return Path2;
  2840. })();
  2841. BABYLON.Path2 = Path2;
  2842. var Path3D = (function () {
  2843. /**
  2844. * new Path3D(path, normal, raw)
  2845. * path : an array of Vector3, the curve axis of the Path3D
  2846. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2847. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2848. */
  2849. function Path3D(path, firstNormal, raw) {
  2850. this.path = path;
  2851. this._curve = new Array();
  2852. this._distances = new Array();
  2853. this._tangents = new Array();
  2854. this._normals = new Array();
  2855. this._binormals = new Array();
  2856. for (var p = 0; p < path.length; p++) {
  2857. this._curve[p] = path[p].clone(); // hard copy
  2858. }
  2859. this._raw = raw || false;
  2860. this._compute(firstNormal);
  2861. }
  2862. Path3D.prototype.getCurve = function () {
  2863. return this._curve;
  2864. };
  2865. Path3D.prototype.getTangents = function () {
  2866. return this._tangents;
  2867. };
  2868. Path3D.prototype.getNormals = function () {
  2869. return this._normals;
  2870. };
  2871. Path3D.prototype.getBinormals = function () {
  2872. return this._binormals;
  2873. };
  2874. Path3D.prototype.getDistances = function () {
  2875. return this._distances;
  2876. };
  2877. Path3D.prototype.update = function (path, firstNormal) {
  2878. for (var p = 0; p < path.length; p++) {
  2879. this._curve[p].x = path[p].x;
  2880. this._curve[p].y = path[p].y;
  2881. this._curve[p].z = path[p].z;
  2882. }
  2883. this._compute(firstNormal);
  2884. return this;
  2885. };
  2886. // private function compute() : computes tangents, normals and binormals
  2887. Path3D.prototype._compute = function (firstNormal) {
  2888. var l = this._curve.length;
  2889. // first and last tangents
  2890. this._tangents[0] = this._getFirstNonNullVector(0);
  2891. if (!this._raw) {
  2892. this._tangents[0].normalize();
  2893. }
  2894. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2895. if (!this._raw) {
  2896. this._tangents[l - 1].normalize();
  2897. }
  2898. // normals and binormals at first point : arbitrary vector with _normalVector()
  2899. var tg0 = this._tangents[0];
  2900. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2901. this._normals[0] = pp0;
  2902. if (!this._raw) {
  2903. this._normals[0].normalize();
  2904. }
  2905. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2906. if (!this._raw) {
  2907. this._binormals[0].normalize();
  2908. }
  2909. this._distances[0] = 0;
  2910. // normals and binormals : next points
  2911. var prev; // previous vector (segment)
  2912. var cur; // current vector (segment)
  2913. var curTang; // current tangent
  2914. // previous normal
  2915. var prevBinor; // previous binormal
  2916. for (var i = 1; i < l; i++) {
  2917. // tangents
  2918. prev = this._getLastNonNullVector(i);
  2919. if (i < l - 1) {
  2920. cur = this._getFirstNonNullVector(i);
  2921. this._tangents[i] = prev.add(cur);
  2922. this._tangents[i].normalize();
  2923. }
  2924. this._distances[i] = this._distances[i - 1] + prev.length();
  2925. // normals and binormals
  2926. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2927. curTang = this._tangents[i];
  2928. prevBinor = this._binormals[i - 1];
  2929. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2930. if (!this._raw) {
  2931. this._normals[i].normalize();
  2932. }
  2933. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2934. if (!this._raw) {
  2935. this._binormals[i].normalize();
  2936. }
  2937. }
  2938. };
  2939. // private function getFirstNonNullVector(index)
  2940. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2941. Path3D.prototype._getFirstNonNullVector = function (index) {
  2942. var i = 1;
  2943. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2944. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2945. i++;
  2946. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2947. }
  2948. return nNVector;
  2949. };
  2950. // private function getLastNonNullVector(index)
  2951. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2952. Path3D.prototype._getLastNonNullVector = function (index) {
  2953. var i = 1;
  2954. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2955. while (nLVector.length() === 0 && index > i + 1) {
  2956. i++;
  2957. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2958. }
  2959. return nLVector;
  2960. };
  2961. // private function normalVector(v0, vt, va) :
  2962. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2963. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2964. Path3D.prototype._normalVector = function (v0, vt, va) {
  2965. var normal0;
  2966. if (va === undefined || va === null) {
  2967. var point;
  2968. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2969. point = new Vector3(0, -1, 0);
  2970. }
  2971. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2972. point = new Vector3(1, 0, 0);
  2973. }
  2974. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2975. point = new Vector3(0, 0, 1);
  2976. }
  2977. normal0 = Vector3.Cross(vt, point);
  2978. }
  2979. else {
  2980. normal0 = Vector3.Cross(vt, va);
  2981. Vector3.CrossToRef(normal0, vt, normal0);
  2982. }
  2983. normal0.normalize();
  2984. return normal0;
  2985. };
  2986. return Path3D;
  2987. })();
  2988. BABYLON.Path3D = Path3D;
  2989. var Curve3 = (function () {
  2990. function Curve3(points) {
  2991. this._length = 0;
  2992. this._points = points;
  2993. this._length = this._computeLength(points);
  2994. }
  2995. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2996. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2997. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2998. var bez = new Array();
  2999. var equation = function (t, val0, val1, val2) {
  3000. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  3001. return res;
  3002. };
  3003. for (var i = 0; i <= nbPoints; i++) {
  3004. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  3005. }
  3006. return new Curve3(bez);
  3007. };
  3008. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  3009. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3010. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3011. var bez = new Array();
  3012. var equation = function (t, val0, val1, val2, val3) {
  3013. 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;
  3014. return res;
  3015. };
  3016. for (var i = 0; i <= nbPoints; i++) {
  3017. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  3018. }
  3019. return new Curve3(bez);
  3020. };
  3021. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  3022. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3023. var hermite = new Array();
  3024. var step = 1 / nbPoints;
  3025. for (var i = 0; i <= nbPoints; i++) {
  3026. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3027. }
  3028. return new Curve3(hermite);
  3029. };
  3030. Curve3.prototype.getPoints = function () {
  3031. return this._points;
  3032. };
  3033. Curve3.prototype.length = function () {
  3034. return this._length;
  3035. };
  3036. Curve3.prototype.continue = function (curve) {
  3037. var lastPoint = this._points[this._points.length - 1];
  3038. var continuedPoints = this._points.slice();
  3039. var curvePoints = curve.getPoints();
  3040. for (var i = 1; i < curvePoints.length; i++) {
  3041. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3042. }
  3043. var continuedCurve = new Curve3(continuedPoints);
  3044. return continuedCurve;
  3045. };
  3046. Curve3.prototype._computeLength = function (path) {
  3047. var l = 0;
  3048. for (var i = 1; i < path.length; i++) {
  3049. l += (path[i].subtract(path[i - 1])).length();
  3050. }
  3051. return l;
  3052. };
  3053. return Curve3;
  3054. })();
  3055. BABYLON.Curve3 = Curve3;
  3056. // Vertex formats
  3057. var PositionNormalVertex = (function () {
  3058. function PositionNormalVertex(position, normal) {
  3059. if (position === void 0) { position = Vector3.Zero(); }
  3060. if (normal === void 0) { normal = Vector3.Up(); }
  3061. this.position = position;
  3062. this.normal = normal;
  3063. }
  3064. PositionNormalVertex.prototype.clone = function () {
  3065. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3066. };
  3067. return PositionNormalVertex;
  3068. })();
  3069. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3070. var PositionNormalTextureVertex = (function () {
  3071. function PositionNormalTextureVertex(position, normal, uv) {
  3072. if (position === void 0) { position = Vector3.Zero(); }
  3073. if (normal === void 0) { normal = Vector3.Up(); }
  3074. if (uv === void 0) { uv = Vector2.Zero(); }
  3075. this.position = position;
  3076. this.normal = normal;
  3077. this.uv = uv;
  3078. }
  3079. PositionNormalTextureVertex.prototype.clone = function () {
  3080. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3081. };
  3082. return PositionNormalTextureVertex;
  3083. })();
  3084. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3085. // SIMD
  3086. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3087. var previousInvertToRef = Matrix.prototype.invertToRef;
  3088. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3089. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3090. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3091. var SIMDHelper = (function () {
  3092. function SIMDHelper() {
  3093. }
  3094. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3095. get: function () {
  3096. return SIMDHelper._isEnabled;
  3097. },
  3098. enumerable: true,
  3099. configurable: true
  3100. });
  3101. SIMDHelper.DisableSIMD = function () {
  3102. // Replace functions
  3103. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3104. Matrix.prototype.invertToRef = previousInvertToRef;
  3105. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3106. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3107. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3108. SIMDHelper._isEnabled = false;
  3109. };
  3110. SIMDHelper.EnableSIMD = function () {
  3111. if (window.SIMD === undefined) {
  3112. return;
  3113. }
  3114. // Replace functions
  3115. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3116. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3117. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3118. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3119. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3120. Object.defineProperty(Vector3.prototype, "x", {
  3121. get: function () { return this._data[0]; },
  3122. set: function (value) {
  3123. if (!this._data) {
  3124. this._data = new Float32Array(3);
  3125. }
  3126. this._data[0] = value;
  3127. }
  3128. });
  3129. Object.defineProperty(Vector3.prototype, "y", {
  3130. get: function () { return this._data[1]; },
  3131. set: function (value) {
  3132. this._data[1] = value;
  3133. }
  3134. });
  3135. Object.defineProperty(Vector3.prototype, "z", {
  3136. get: function () { return this._data[2]; },
  3137. set: function (value) {
  3138. this._data[2] = value;
  3139. }
  3140. });
  3141. SIMDHelper._isEnabled = true;
  3142. };
  3143. SIMDHelper._isEnabled = false;
  3144. return SIMDHelper;
  3145. })();
  3146. BABYLON.SIMDHelper = SIMDHelper;
  3147. })(BABYLON || (BABYLON = {}));
  3148. var BABYLON;
  3149. (function (BABYLON) {
  3150. var Database = (function () {
  3151. function Database(urlToScene, callbackManifestChecked) {
  3152. // Handling various flavors of prefixed version of IndexedDB
  3153. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3154. this.callbackManifestChecked = callbackManifestChecked;
  3155. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3156. this.db = null;
  3157. this.enableSceneOffline = false;
  3158. this.enableTexturesOffline = false;
  3159. this.manifestVersionFound = 0;
  3160. this.mustUpdateRessources = false;
  3161. this.hasReachedQuota = false;
  3162. if (!Database.IDBStorageEnabled) {
  3163. this.callbackManifestChecked(true);
  3164. }
  3165. else {
  3166. this.checkManifestFile();
  3167. }
  3168. }
  3169. Database.prototype.checkManifestFile = function () {
  3170. var _this = this;
  3171. function noManifestFile() {
  3172. that.enableSceneOffline = false;
  3173. that.enableTexturesOffline = false;
  3174. that.callbackManifestChecked(false);
  3175. }
  3176. var that = this;
  3177. var manifestURL = this.currentSceneUrl + ".manifest";
  3178. var xhr = new XMLHttpRequest();
  3179. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3180. xhr.open("GET", manifestURLTimeStamped, true);
  3181. xhr.addEventListener("load", function () {
  3182. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3183. try {
  3184. var manifestFile = JSON.parse(xhr.response);
  3185. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3186. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3187. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3188. _this.manifestVersionFound = manifestFile.version;
  3189. }
  3190. if (_this.callbackManifestChecked) {
  3191. _this.callbackManifestChecked(true);
  3192. }
  3193. }
  3194. catch (ex) {
  3195. noManifestFile();
  3196. }
  3197. }
  3198. else {
  3199. noManifestFile();
  3200. }
  3201. }, false);
  3202. xhr.addEventListener("error", function (event) {
  3203. noManifestFile();
  3204. }, false);
  3205. try {
  3206. xhr.send();
  3207. }
  3208. catch (ex) {
  3209. BABYLON.Tools.Error("Error on XHR send request.");
  3210. that.callbackManifestChecked(false);
  3211. }
  3212. };
  3213. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3214. var _this = this;
  3215. function handleError() {
  3216. that.isSupported = false;
  3217. if (errorCallback)
  3218. errorCallback();
  3219. }
  3220. var that = this;
  3221. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3222. // Your browser doesn't support IndexedDB
  3223. this.isSupported = false;
  3224. if (errorCallback)
  3225. errorCallback();
  3226. }
  3227. else {
  3228. // If the DB hasn't been opened or created yet
  3229. if (!this.db) {
  3230. this.hasReachedQuota = false;
  3231. this.isSupported = true;
  3232. var request = this.idbFactory.open("babylonjs", 1);
  3233. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3234. request.onerror = function (event) {
  3235. handleError();
  3236. };
  3237. // executes when a version change transaction cannot complete due to other active transactions
  3238. request.onblocked = function (event) {
  3239. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3240. handleError();
  3241. };
  3242. // DB has been opened successfully
  3243. request.onsuccess = function (event) {
  3244. _this.db = request.result;
  3245. successCallback();
  3246. };
  3247. // Initialization of the DB. Creating Scenes & Textures stores
  3248. request.onupgradeneeded = function (event) {
  3249. _this.db = (event.target).result;
  3250. try {
  3251. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3252. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3253. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3254. }
  3255. catch (ex) {
  3256. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3257. handleError();
  3258. }
  3259. };
  3260. }
  3261. else {
  3262. if (successCallback)
  3263. successCallback();
  3264. }
  3265. }
  3266. };
  3267. Database.prototype.loadImageFromDB = function (url, image) {
  3268. var _this = this;
  3269. var completeURL = Database.ReturnFullUrlLocation(url);
  3270. var saveAndLoadImage = function () {
  3271. if (!_this.hasReachedQuota && _this.db !== null) {
  3272. // the texture is not yet in the DB, let's try to save it
  3273. _this._saveImageIntoDBAsync(completeURL, image);
  3274. }
  3275. else {
  3276. image.src = url;
  3277. }
  3278. };
  3279. if (!this.mustUpdateRessources) {
  3280. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3281. }
  3282. else {
  3283. saveAndLoadImage();
  3284. }
  3285. };
  3286. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3287. if (this.isSupported && this.db !== null) {
  3288. var texture;
  3289. var transaction = this.db.transaction(["textures"]);
  3290. transaction.onabort = function (event) {
  3291. image.src = url;
  3292. };
  3293. transaction.oncomplete = function (event) {
  3294. var blobTextureURL;
  3295. if (texture) {
  3296. var URL = window.URL || window.webkitURL;
  3297. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3298. image.onerror = function () {
  3299. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3300. image.src = url;
  3301. };
  3302. image.src = blobTextureURL;
  3303. }
  3304. else {
  3305. notInDBCallback();
  3306. }
  3307. };
  3308. var getRequest = transaction.objectStore("textures").get(url);
  3309. getRequest.onsuccess = function (event) {
  3310. texture = (event.target).result;
  3311. };
  3312. getRequest.onerror = function (event) {
  3313. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3314. image.src = url;
  3315. };
  3316. }
  3317. else {
  3318. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3319. image.src = url;
  3320. }
  3321. };
  3322. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3323. var _this = this;
  3324. if (this.isSupported) {
  3325. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3326. var generateBlobUrl = function () {
  3327. var blobTextureURL;
  3328. if (blob) {
  3329. var URL = window.URL || window.webkitURL;
  3330. try {
  3331. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3332. }
  3333. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3334. catch (ex) {
  3335. blobTextureURL = URL.createObjectURL(blob);
  3336. }
  3337. }
  3338. image.src = blobTextureURL;
  3339. };
  3340. if (Database.IsUASupportingBlobStorage) {
  3341. var xhr = new XMLHttpRequest(), blob;
  3342. xhr.open("GET", url, true);
  3343. xhr.responseType = "blob";
  3344. xhr.addEventListener("load", function () {
  3345. if (xhr.status === 200) {
  3346. // Blob as response (XHR2)
  3347. blob = xhr.response;
  3348. var transaction = _this.db.transaction(["textures"], "readwrite");
  3349. // the transaction could abort because of a QuotaExceededError error
  3350. transaction.onabort = function (event) {
  3351. try {
  3352. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3353. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3354. this.hasReachedQuota = true;
  3355. }
  3356. }
  3357. catch (ex) { }
  3358. generateBlobUrl();
  3359. };
  3360. transaction.oncomplete = function (event) {
  3361. generateBlobUrl();
  3362. };
  3363. var newTexture = { textureUrl: url, data: blob };
  3364. try {
  3365. // Put the blob into the dabase
  3366. var addRequest = transaction.objectStore("textures").put(newTexture);
  3367. addRequest.onsuccess = function (event) {
  3368. };
  3369. addRequest.onerror = function (event) {
  3370. generateBlobUrl();
  3371. };
  3372. }
  3373. catch (ex) {
  3374. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3375. if (ex.code === 25) {
  3376. Database.IsUASupportingBlobStorage = false;
  3377. }
  3378. image.src = url;
  3379. }
  3380. }
  3381. else {
  3382. image.src = url;
  3383. }
  3384. }, false);
  3385. xhr.addEventListener("error", function (event) {
  3386. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3387. image.src = url;
  3388. }, false);
  3389. xhr.send();
  3390. }
  3391. else {
  3392. image.src = url;
  3393. }
  3394. }
  3395. else {
  3396. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3397. image.src = url;
  3398. }
  3399. };
  3400. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3401. var _this = this;
  3402. var updateVersion = function (event) {
  3403. // the version is not yet in the DB or we need to update it
  3404. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3405. };
  3406. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3407. };
  3408. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3409. var _this = this;
  3410. if (this.isSupported) {
  3411. var version;
  3412. try {
  3413. var transaction = this.db.transaction(["versions"]);
  3414. transaction.oncomplete = function (event) {
  3415. if (version) {
  3416. // If the version in the JSON file is > than the version in DB
  3417. if (_this.manifestVersionFound > version.data) {
  3418. _this.mustUpdateRessources = true;
  3419. updateInDBCallback();
  3420. }
  3421. else {
  3422. callback(version.data);
  3423. }
  3424. }
  3425. else {
  3426. _this.mustUpdateRessources = true;
  3427. updateInDBCallback();
  3428. }
  3429. };
  3430. transaction.onabort = function (event) {
  3431. callback(-1);
  3432. };
  3433. var getRequest = transaction.objectStore("versions").get(url);
  3434. getRequest.onsuccess = function (event) {
  3435. version = (event.target).result;
  3436. };
  3437. getRequest.onerror = function (event) {
  3438. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3439. callback(-1);
  3440. };
  3441. }
  3442. catch (ex) {
  3443. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3444. callback(-1);
  3445. }
  3446. }
  3447. else {
  3448. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3449. callback(-1);
  3450. }
  3451. };
  3452. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3453. var _this = this;
  3454. if (this.isSupported && !this.hasReachedQuota) {
  3455. try {
  3456. // Open a transaction to the database
  3457. var transaction = this.db.transaction(["versions"], "readwrite");
  3458. // the transaction could abort because of a QuotaExceededError error
  3459. transaction.onabort = function (event) {
  3460. try {
  3461. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3462. _this.hasReachedQuota = true;
  3463. }
  3464. }
  3465. catch (ex) { }
  3466. callback(-1);
  3467. };
  3468. transaction.oncomplete = function (event) {
  3469. callback(_this.manifestVersionFound);
  3470. };
  3471. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3472. // Put the scene into the database
  3473. var addRequest = transaction.objectStore("versions").put(newVersion);
  3474. addRequest.onsuccess = function (event) {
  3475. };
  3476. addRequest.onerror = function (event) {
  3477. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3478. };
  3479. }
  3480. catch (ex) {
  3481. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3482. callback(-1);
  3483. }
  3484. }
  3485. else {
  3486. callback(-1);
  3487. }
  3488. };
  3489. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3490. var _this = this;
  3491. var completeUrl = Database.ReturnFullUrlLocation(url);
  3492. var saveAndLoadFile = function (event) {
  3493. // the scene is not yet in the DB, let's try to save it
  3494. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3495. };
  3496. this._checkVersionFromDB(completeUrl, function (version) {
  3497. if (version !== -1) {
  3498. if (!_this.mustUpdateRessources) {
  3499. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3500. }
  3501. else {
  3502. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3503. }
  3504. }
  3505. else {
  3506. errorCallback();
  3507. }
  3508. });
  3509. };
  3510. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3511. if (this.isSupported) {
  3512. var targetStore;
  3513. if (url.indexOf(".babylon") !== -1) {
  3514. targetStore = "scenes";
  3515. }
  3516. else {
  3517. targetStore = "textures";
  3518. }
  3519. var file;
  3520. var transaction = this.db.transaction([targetStore]);
  3521. transaction.oncomplete = function (event) {
  3522. if (file) {
  3523. callback(file.data);
  3524. }
  3525. else {
  3526. notInDBCallback();
  3527. }
  3528. };
  3529. transaction.onabort = function (event) {
  3530. notInDBCallback();
  3531. };
  3532. var getRequest = transaction.objectStore(targetStore).get(url);
  3533. getRequest.onsuccess = function (event) {
  3534. file = (event.target).result;
  3535. };
  3536. getRequest.onerror = function (event) {
  3537. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3538. notInDBCallback();
  3539. };
  3540. }
  3541. else {
  3542. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3543. callback();
  3544. }
  3545. };
  3546. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3547. var _this = this;
  3548. if (this.isSupported) {
  3549. var targetStore;
  3550. if (url.indexOf(".babylon") !== -1) {
  3551. targetStore = "scenes";
  3552. }
  3553. else {
  3554. targetStore = "textures";
  3555. }
  3556. // Create XHR
  3557. var xhr = new XMLHttpRequest(), fileData;
  3558. xhr.open("GET", url, true);
  3559. if (useArrayBuffer) {
  3560. xhr.responseType = "arraybuffer";
  3561. }
  3562. xhr.onprogress = progressCallback;
  3563. xhr.addEventListener("load", function () {
  3564. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3565. // Blob as response (XHR2)
  3566. //fileData = xhr.responseText;
  3567. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3568. if (!_this.hasReachedQuota) {
  3569. // Open a transaction to the database
  3570. var transaction = _this.db.transaction([targetStore], "readwrite");
  3571. // the transaction could abort because of a QuotaExceededError error
  3572. transaction.onabort = function (event) {
  3573. try {
  3574. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3575. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3576. this.hasReachedQuota = true;
  3577. }
  3578. }
  3579. catch (ex) { }
  3580. callback(fileData);
  3581. };
  3582. transaction.oncomplete = function (event) {
  3583. callback(fileData);
  3584. };
  3585. var newFile;
  3586. if (targetStore === "scenes") {
  3587. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3588. }
  3589. else {
  3590. newFile = { textureUrl: url, data: fileData };
  3591. }
  3592. try {
  3593. // Put the scene into the database
  3594. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3595. addRequest.onsuccess = function (event) {
  3596. };
  3597. addRequest.onerror = function (event) {
  3598. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3599. };
  3600. }
  3601. catch (ex) {
  3602. callback(fileData);
  3603. }
  3604. }
  3605. else {
  3606. callback(fileData);
  3607. }
  3608. }
  3609. else {
  3610. callback();
  3611. }
  3612. }, false);
  3613. xhr.addEventListener("error", function (event) {
  3614. BABYLON.Tools.Error("error on XHR request.");
  3615. callback();
  3616. }, false);
  3617. xhr.send();
  3618. }
  3619. else {
  3620. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3621. callback();
  3622. }
  3623. };
  3624. Database.IsUASupportingBlobStorage = true;
  3625. Database.IDBStorageEnabled = true;
  3626. Database.parseURL = function (url) {
  3627. var a = document.createElement('a');
  3628. a.href = url;
  3629. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3630. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3631. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3632. return absLocation;
  3633. };
  3634. Database.ReturnFullUrlLocation = function (url) {
  3635. if (url.indexOf("http:/") === -1) {
  3636. return (Database.parseURL(window.location.href) + url);
  3637. }
  3638. else {
  3639. return url;
  3640. }
  3641. };
  3642. return Database;
  3643. })();
  3644. BABYLON.Database = Database;
  3645. })(BABYLON || (BABYLON = {}));
  3646. var BABYLON;
  3647. (function (BABYLON) {
  3648. var Internals;
  3649. (function (Internals) {
  3650. /*
  3651. * Based on jsTGALoader - Javascript loader for TGA file
  3652. * By Vincent Thibault
  3653. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3654. */
  3655. var TGATools = (function () {
  3656. function TGATools() {
  3657. }
  3658. TGATools.GetTGAHeader = function (data) {
  3659. var offset = 0;
  3660. var header = {
  3661. id_length: data[offset++],
  3662. colormap_type: data[offset++],
  3663. image_type: data[offset++],
  3664. colormap_index: data[offset++] | data[offset++] << 8,
  3665. colormap_length: data[offset++] | data[offset++] << 8,
  3666. colormap_size: data[offset++],
  3667. origin: [
  3668. data[offset++] | data[offset++] << 8,
  3669. data[offset++] | data[offset++] << 8
  3670. ],
  3671. width: data[offset++] | data[offset++] << 8,
  3672. height: data[offset++] | data[offset++] << 8,
  3673. pixel_size: data[offset++],
  3674. flags: data[offset++]
  3675. };
  3676. return header;
  3677. };
  3678. TGATools.UploadContent = function (gl, data) {
  3679. // Not enough data to contain header ?
  3680. if (data.length < 19) {
  3681. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3682. return;
  3683. }
  3684. // Read Header
  3685. var offset = 18;
  3686. var header = TGATools.GetTGAHeader(data);
  3687. // Assume it's a valid Targa file.
  3688. if (header.id_length + offset > data.length) {
  3689. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3690. return;
  3691. }
  3692. // Skip not needed data
  3693. offset += header.id_length;
  3694. var use_rle = false;
  3695. var use_pal = false;
  3696. var use_rgb = false;
  3697. var use_grey = false;
  3698. // Get some informations.
  3699. switch (header.image_type) {
  3700. case TGATools._TYPE_RLE_INDEXED:
  3701. use_rle = true;
  3702. case TGATools._TYPE_INDEXED:
  3703. use_pal = true;
  3704. break;
  3705. case TGATools._TYPE_RLE_RGB:
  3706. use_rle = true;
  3707. case TGATools._TYPE_RGB:
  3708. use_rgb = true;
  3709. break;
  3710. case TGATools._TYPE_RLE_GREY:
  3711. use_rle = true;
  3712. case TGATools._TYPE_GREY:
  3713. use_grey = true;
  3714. break;
  3715. }
  3716. var pixel_data;
  3717. var numAlphaBits = header.flags & 0xf;
  3718. var pixel_size = header.pixel_size >> 3;
  3719. var pixel_total = header.width * header.height * pixel_size;
  3720. // Read palettes
  3721. var palettes;
  3722. if (use_pal) {
  3723. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3724. }
  3725. // Read LRE
  3726. if (use_rle) {
  3727. pixel_data = new Uint8Array(pixel_total);
  3728. var c, count, i;
  3729. var localOffset = 0;
  3730. var pixels = new Uint8Array(pixel_size);
  3731. while (offset < pixel_total && localOffset < pixel_total) {
  3732. c = data[offset++];
  3733. count = (c & 0x7f) + 1;
  3734. // RLE pixels
  3735. if (c & 0x80) {
  3736. // Bind pixel tmp array
  3737. for (i = 0; i < pixel_size; ++i) {
  3738. pixels[i] = data[offset++];
  3739. }
  3740. // Copy pixel array
  3741. for (i = 0; i < count; ++i) {
  3742. pixel_data.set(pixels, localOffset + i * pixel_size);
  3743. }
  3744. localOffset += pixel_size * count;
  3745. }
  3746. else {
  3747. count *= pixel_size;
  3748. for (i = 0; i < count; ++i) {
  3749. pixel_data[localOffset + i] = data[offset++];
  3750. }
  3751. localOffset += count;
  3752. }
  3753. }
  3754. }
  3755. else {
  3756. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3757. }
  3758. // Load to texture
  3759. var x_start, y_start, x_step, y_step, y_end, x_end;
  3760. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3761. default:
  3762. case TGATools._ORIGIN_UL:
  3763. x_start = 0;
  3764. x_step = 1;
  3765. x_end = header.width;
  3766. y_start = 0;
  3767. y_step = 1;
  3768. y_end = header.height;
  3769. break;
  3770. case TGATools._ORIGIN_BL:
  3771. x_start = 0;
  3772. x_step = 1;
  3773. x_end = header.width;
  3774. y_start = header.height - 1;
  3775. y_step = -1;
  3776. y_end = -1;
  3777. break;
  3778. case TGATools._ORIGIN_UR:
  3779. x_start = header.width - 1;
  3780. x_step = -1;
  3781. x_end = -1;
  3782. y_start = 0;
  3783. y_step = 1;
  3784. y_end = header.height;
  3785. break;
  3786. case TGATools._ORIGIN_BR:
  3787. x_start = header.width - 1;
  3788. x_step = -1;
  3789. x_end = -1;
  3790. y_start = header.height - 1;
  3791. y_step = -1;
  3792. y_end = -1;
  3793. break;
  3794. }
  3795. // Load the specify method
  3796. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3797. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3798. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3799. };
  3800. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3801. var image = pixel_data, colormap = palettes;
  3802. var width = header.width, height = header.height;
  3803. var color, i = 0, x, y;
  3804. var imageData = new Uint8Array(width * height * 4);
  3805. for (y = y_start; y !== y_end; y += y_step) {
  3806. for (x = x_start; x !== x_end; x += x_step, i++) {
  3807. color = image[i];
  3808. imageData[(x + width * y) * 4 + 3] = 255;
  3809. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3810. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3811. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3812. }
  3813. }
  3814. return imageData;
  3815. };
  3816. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3817. var image = pixel_data;
  3818. var width = header.width, height = header.height;
  3819. var color, i = 0, x, y;
  3820. var imageData = new Uint8Array(width * height * 4);
  3821. for (y = y_start; y !== y_end; y += y_step) {
  3822. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3823. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3824. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3825. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3826. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3827. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3828. }
  3829. }
  3830. return imageData;
  3831. };
  3832. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3833. var image = pixel_data;
  3834. var width = header.width, height = header.height;
  3835. var i = 0, x, y;
  3836. var imageData = new Uint8Array(width * height * 4);
  3837. for (y = y_start; y !== y_end; y += y_step) {
  3838. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3839. imageData[(x + width * y) * 4 + 3] = 255;
  3840. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3841. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3842. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3843. }
  3844. }
  3845. return imageData;
  3846. };
  3847. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3848. var image = pixel_data;
  3849. var width = header.width, height = header.height;
  3850. var i = 0, x, y;
  3851. var imageData = new Uint8Array(width * height * 4);
  3852. for (y = y_start; y !== y_end; y += y_step) {
  3853. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3854. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3855. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3856. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3857. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3858. }
  3859. }
  3860. return imageData;
  3861. };
  3862. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3863. var image = pixel_data;
  3864. var width = header.width, height = header.height;
  3865. var color, i = 0, x, y;
  3866. var imageData = new Uint8Array(width * height * 4);
  3867. for (y = y_start; y !== y_end; y += y_step) {
  3868. for (x = x_start; x !== x_end; x += x_step, i++) {
  3869. color = image[i];
  3870. imageData[(x + width * y) * 4 + 0] = color;
  3871. imageData[(x + width * y) * 4 + 1] = color;
  3872. imageData[(x + width * y) * 4 + 2] = color;
  3873. imageData[(x + width * y) * 4 + 3] = 255;
  3874. }
  3875. }
  3876. return imageData;
  3877. };
  3878. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3879. var image = pixel_data;
  3880. var width = header.width, height = header.height;
  3881. var i = 0, x, y;
  3882. var imageData = new Uint8Array(width * height * 4);
  3883. for (y = y_start; y !== y_end; y += y_step) {
  3884. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3885. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3886. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3887. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3888. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3889. }
  3890. }
  3891. return imageData;
  3892. };
  3893. TGATools._TYPE_NO_DATA = 0;
  3894. TGATools._TYPE_INDEXED = 1;
  3895. TGATools._TYPE_RGB = 2;
  3896. TGATools._TYPE_GREY = 3;
  3897. TGATools._TYPE_RLE_INDEXED = 9;
  3898. TGATools._TYPE_RLE_RGB = 10;
  3899. TGATools._TYPE_RLE_GREY = 11;
  3900. TGATools._ORIGIN_MASK = 0x30;
  3901. TGATools._ORIGIN_SHIFT = 0x04;
  3902. TGATools._ORIGIN_BL = 0x00;
  3903. TGATools._ORIGIN_BR = 0x01;
  3904. TGATools._ORIGIN_UL = 0x02;
  3905. TGATools._ORIGIN_UR = 0x03;
  3906. return TGATools;
  3907. })();
  3908. Internals.TGATools = TGATools;
  3909. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3910. })(BABYLON || (BABYLON = {}));
  3911. var BABYLON;
  3912. (function (BABYLON) {
  3913. var Internals;
  3914. (function (Internals) {
  3915. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3916. // All values and structures referenced from:
  3917. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3918. var DDS_MAGIC = 0x20534444;
  3919. 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;
  3920. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3921. 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;
  3922. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3923. function FourCCToInt32(value) {
  3924. return value.charCodeAt(0) +
  3925. (value.charCodeAt(1) << 8) +
  3926. (value.charCodeAt(2) << 16) +
  3927. (value.charCodeAt(3) << 24);
  3928. }
  3929. function Int32ToFourCC(value) {
  3930. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3931. }
  3932. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3933. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3934. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3935. var headerLengthInt = 31; // The header length in 32 bit ints
  3936. // Offsets into the header array
  3937. var off_magic = 0;
  3938. var off_size = 1;
  3939. var off_flags = 2;
  3940. var off_height = 3;
  3941. var off_width = 4;
  3942. var off_mipmapCount = 7;
  3943. var off_pfFlags = 20;
  3944. var off_pfFourCC = 21;
  3945. var off_RGBbpp = 22;
  3946. var off_RMask = 23;
  3947. var off_GMask = 24;
  3948. var off_BMask = 25;
  3949. var off_AMask = 26;
  3950. var off_caps1 = 27;
  3951. var off_caps2 = 28;
  3952. ;
  3953. var DDSTools = (function () {
  3954. function DDSTools() {
  3955. }
  3956. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3957. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3958. var mipmapCount = 1;
  3959. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3960. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3961. }
  3962. return {
  3963. width: header[off_width],
  3964. height: header[off_height],
  3965. mipmapCount: mipmapCount,
  3966. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3967. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3968. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3969. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3970. };
  3971. };
  3972. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3973. var byteArray = new Uint8Array(dataLength);
  3974. var srcData = new Uint8Array(arrayBuffer);
  3975. var index = 0;
  3976. for (var y = height - 1; y >= 0; y--) {
  3977. for (var x = 0; x < width; x++) {
  3978. var srcPos = dataOffset + (x + y * width) * 4;
  3979. byteArray[index + 2] = srcData[srcPos];
  3980. byteArray[index + 1] = srcData[srcPos + 1];
  3981. byteArray[index] = srcData[srcPos + 2];
  3982. byteArray[index + 3] = srcData[srcPos + 3];
  3983. index += 4;
  3984. }
  3985. }
  3986. return byteArray;
  3987. };
  3988. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3989. var byteArray = new Uint8Array(dataLength);
  3990. var srcData = new Uint8Array(arrayBuffer);
  3991. var index = 0;
  3992. for (var y = height - 1; y >= 0; y--) {
  3993. for (var x = 0; x < width; x++) {
  3994. var srcPos = dataOffset + (x + y * width) * 3;
  3995. byteArray[index + 2] = srcData[srcPos];
  3996. byteArray[index + 1] = srcData[srcPos + 1];
  3997. byteArray[index] = srcData[srcPos + 2];
  3998. index += 3;
  3999. }
  4000. }
  4001. return byteArray;
  4002. };
  4003. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  4004. var byteArray = new Uint8Array(dataLength);
  4005. var srcData = new Uint8Array(arrayBuffer);
  4006. var index = 0;
  4007. for (var y = height - 1; y >= 0; y--) {
  4008. for (var x = 0; x < width; x++) {
  4009. var srcPos = dataOffset + (x + y * width);
  4010. byteArray[index] = srcData[srcPos];
  4011. index++;
  4012. }
  4013. }
  4014. return byteArray;
  4015. };
  4016. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  4017. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  4018. if (header[off_magic] != DDS_MAGIC) {
  4019. BABYLON.Tools.Error("Invalid magic number in DDS header");
  4020. return;
  4021. }
  4022. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  4023. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  4024. return;
  4025. }
  4026. if (info.isFourCC) {
  4027. fourCC = header[off_pfFourCC];
  4028. switch (fourCC) {
  4029. case FOURCC_DXT1:
  4030. blockBytes = 8;
  4031. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  4032. break;
  4033. case FOURCC_DXT3:
  4034. blockBytes = 16;
  4035. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  4036. break;
  4037. case FOURCC_DXT5:
  4038. blockBytes = 16;
  4039. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  4040. break;
  4041. default:
  4042. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  4043. return;
  4044. }
  4045. }
  4046. mipmapCount = 1;
  4047. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4048. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4049. }
  4050. var bpp = header[off_RGBbpp];
  4051. for (var face = 0; face < faces; face++) {
  4052. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4053. width = header[off_width];
  4054. height = header[off_height];
  4055. dataOffset = header[off_size] + 4;
  4056. for (i = 0; i < mipmapCount; ++i) {
  4057. if (info.isRGB) {
  4058. if (bpp === 24) {
  4059. dataLength = width * height * 3;
  4060. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4061. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4062. }
  4063. else {
  4064. dataLength = width * height * 4;
  4065. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4066. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4067. }
  4068. }
  4069. else if (info.isLuminance) {
  4070. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4071. var unpaddedRowSize = width;
  4072. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4073. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4074. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4075. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4076. }
  4077. else {
  4078. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4079. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4080. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4081. }
  4082. dataOffset += dataLength;
  4083. width *= 0.5;
  4084. height *= 0.5;
  4085. width = Math.max(1.0, width);
  4086. height = Math.max(1.0, height);
  4087. }
  4088. }
  4089. };
  4090. return DDSTools;
  4091. })();
  4092. Internals.DDSTools = DDSTools;
  4093. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4094. })(BABYLON || (BABYLON = {}));
  4095. var BABYLON;
  4096. (function (BABYLON) {
  4097. var SmartArray = (function () {
  4098. function SmartArray(capacity) {
  4099. this.length = 0;
  4100. this._duplicateId = 0;
  4101. this.data = new Array(capacity);
  4102. this._id = SmartArray._GlobalId++;
  4103. }
  4104. SmartArray.prototype.push = function (value) {
  4105. this.data[this.length++] = value;
  4106. if (this.length > this.data.length) {
  4107. this.data.length *= 2;
  4108. }
  4109. if (!value.__smartArrayFlags) {
  4110. value.__smartArrayFlags = {};
  4111. }
  4112. value.__smartArrayFlags[this._id] = this._duplicateId;
  4113. };
  4114. SmartArray.prototype.pushNoDuplicate = function (value) {
  4115. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4116. return;
  4117. }
  4118. this.push(value);
  4119. };
  4120. SmartArray.prototype.sort = function (compareFn) {
  4121. this.data.sort(compareFn);
  4122. };
  4123. SmartArray.prototype.reset = function () {
  4124. this.length = 0;
  4125. this._duplicateId++;
  4126. };
  4127. SmartArray.prototype.concat = function (array) {
  4128. if (array.length === 0) {
  4129. return;
  4130. }
  4131. if (this.length + array.length > this.data.length) {
  4132. this.data.length = (this.length + array.length) * 2;
  4133. }
  4134. for (var index = 0; index < array.length; index++) {
  4135. this.data[this.length++] = (array.data || array)[index];
  4136. }
  4137. };
  4138. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4139. if (array.length === 0) {
  4140. return;
  4141. }
  4142. if (this.length + array.length > this.data.length) {
  4143. this.data.length = (this.length + array.length) * 2;
  4144. }
  4145. for (var index = 0; index < array.length; index++) {
  4146. var item = (array.data || array)[index];
  4147. this.pushNoDuplicate(item);
  4148. }
  4149. };
  4150. SmartArray.prototype.indexOf = function (value) {
  4151. var position = this.data.indexOf(value);
  4152. if (position >= this.length) {
  4153. return -1;
  4154. }
  4155. return position;
  4156. };
  4157. // Statics
  4158. SmartArray._GlobalId = 0;
  4159. return SmartArray;
  4160. })();
  4161. BABYLON.SmartArray = SmartArray;
  4162. })(BABYLON || (BABYLON = {}));
  4163. var BABYLON;
  4164. (function (BABYLON) {
  4165. var SmartCollection = (function () {
  4166. function SmartCollection(capacity) {
  4167. if (capacity === void 0) { capacity = 10; }
  4168. this.count = 0;
  4169. this._initialCapacity = capacity;
  4170. this.items = {};
  4171. this._keys = new Array(this._initialCapacity);
  4172. }
  4173. SmartCollection.prototype.add = function (key, item) {
  4174. if (this.items[key] != undefined) {
  4175. return -1;
  4176. }
  4177. this.items[key] = item;
  4178. //literal keys are always strings, but we keep source type of key in _keys array
  4179. this._keys[this.count++] = key;
  4180. if (this.count > this._keys.length) {
  4181. this._keys.length *= 2;
  4182. }
  4183. return this.count;
  4184. };
  4185. SmartCollection.prototype.remove = function (key) {
  4186. if (this.items[key] == undefined) {
  4187. return -1;
  4188. }
  4189. return this.removeItemOfIndex(this.indexOf(key));
  4190. };
  4191. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4192. if (index < this.count && index > -1) {
  4193. delete this.items[this._keys[index]];
  4194. //here, shifting by hand is better optimised than .splice
  4195. while (index < this.count) {
  4196. this._keys[index] = this._keys[index + 1];
  4197. index++;
  4198. }
  4199. }
  4200. else {
  4201. return -1;
  4202. }
  4203. return --this.count;
  4204. };
  4205. SmartCollection.prototype.indexOf = function (key) {
  4206. for (var i = 0; i !== this.count; i++) {
  4207. if (this._keys[i] === key) {
  4208. return i;
  4209. }
  4210. }
  4211. return -1;
  4212. };
  4213. SmartCollection.prototype.item = function (key) {
  4214. return this.items[key];
  4215. };
  4216. SmartCollection.prototype.getAllKeys = function () {
  4217. if (this.count > 0) {
  4218. var keys = new Array(this.count);
  4219. for (var i = 0; i < this.count; i++) {
  4220. keys[i] = this._keys[i];
  4221. }
  4222. return keys;
  4223. }
  4224. else {
  4225. return undefined;
  4226. }
  4227. };
  4228. SmartCollection.prototype.getKeyByIndex = function (index) {
  4229. if (index < this.count && index > -1) {
  4230. return this._keys[index];
  4231. }
  4232. else {
  4233. return undefined;
  4234. }
  4235. };
  4236. SmartCollection.prototype.getItemByIndex = function (index) {
  4237. if (index < this.count && index > -1) {
  4238. return this.items[this._keys[index]];
  4239. }
  4240. else {
  4241. return undefined;
  4242. }
  4243. };
  4244. SmartCollection.prototype.empty = function () {
  4245. if (this.count > 0) {
  4246. this.count = 0;
  4247. this.items = {};
  4248. this._keys = new Array(this._initialCapacity);
  4249. }
  4250. };
  4251. SmartCollection.prototype.forEach = function (block) {
  4252. var key;
  4253. for (key in this.items) {
  4254. if (this.items.hasOwnProperty(key)) {
  4255. block(this.items[key]);
  4256. }
  4257. }
  4258. };
  4259. return SmartCollection;
  4260. })();
  4261. BABYLON.SmartCollection = SmartCollection;
  4262. })(BABYLON || (BABYLON = {}));
  4263. var BABYLON;
  4264. (function (BABYLON) {
  4265. // Screenshots
  4266. var screenshotCanvas;
  4267. var cloneValue = function (source, destinationObject) {
  4268. if (!source)
  4269. return null;
  4270. if (source instanceof BABYLON.Mesh) {
  4271. return null;
  4272. }
  4273. if (source instanceof BABYLON.SubMesh) {
  4274. return source.clone(destinationObject);
  4275. }
  4276. else if (source.clone) {
  4277. return source.clone();
  4278. }
  4279. return null;
  4280. };
  4281. var Tools = (function () {
  4282. function Tools() {
  4283. }
  4284. Tools.ToHex = function (i) {
  4285. var str = i.toString(16);
  4286. if (i <= 15) {
  4287. return ("0" + str).toUpperCase();
  4288. }
  4289. return str.toUpperCase();
  4290. };
  4291. Tools.SetImmediate = function (action) {
  4292. if (window.setImmediate) {
  4293. window.setImmediate(action);
  4294. }
  4295. else {
  4296. setTimeout(action, 1);
  4297. }
  4298. };
  4299. Tools.IsExponentOfTwo = function (value) {
  4300. var count = 1;
  4301. do {
  4302. count *= 2;
  4303. } while (count < value);
  4304. return count === value;
  4305. };
  4306. Tools.GetExponentOfTwo = function (value, max) {
  4307. var count = 1;
  4308. do {
  4309. count *= 2;
  4310. } while (count < value);
  4311. if (count > max)
  4312. count = max;
  4313. return count;
  4314. };
  4315. Tools.GetFilename = function (path) {
  4316. var index = path.lastIndexOf("/");
  4317. if (index < 0)
  4318. return path;
  4319. return path.substring(index + 1);
  4320. };
  4321. Tools.GetDOMTextContent = function (element) {
  4322. var result = "";
  4323. var child = element.firstChild;
  4324. while (child) {
  4325. if (child.nodeType === 3) {
  4326. result += child.textContent;
  4327. }
  4328. child = child.nextSibling;
  4329. }
  4330. return result;
  4331. };
  4332. Tools.ToDegrees = function (angle) {
  4333. return angle * 180 / Math.PI;
  4334. };
  4335. Tools.ToRadians = function (angle) {
  4336. return angle * Math.PI / 180;
  4337. };
  4338. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4339. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4340. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4341. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4342. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4343. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4344. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4345. }
  4346. return {
  4347. minimum: minimum,
  4348. maximum: maximum
  4349. };
  4350. };
  4351. Tools.ExtractMinAndMax = function (positions, start, count) {
  4352. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4353. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4354. for (var index = start; index < start + count; index++) {
  4355. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4356. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4357. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4358. }
  4359. return {
  4360. minimum: minimum,
  4361. maximum: maximum
  4362. };
  4363. };
  4364. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4365. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4366. return undefined;
  4367. return Array.isArray(obj) ? obj : [obj];
  4368. };
  4369. // Misc.
  4370. Tools.GetPointerPrefix = function () {
  4371. var eventPrefix = "pointer";
  4372. // Check if hand.js is referenced or if the browser natively supports pointer events
  4373. if (!navigator.pointerEnabled) {
  4374. eventPrefix = "mouse";
  4375. }
  4376. return eventPrefix;
  4377. };
  4378. Tools.QueueNewFrame = function (func) {
  4379. if (window.requestAnimationFrame)
  4380. window.requestAnimationFrame(func);
  4381. else if (window.msRequestAnimationFrame)
  4382. window.msRequestAnimationFrame(func);
  4383. else if (window.webkitRequestAnimationFrame)
  4384. window.webkitRequestAnimationFrame(func);
  4385. else if (window.mozRequestAnimationFrame)
  4386. window.mozRequestAnimationFrame(func);
  4387. else if (window.oRequestAnimationFrame)
  4388. window.oRequestAnimationFrame(func);
  4389. else {
  4390. window.setTimeout(func, 16);
  4391. }
  4392. };
  4393. Tools.RequestFullscreen = function (element) {
  4394. if (element.requestFullscreen)
  4395. element.requestFullscreen();
  4396. else if (element.msRequestFullscreen)
  4397. element.msRequestFullscreen();
  4398. else if (element.webkitRequestFullscreen)
  4399. element.webkitRequestFullscreen();
  4400. else if (element.mozRequestFullScreen)
  4401. element.mozRequestFullScreen();
  4402. };
  4403. Tools.ExitFullscreen = function () {
  4404. if (document.exitFullscreen) {
  4405. document.exitFullscreen();
  4406. }
  4407. else if (document.mozCancelFullScreen) {
  4408. document.mozCancelFullScreen();
  4409. }
  4410. else if (document.webkitCancelFullScreen) {
  4411. document.webkitCancelFullScreen();
  4412. }
  4413. else if (document.msCancelFullScreen) {
  4414. document.msCancelFullScreen();
  4415. }
  4416. };
  4417. // External files
  4418. Tools.CleanUrl = function (url) {
  4419. url = url.replace(/#/mg, "%23");
  4420. return url;
  4421. };
  4422. Tools.LoadImage = function (url, onload, onerror, database) {
  4423. url = Tools.CleanUrl(url);
  4424. var img = new Image();
  4425. if (url.substr(0, 5) !== "data:")
  4426. img.crossOrigin = 'anonymous';
  4427. img.onload = function () {
  4428. onload(img);
  4429. };
  4430. img.onerror = function (err) {
  4431. Tools.Error("Error while trying to load texture: " + url);
  4432. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4433. onload(img);
  4434. };
  4435. var noIndexedDB = function () {
  4436. img.src = url;
  4437. };
  4438. var loadFromIndexedDB = function () {
  4439. database.loadImageFromDB(url, img);
  4440. };
  4441. //ANY database to do!
  4442. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4443. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4444. }
  4445. else {
  4446. if (url.indexOf("file:") === -1) {
  4447. noIndexedDB();
  4448. }
  4449. else {
  4450. try {
  4451. var textureName = url.substring(5);
  4452. var blobURL;
  4453. try {
  4454. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4455. }
  4456. catch (ex) {
  4457. // Chrome doesn't support oneTimeOnly parameter
  4458. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4459. }
  4460. img.src = blobURL;
  4461. }
  4462. catch (e) {
  4463. img.src = null;
  4464. }
  4465. }
  4466. }
  4467. return img;
  4468. };
  4469. //ANY
  4470. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4471. url = Tools.CleanUrl(url);
  4472. var noIndexedDB = function () {
  4473. var request = new XMLHttpRequest();
  4474. var loadUrl = Tools.BaseUrl + url;
  4475. request.open('GET', loadUrl, true);
  4476. if (useArrayBuffer) {
  4477. request.responseType = "arraybuffer";
  4478. }
  4479. request.onprogress = progressCallBack;
  4480. request.onreadystatechange = function () {
  4481. if (request.readyState === 4) {
  4482. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4483. callback(!useArrayBuffer ? request.responseText : request.response);
  4484. }
  4485. else {
  4486. if (onError) {
  4487. onError();
  4488. }
  4489. else {
  4490. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4491. }
  4492. }
  4493. }
  4494. };
  4495. request.send(null);
  4496. };
  4497. var loadFromIndexedDB = function () {
  4498. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4499. };
  4500. if (url.indexOf("file:") !== -1) {
  4501. var fileName = url.substring(5);
  4502. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4503. }
  4504. else {
  4505. // Caching all files
  4506. if (database && database.enableSceneOffline) {
  4507. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4508. }
  4509. else {
  4510. noIndexedDB();
  4511. }
  4512. }
  4513. };
  4514. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4515. var reader = new FileReader();
  4516. reader.onload = function (e) {
  4517. //target doesn't have result from ts 1.3
  4518. callback(e.target['result']);
  4519. };
  4520. reader.onprogress = progressCallback;
  4521. reader.readAsDataURL(fileToLoad);
  4522. };
  4523. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4524. var reader = new FileReader();
  4525. reader.onerror = function (e) {
  4526. Tools.Log("Error while reading file: " + fileToLoad.name);
  4527. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4528. };
  4529. reader.onload = function (e) {
  4530. //target doesn't have result from ts 1.3
  4531. callback(e.target['result']);
  4532. };
  4533. reader.onprogress = progressCallBack;
  4534. if (!useArrayBuffer) {
  4535. // Asynchronous read
  4536. reader.readAsText(fileToLoad);
  4537. }
  4538. else {
  4539. reader.readAsArrayBuffer(fileToLoad);
  4540. }
  4541. };
  4542. //returns a downloadable url to a file content.
  4543. Tools.FileAsURL = function (content) {
  4544. var fileBlob = new Blob([content]);
  4545. var url = window.URL || window.webkitURL;
  4546. var link = url.createObjectURL(fileBlob);
  4547. return link;
  4548. };
  4549. // Misc.
  4550. Tools.Clamp = function (value, min, max) {
  4551. if (min === void 0) { min = 0; }
  4552. if (max === void 0) { max = 1; }
  4553. return Math.min(max, Math.max(min, value));
  4554. };
  4555. // Returns -1 when value is a negative number and
  4556. // +1 when value is a positive number.
  4557. Tools.Sign = function (value) {
  4558. value = +value; // convert to a number
  4559. if (value === 0 || isNaN(value))
  4560. return value;
  4561. return value > 0 ? 1 : -1;
  4562. };
  4563. Tools.Format = function (value, decimals) {
  4564. if (decimals === void 0) { decimals = 2; }
  4565. return value.toFixed(decimals);
  4566. };
  4567. Tools.CheckExtends = function (v, min, max) {
  4568. if (v.x < min.x)
  4569. min.x = v.x;
  4570. if (v.y < min.y)
  4571. min.y = v.y;
  4572. if (v.z < min.z)
  4573. min.z = v.z;
  4574. if (v.x > max.x)
  4575. max.x = v.x;
  4576. if (v.y > max.y)
  4577. max.y = v.y;
  4578. if (v.z > max.z)
  4579. max.z = v.z;
  4580. };
  4581. Tools.WithinEpsilon = function (a, b, epsilon) {
  4582. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4583. var num = a - b;
  4584. return -epsilon <= num && num <= epsilon;
  4585. };
  4586. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4587. for (var prop in source) {
  4588. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4589. continue;
  4590. }
  4591. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4592. continue;
  4593. }
  4594. var sourceValue = source[prop];
  4595. var typeOfSourceValue = typeof sourceValue;
  4596. if (typeOfSourceValue === "function") {
  4597. continue;
  4598. }
  4599. if (typeOfSourceValue === "object") {
  4600. if (sourceValue instanceof Array) {
  4601. destination[prop] = [];
  4602. if (sourceValue.length > 0) {
  4603. if (typeof sourceValue[0] == "object") {
  4604. for (var index = 0; index < sourceValue.length; index++) {
  4605. var clonedValue = cloneValue(sourceValue[index], destination);
  4606. if (destination[prop].indexOf(clonedValue) === -1) {
  4607. destination[prop].push(clonedValue);
  4608. }
  4609. }
  4610. }
  4611. else {
  4612. destination[prop] = sourceValue.slice(0);
  4613. }
  4614. }
  4615. }
  4616. else {
  4617. destination[prop] = cloneValue(sourceValue, destination);
  4618. }
  4619. }
  4620. else {
  4621. destination[prop] = sourceValue;
  4622. }
  4623. }
  4624. };
  4625. Tools.IsEmpty = function (obj) {
  4626. for (var i in obj) {
  4627. return false;
  4628. }
  4629. return true;
  4630. };
  4631. Tools.RegisterTopRootEvents = function (events) {
  4632. for (var index = 0; index < events.length; index++) {
  4633. var event = events[index];
  4634. window.addEventListener(event.name, event.handler, false);
  4635. try {
  4636. if (window.parent) {
  4637. window.parent.addEventListener(event.name, event.handler, false);
  4638. }
  4639. }
  4640. catch (e) {
  4641. }
  4642. }
  4643. };
  4644. Tools.UnregisterTopRootEvents = function (events) {
  4645. for (var index = 0; index < events.length; index++) {
  4646. var event = events[index];
  4647. window.removeEventListener(event.name, event.handler);
  4648. try {
  4649. if (window.parent) {
  4650. window.parent.removeEventListener(event.name, event.handler);
  4651. }
  4652. }
  4653. catch (e) {
  4654. }
  4655. }
  4656. };
  4657. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4658. // Read the contents of the framebuffer
  4659. var numberOfChannelsByLine = width * 4;
  4660. var halfHeight = height / 2;
  4661. //Reading datas from WebGL
  4662. var data = engine.readPixels(0, 0, width, height);
  4663. //To flip image on Y axis.
  4664. for (var i = 0; i < halfHeight; i++) {
  4665. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4666. var currentCell = j + i * numberOfChannelsByLine;
  4667. var targetLine = height - i - 1;
  4668. var targetCell = j + targetLine * numberOfChannelsByLine;
  4669. var temp = data[currentCell];
  4670. data[currentCell] = data[targetCell];
  4671. data[targetCell] = temp;
  4672. }
  4673. }
  4674. // Create a 2D canvas to store the result
  4675. if (!screenshotCanvas) {
  4676. screenshotCanvas = document.createElement('canvas');
  4677. }
  4678. screenshotCanvas.width = width;
  4679. screenshotCanvas.height = height;
  4680. var context = screenshotCanvas.getContext('2d');
  4681. // Copy the pixels to a 2D canvas
  4682. var imageData = context.createImageData(width, height);
  4683. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4684. var castData = imageData.data;
  4685. castData.set(data);
  4686. context.putImageData(imageData, 0, 0);
  4687. var base64Image = screenshotCanvas.toDataURL();
  4688. if (successCallback) {
  4689. successCallback(base64Image);
  4690. }
  4691. else {
  4692. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4693. if (("download" in document.createElement("a"))) {
  4694. var a = window.document.createElement("a");
  4695. a.href = base64Image;
  4696. var date = new Date();
  4697. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4698. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4699. window.document.body.appendChild(a);
  4700. a.addEventListener("click", function () {
  4701. a.parentElement.removeChild(a);
  4702. });
  4703. a.click();
  4704. }
  4705. else {
  4706. var newWindow = window.open("");
  4707. var img = newWindow.document.createElement("img");
  4708. img.src = base64Image;
  4709. newWindow.document.body.appendChild(img);
  4710. }
  4711. }
  4712. };
  4713. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4714. var width;
  4715. var height;
  4716. //If a precision value is specified
  4717. if (size.precision) {
  4718. width = Math.round(engine.getRenderWidth() * size.precision);
  4719. height = Math.round(width / engine.getAspectRatio(camera));
  4720. size = { width: width, height: height };
  4721. }
  4722. else if (size.width && size.height) {
  4723. width = size.width;
  4724. height = size.height;
  4725. }
  4726. else if (size.width && !size.height) {
  4727. width = size.width;
  4728. height = Math.round(width / engine.getAspectRatio(camera));
  4729. size = { width: width, height: height };
  4730. }
  4731. else if (size.height && !size.width) {
  4732. height = size.height;
  4733. width = Math.round(height * engine.getAspectRatio(camera));
  4734. size = { width: width, height: height };
  4735. }
  4736. else if (!isNaN(size)) {
  4737. height = size;
  4738. width = size;
  4739. }
  4740. else {
  4741. Tools.Error("Invalid 'size' parameter !");
  4742. return;
  4743. }
  4744. var scene = camera.getScene();
  4745. var previousCamera = null;
  4746. if (scene.activeCamera !== camera) {
  4747. previousCamera = scene.activeCamera;
  4748. scene.activeCamera = camera;
  4749. }
  4750. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4751. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4752. texture.renderList = scene.meshes;
  4753. texture.onAfterRender = function () {
  4754. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4755. };
  4756. scene.incrementRenderId();
  4757. texture.render(true);
  4758. texture.dispose();
  4759. if (previousCamera) {
  4760. scene.activeCamera = previousCamera;
  4761. }
  4762. };
  4763. // XHR response validator for local file scenario
  4764. Tools.ValidateXHRData = function (xhr, dataType) {
  4765. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4766. if (dataType === void 0) { dataType = 7; }
  4767. try {
  4768. if (dataType & 1) {
  4769. if (xhr.responseText && xhr.responseText.length > 0) {
  4770. return true;
  4771. }
  4772. else if (dataType === 1) {
  4773. return false;
  4774. }
  4775. }
  4776. if (dataType & 2) {
  4777. // Check header width and height since there is no "TGA" magic number
  4778. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4779. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4780. return true;
  4781. }
  4782. else if (dataType === 2) {
  4783. return false;
  4784. }
  4785. }
  4786. if (dataType & 4) {
  4787. // Check for the "DDS" magic number
  4788. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4789. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4790. return true;
  4791. }
  4792. else {
  4793. return false;
  4794. }
  4795. }
  4796. }
  4797. catch (e) {
  4798. }
  4799. return false;
  4800. };
  4801. Object.defineProperty(Tools, "NoneLogLevel", {
  4802. get: function () {
  4803. return Tools._NoneLogLevel;
  4804. },
  4805. enumerable: true,
  4806. configurable: true
  4807. });
  4808. Object.defineProperty(Tools, "MessageLogLevel", {
  4809. get: function () {
  4810. return Tools._MessageLogLevel;
  4811. },
  4812. enumerable: true,
  4813. configurable: true
  4814. });
  4815. Object.defineProperty(Tools, "WarningLogLevel", {
  4816. get: function () {
  4817. return Tools._WarningLogLevel;
  4818. },
  4819. enumerable: true,
  4820. configurable: true
  4821. });
  4822. Object.defineProperty(Tools, "ErrorLogLevel", {
  4823. get: function () {
  4824. return Tools._ErrorLogLevel;
  4825. },
  4826. enumerable: true,
  4827. configurable: true
  4828. });
  4829. Object.defineProperty(Tools, "AllLogLevel", {
  4830. get: function () {
  4831. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4832. },
  4833. enumerable: true,
  4834. configurable: true
  4835. });
  4836. Tools._AddLogEntry = function (entry) {
  4837. Tools._LogCache = entry + Tools._LogCache;
  4838. if (Tools.OnNewCacheEntry) {
  4839. Tools.OnNewCacheEntry(entry);
  4840. }
  4841. };
  4842. Tools._FormatMessage = function (message) {
  4843. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4844. var date = new Date();
  4845. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4846. };
  4847. Tools._LogDisabled = function (message) {
  4848. // nothing to do
  4849. };
  4850. Tools._LogEnabled = function (message) {
  4851. var formattedMessage = Tools._FormatMessage(message);
  4852. console.log("BJS - " + formattedMessage);
  4853. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4854. Tools._AddLogEntry(entry);
  4855. };
  4856. Tools._WarnDisabled = function (message) {
  4857. // nothing to do
  4858. };
  4859. Tools._WarnEnabled = function (message) {
  4860. var formattedMessage = Tools._FormatMessage(message);
  4861. console.warn("BJS - " + formattedMessage);
  4862. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4863. Tools._AddLogEntry(entry);
  4864. };
  4865. Tools._ErrorDisabled = function (message) {
  4866. // nothing to do
  4867. };
  4868. Tools._ErrorEnabled = function (message) {
  4869. Tools.errorsCount++;
  4870. var formattedMessage = Tools._FormatMessage(message);
  4871. console.error("BJS - " + formattedMessage);
  4872. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4873. Tools._AddLogEntry(entry);
  4874. };
  4875. Object.defineProperty(Tools, "LogCache", {
  4876. get: function () {
  4877. return Tools._LogCache;
  4878. },
  4879. enumerable: true,
  4880. configurable: true
  4881. });
  4882. Tools.ClearLogCache = function () {
  4883. Tools._LogCache = "";
  4884. Tools.errorsCount = 0;
  4885. };
  4886. Object.defineProperty(Tools, "LogLevels", {
  4887. set: function (level) {
  4888. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4889. Tools.Log = Tools._LogEnabled;
  4890. }
  4891. else {
  4892. Tools.Log = Tools._LogDisabled;
  4893. }
  4894. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4895. Tools.Warn = Tools._WarnEnabled;
  4896. }
  4897. else {
  4898. Tools.Warn = Tools._WarnDisabled;
  4899. }
  4900. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4901. Tools.Error = Tools._ErrorEnabled;
  4902. }
  4903. else {
  4904. Tools.Error = Tools._ErrorDisabled;
  4905. }
  4906. },
  4907. enumerable: true,
  4908. configurable: true
  4909. });
  4910. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4911. get: function () {
  4912. return Tools._PerformanceNoneLogLevel;
  4913. },
  4914. enumerable: true,
  4915. configurable: true
  4916. });
  4917. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4918. get: function () {
  4919. return Tools._PerformanceUserMarkLogLevel;
  4920. },
  4921. enumerable: true,
  4922. configurable: true
  4923. });
  4924. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4925. get: function () {
  4926. return Tools._PerformanceConsoleLogLevel;
  4927. },
  4928. enumerable: true,
  4929. configurable: true
  4930. });
  4931. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4932. set: function (level) {
  4933. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4934. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4935. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4936. return;
  4937. }
  4938. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4939. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4940. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4941. return;
  4942. }
  4943. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4944. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4945. },
  4946. enumerable: true,
  4947. configurable: true
  4948. });
  4949. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4950. };
  4951. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4952. };
  4953. Tools._StartUserMark = function (counterName, condition) {
  4954. if (condition === void 0) { condition = true; }
  4955. if (!condition || !Tools._performance.mark) {
  4956. return;
  4957. }
  4958. Tools._performance.mark(counterName + "-Begin");
  4959. };
  4960. Tools._EndUserMark = function (counterName, condition) {
  4961. if (condition === void 0) { condition = true; }
  4962. if (!condition || !Tools._performance.mark) {
  4963. return;
  4964. }
  4965. Tools._performance.mark(counterName + "-End");
  4966. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4967. };
  4968. Tools._StartPerformanceConsole = function (counterName, condition) {
  4969. if (condition === void 0) { condition = true; }
  4970. if (!condition) {
  4971. return;
  4972. }
  4973. Tools._StartUserMark(counterName, condition);
  4974. if (console.time) {
  4975. console.time(counterName);
  4976. }
  4977. };
  4978. Tools._EndPerformanceConsole = function (counterName, condition) {
  4979. if (condition === void 0) { condition = true; }
  4980. if (!condition) {
  4981. return;
  4982. }
  4983. Tools._EndUserMark(counterName, condition);
  4984. if (console.time) {
  4985. console.timeEnd(counterName);
  4986. }
  4987. };
  4988. Object.defineProperty(Tools, "Now", {
  4989. get: function () {
  4990. if (window.performance && window.performance.now) {
  4991. return window.performance.now();
  4992. }
  4993. return new Date().getTime();
  4994. },
  4995. enumerable: true,
  4996. configurable: true
  4997. });
  4998. // Deprecated
  4999. Tools.GetFps = function () {
  5000. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  5001. return 0;
  5002. };
  5003. Tools.BaseUrl = "";
  5004. // Logs
  5005. Tools._NoneLogLevel = 0;
  5006. Tools._MessageLogLevel = 1;
  5007. Tools._WarningLogLevel = 2;
  5008. Tools._ErrorLogLevel = 4;
  5009. Tools._LogCache = "";
  5010. Tools.errorsCount = 0;
  5011. Tools.Log = Tools._LogEnabled;
  5012. Tools.Warn = Tools._WarnEnabled;
  5013. Tools.Error = Tools._ErrorEnabled;
  5014. // Performances
  5015. Tools._PerformanceNoneLogLevel = 0;
  5016. Tools._PerformanceUserMarkLogLevel = 1;
  5017. Tools._PerformanceConsoleLogLevel = 2;
  5018. Tools._performance = window.performance;
  5019. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5020. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5021. return Tools;
  5022. })();
  5023. BABYLON.Tools = Tools;
  5024. /**
  5025. * An implementation of a loop for asynchronous functions.
  5026. */
  5027. var AsyncLoop = (function () {
  5028. /**
  5029. * Constroctor.
  5030. * @param iterations the number of iterations.
  5031. * @param _fn the function to run each iteration
  5032. * @param _successCallback the callback that will be called upon succesful execution
  5033. * @param offset starting offset.
  5034. */
  5035. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5036. if (offset === void 0) { offset = 0; }
  5037. this.iterations = iterations;
  5038. this._fn = _fn;
  5039. this._successCallback = _successCallback;
  5040. this.index = offset - 1;
  5041. this._done = false;
  5042. }
  5043. /**
  5044. * Execute the next iteration. Must be called after the last iteration was finished.
  5045. */
  5046. AsyncLoop.prototype.executeNext = function () {
  5047. if (!this._done) {
  5048. if (this.index + 1 < this.iterations) {
  5049. ++this.index;
  5050. this._fn(this);
  5051. }
  5052. else {
  5053. this.breakLoop();
  5054. }
  5055. }
  5056. };
  5057. /**
  5058. * Break the loop and run the success callback.
  5059. */
  5060. AsyncLoop.prototype.breakLoop = function () {
  5061. this._done = true;
  5062. this._successCallback();
  5063. };
  5064. /**
  5065. * Helper function
  5066. */
  5067. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5068. if (offset === void 0) { offset = 0; }
  5069. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5070. loop.executeNext();
  5071. return loop;
  5072. };
  5073. /**
  5074. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5075. * @param iterations total number of iterations
  5076. * @param syncedIterations number of synchronous iterations in each async iteration.
  5077. * @param fn the function to call each iteration.
  5078. * @param callback a success call back that will be called when iterating stops.
  5079. * @param breakFunction a break condition (optional)
  5080. * @param timeout timeout settings for the setTimeout function. default - 0.
  5081. * @constructor
  5082. */
  5083. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5084. if (timeout === void 0) { timeout = 0; }
  5085. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5086. if (breakFunction && breakFunction())
  5087. loop.breakLoop();
  5088. else {
  5089. setTimeout(function () {
  5090. for (var i = 0; i < syncedIterations; ++i) {
  5091. var iteration = (loop.index * syncedIterations) + i;
  5092. if (iteration >= iterations)
  5093. break;
  5094. fn(iteration);
  5095. if (breakFunction && breakFunction()) {
  5096. loop.breakLoop();
  5097. break;
  5098. }
  5099. }
  5100. loop.executeNext();
  5101. }, timeout);
  5102. }
  5103. }, callback);
  5104. };
  5105. return AsyncLoop;
  5106. })();
  5107. BABYLON.AsyncLoop = AsyncLoop;
  5108. })(BABYLON || (BABYLON = {}));
  5109. var BABYLON;
  5110. (function (BABYLON) {
  5111. var _DepthCullingState = (function () {
  5112. function _DepthCullingState() {
  5113. this._isDepthTestDirty = false;
  5114. this._isDepthMaskDirty = false;
  5115. this._isDepthFuncDirty = false;
  5116. this._isCullFaceDirty = false;
  5117. this._isCullDirty = false;
  5118. this._isZOffsetDirty = false;
  5119. }
  5120. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5121. get: function () {
  5122. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5123. },
  5124. enumerable: true,
  5125. configurable: true
  5126. });
  5127. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5128. get: function () {
  5129. return this._zOffset;
  5130. },
  5131. set: function (value) {
  5132. if (this._zOffset === value) {
  5133. return;
  5134. }
  5135. this._zOffset = value;
  5136. this._isZOffsetDirty = true;
  5137. },
  5138. enumerable: true,
  5139. configurable: true
  5140. });
  5141. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5142. get: function () {
  5143. return this._cullFace;
  5144. },
  5145. set: function (value) {
  5146. if (this._cullFace === value) {
  5147. return;
  5148. }
  5149. this._cullFace = value;
  5150. this._isCullFaceDirty = true;
  5151. },
  5152. enumerable: true,
  5153. configurable: true
  5154. });
  5155. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5156. get: function () {
  5157. return this._cull;
  5158. },
  5159. set: function (value) {
  5160. if (this._cull === value) {
  5161. return;
  5162. }
  5163. this._cull = value;
  5164. this._isCullDirty = true;
  5165. },
  5166. enumerable: true,
  5167. configurable: true
  5168. });
  5169. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5170. get: function () {
  5171. return this._depthFunc;
  5172. },
  5173. set: function (value) {
  5174. if (this._depthFunc === value) {
  5175. return;
  5176. }
  5177. this._depthFunc = value;
  5178. this._isDepthFuncDirty = true;
  5179. },
  5180. enumerable: true,
  5181. configurable: true
  5182. });
  5183. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5184. get: function () {
  5185. return this._depthMask;
  5186. },
  5187. set: function (value) {
  5188. if (this._depthMask === value) {
  5189. return;
  5190. }
  5191. this._depthMask = value;
  5192. this._isDepthMaskDirty = true;
  5193. },
  5194. enumerable: true,
  5195. configurable: true
  5196. });
  5197. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5198. get: function () {
  5199. return this._depthTest;
  5200. },
  5201. set: function (value) {
  5202. if (this._depthTest === value) {
  5203. return;
  5204. }
  5205. this._depthTest = value;
  5206. this._isDepthTestDirty = true;
  5207. },
  5208. enumerable: true,
  5209. configurable: true
  5210. });
  5211. _DepthCullingState.prototype.reset = function () {
  5212. this._depthMask = true;
  5213. this._depthTest = true;
  5214. this._depthFunc = null;
  5215. this._cull = null;
  5216. this._cullFace = null;
  5217. this._zOffset = 0;
  5218. this._isDepthTestDirty = true;
  5219. this._isDepthMaskDirty = true;
  5220. this._isDepthFuncDirty = false;
  5221. this._isCullFaceDirty = false;
  5222. this._isCullDirty = false;
  5223. this._isZOffsetDirty = false;
  5224. };
  5225. _DepthCullingState.prototype.apply = function (gl) {
  5226. if (!this.isDirty) {
  5227. return;
  5228. }
  5229. // Cull
  5230. if (this._isCullDirty) {
  5231. if (this.cull) {
  5232. gl.enable(gl.CULL_FACE);
  5233. }
  5234. else {
  5235. gl.disable(gl.CULL_FACE);
  5236. }
  5237. this._isCullDirty = false;
  5238. }
  5239. // Cull face
  5240. if (this._isCullFaceDirty) {
  5241. gl.cullFace(this.cullFace);
  5242. this._isCullFaceDirty = false;
  5243. }
  5244. // Depth mask
  5245. if (this._isDepthMaskDirty) {
  5246. gl.depthMask(this.depthMask);
  5247. this._isDepthMaskDirty = false;
  5248. }
  5249. // Depth test
  5250. if (this._isDepthTestDirty) {
  5251. if (this.depthTest) {
  5252. gl.enable(gl.DEPTH_TEST);
  5253. }
  5254. else {
  5255. gl.disable(gl.DEPTH_TEST);
  5256. }
  5257. this._isDepthTestDirty = false;
  5258. }
  5259. // Depth func
  5260. if (this._isDepthFuncDirty) {
  5261. gl.depthFunc(this.depthFunc);
  5262. this._isDepthFuncDirty = false;
  5263. }
  5264. // zOffset
  5265. if (this._isZOffsetDirty) {
  5266. if (this.zOffset) {
  5267. gl.enable(gl.POLYGON_OFFSET_FILL);
  5268. gl.polygonOffset(this.zOffset, 0);
  5269. }
  5270. else {
  5271. gl.disable(gl.POLYGON_OFFSET_FILL);
  5272. }
  5273. this._isZOffsetDirty = false;
  5274. }
  5275. };
  5276. return _DepthCullingState;
  5277. })();
  5278. BABYLON._DepthCullingState = _DepthCullingState;
  5279. var _AlphaState = (function () {
  5280. function _AlphaState() {
  5281. this._isAlphaBlendDirty = false;
  5282. this._isBlendFunctionParametersDirty = false;
  5283. this._alphaBlend = false;
  5284. this._blendFunctionParameters = new Array(4);
  5285. }
  5286. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5287. get: function () {
  5288. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5289. },
  5290. enumerable: true,
  5291. configurable: true
  5292. });
  5293. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5294. get: function () {
  5295. return this._alphaBlend;
  5296. },
  5297. set: function (value) {
  5298. if (this._alphaBlend === value) {
  5299. return;
  5300. }
  5301. this._alphaBlend = value;
  5302. this._isAlphaBlendDirty = true;
  5303. },
  5304. enumerable: true,
  5305. configurable: true
  5306. });
  5307. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5308. if (this._blendFunctionParameters[0] === value0 &&
  5309. this._blendFunctionParameters[1] === value1 &&
  5310. this._blendFunctionParameters[2] === value2 &&
  5311. this._blendFunctionParameters[3] === value3) {
  5312. return;
  5313. }
  5314. this._blendFunctionParameters[0] = value0;
  5315. this._blendFunctionParameters[1] = value1;
  5316. this._blendFunctionParameters[2] = value2;
  5317. this._blendFunctionParameters[3] = value3;
  5318. this._isBlendFunctionParametersDirty = true;
  5319. };
  5320. _AlphaState.prototype.reset = function () {
  5321. this._alphaBlend = false;
  5322. this._blendFunctionParameters[0] = null;
  5323. this._blendFunctionParameters[1] = null;
  5324. this._blendFunctionParameters[2] = null;
  5325. this._blendFunctionParameters[3] = null;
  5326. this._isAlphaBlendDirty = true;
  5327. this._isBlendFunctionParametersDirty = false;
  5328. };
  5329. _AlphaState.prototype.apply = function (gl) {
  5330. if (!this.isDirty) {
  5331. return;
  5332. }
  5333. // Alpha blend
  5334. if (this._isAlphaBlendDirty) {
  5335. if (this._alphaBlend) {
  5336. gl.enable(gl.BLEND);
  5337. }
  5338. else {
  5339. gl.disable(gl.BLEND);
  5340. }
  5341. this._isAlphaBlendDirty = false;
  5342. }
  5343. // Alpha function
  5344. if (this._isBlendFunctionParametersDirty) {
  5345. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5346. this._isBlendFunctionParametersDirty = false;
  5347. }
  5348. };
  5349. return _AlphaState;
  5350. })();
  5351. BABYLON._AlphaState = _AlphaState;
  5352. var compileShader = function (gl, source, type, defines) {
  5353. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5354. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5355. gl.compileShader(shader);
  5356. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5357. throw new Error(gl.getShaderInfoLog(shader));
  5358. }
  5359. return shader;
  5360. };
  5361. var getWebGLTextureType = function (gl, type) {
  5362. var textureType = gl.UNSIGNED_BYTE;
  5363. if (type === Engine.TEXTURETYPE_FLOAT)
  5364. textureType = gl.FLOAT;
  5365. return textureType;
  5366. };
  5367. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5368. var magFilter = gl.NEAREST;
  5369. var minFilter = gl.NEAREST;
  5370. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5371. magFilter = gl.LINEAR;
  5372. if (generateMipMaps) {
  5373. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5374. }
  5375. else {
  5376. minFilter = gl.LINEAR;
  5377. }
  5378. }
  5379. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5380. magFilter = gl.LINEAR;
  5381. if (generateMipMaps) {
  5382. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5383. }
  5384. else {
  5385. minFilter = gl.LINEAR;
  5386. }
  5387. }
  5388. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5389. magFilter = gl.NEAREST;
  5390. if (generateMipMaps) {
  5391. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5392. }
  5393. else {
  5394. minFilter = gl.NEAREST;
  5395. }
  5396. }
  5397. return {
  5398. min: minFilter,
  5399. mag: magFilter
  5400. };
  5401. };
  5402. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5403. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5404. var engine = scene.getEngine();
  5405. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5406. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5407. gl.bindTexture(gl.TEXTURE_2D, texture);
  5408. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5409. texture._baseWidth = width;
  5410. texture._baseHeight = height;
  5411. texture._width = potWidth;
  5412. texture._height = potHeight;
  5413. texture.isReady = true;
  5414. processFunction(potWidth, potHeight);
  5415. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5418. if (!noMipmap && !isCompressed) {
  5419. gl.generateMipmap(gl.TEXTURE_2D);
  5420. }
  5421. gl.bindTexture(gl.TEXTURE_2D, null);
  5422. engine._activeTexturesCache = [];
  5423. scene._removePendingData(texture);
  5424. };
  5425. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5426. var onload = function () {
  5427. loadedImages[index] = img;
  5428. loadedImages._internalCount++;
  5429. scene._removePendingData(img);
  5430. if (loadedImages._internalCount === 6) {
  5431. onfinish(loadedImages);
  5432. }
  5433. };
  5434. var onerror = function () {
  5435. scene._removePendingData(img);
  5436. };
  5437. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5438. scene._addPendingData(img);
  5439. };
  5440. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5441. var loadedImages = [];
  5442. loadedImages._internalCount = 0;
  5443. for (var index = 0; index < 6; index++) {
  5444. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5445. }
  5446. };
  5447. var EngineCapabilities = (function () {
  5448. function EngineCapabilities() {
  5449. }
  5450. return EngineCapabilities;
  5451. })();
  5452. BABYLON.EngineCapabilities = EngineCapabilities;
  5453. /**
  5454. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5455. */
  5456. var Engine = (function () {
  5457. /**
  5458. * @constructor
  5459. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5460. * @param {boolean} [antialias] - enable antialias
  5461. * @param options - further options to be sent to the getContext function
  5462. */
  5463. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5464. var _this = this;
  5465. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5466. // Public members
  5467. this.isFullscreen = false;
  5468. this.isPointerLock = false;
  5469. this.cullBackFaces = true;
  5470. this.renderEvenInBackground = true;
  5471. // To enable/disable IDB support and avoid XHR on .manifest
  5472. this.enableOfflineSupport = true;
  5473. this.scenes = new Array();
  5474. this._windowIsBackground = false;
  5475. this._drawCalls = 0;
  5476. this._renderingQueueLaunched = false;
  5477. this._activeRenderLoops = [];
  5478. // FPS
  5479. this.fpsRange = 60;
  5480. this.previousFramesDuration = [];
  5481. this.fps = 60;
  5482. this.deltaTime = 0;
  5483. // States
  5484. this._depthCullingState = new _DepthCullingState();
  5485. this._alphaState = new _AlphaState();
  5486. this._alphaMode = Engine.ALPHA_DISABLE;
  5487. // Cache
  5488. this._loadedTexturesCache = new Array();
  5489. this._activeTexturesCache = new Array();
  5490. this._compiledEffects = {};
  5491. this._uintIndicesCurrentlySet = false;
  5492. this._renderingCanvas = canvas;
  5493. options = options || {};
  5494. options.antialias = antialias;
  5495. if (options.preserveDrawingBuffer === undefined) {
  5496. options.preserveDrawingBuffer = false;
  5497. }
  5498. // GL
  5499. try {
  5500. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5501. }
  5502. catch (e) {
  5503. throw new Error("WebGL not supported");
  5504. }
  5505. if (!this._gl) {
  5506. throw new Error("WebGL not supported");
  5507. }
  5508. this._onBlur = function () {
  5509. _this._windowIsBackground = true;
  5510. };
  5511. this._onFocus = function () {
  5512. _this._windowIsBackground = false;
  5513. };
  5514. window.addEventListener("blur", this._onBlur);
  5515. window.addEventListener("focus", this._onFocus);
  5516. // Viewport
  5517. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5518. this.resize();
  5519. // Caps
  5520. this._caps = new EngineCapabilities();
  5521. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5522. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5523. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5524. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5525. // Infos
  5526. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5527. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5528. if (rendererInfo != null) {
  5529. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5530. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5531. }
  5532. if (!this._glVendor) {
  5533. this._glVendor = "Unknown vendor";
  5534. }
  5535. if (!this._glRenderer) {
  5536. this._glRenderer = "Unknown renderer";
  5537. }
  5538. // Extensions
  5539. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5540. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5541. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5542. 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');
  5543. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5544. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5545. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5546. this._caps.highPrecisionShaderSupported = true;
  5547. if (this._gl.getShaderPrecisionFormat) {
  5548. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5549. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5550. }
  5551. // Depth buffer
  5552. this.setDepthBuffer(true);
  5553. this.setDepthFunctionToLessOrEqual();
  5554. this.setDepthWrite(true);
  5555. // Fullscreen
  5556. this._onFullscreenChange = function () {
  5557. if (document.fullscreen !== undefined) {
  5558. _this.isFullscreen = document.fullscreen;
  5559. }
  5560. else if (document.mozFullScreen !== undefined) {
  5561. _this.isFullscreen = document.mozFullScreen;
  5562. }
  5563. else if (document.webkitIsFullScreen !== undefined) {
  5564. _this.isFullscreen = document.webkitIsFullScreen;
  5565. }
  5566. else if (document.msIsFullScreen !== undefined) {
  5567. _this.isFullscreen = document.msIsFullScreen;
  5568. }
  5569. // Pointer lock
  5570. if (_this.isFullscreen && _this._pointerLockRequested) {
  5571. canvas.requestPointerLock = canvas.requestPointerLock ||
  5572. canvas.msRequestPointerLock ||
  5573. canvas.mozRequestPointerLock ||
  5574. canvas.webkitRequestPointerLock;
  5575. if (canvas.requestPointerLock) {
  5576. canvas.requestPointerLock();
  5577. }
  5578. }
  5579. };
  5580. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5581. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5582. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5583. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5584. // Pointer lock
  5585. this._onPointerLockChange = function () {
  5586. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5587. document.webkitPointerLockElement === canvas ||
  5588. document.msPointerLockElement === canvas ||
  5589. document.pointerLockElement === canvas);
  5590. };
  5591. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5592. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5593. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5594. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5595. if (!Engine.audioEngine) {
  5596. Engine.audioEngine = new BABYLON.AudioEngine();
  5597. }
  5598. //default loading screen
  5599. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5600. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5601. }
  5602. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5603. get: function () {
  5604. return Engine._ALPHA_DISABLE;
  5605. },
  5606. enumerable: true,
  5607. configurable: true
  5608. });
  5609. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5610. get: function () {
  5611. return Engine._ALPHA_ONEONE;
  5612. },
  5613. enumerable: true,
  5614. configurable: true
  5615. });
  5616. Object.defineProperty(Engine, "ALPHA_ADD", {
  5617. get: function () {
  5618. return Engine._ALPHA_ADD;
  5619. },
  5620. enumerable: true,
  5621. configurable: true
  5622. });
  5623. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5624. get: function () {
  5625. return Engine._ALPHA_COMBINE;
  5626. },
  5627. enumerable: true,
  5628. configurable: true
  5629. });
  5630. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5631. get: function () {
  5632. return Engine._ALPHA_SUBTRACT;
  5633. },
  5634. enumerable: true,
  5635. configurable: true
  5636. });
  5637. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5638. get: function () {
  5639. return Engine._ALPHA_MULTIPLY;
  5640. },
  5641. enumerable: true,
  5642. configurable: true
  5643. });
  5644. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5645. get: function () {
  5646. return Engine._ALPHA_MAXIMIZED;
  5647. },
  5648. enumerable: true,
  5649. configurable: true
  5650. });
  5651. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5652. get: function () {
  5653. return Engine._DELAYLOADSTATE_NONE;
  5654. },
  5655. enumerable: true,
  5656. configurable: true
  5657. });
  5658. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5659. get: function () {
  5660. return Engine._DELAYLOADSTATE_LOADED;
  5661. },
  5662. enumerable: true,
  5663. configurable: true
  5664. });
  5665. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5666. get: function () {
  5667. return Engine._DELAYLOADSTATE_LOADING;
  5668. },
  5669. enumerable: true,
  5670. configurable: true
  5671. });
  5672. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5673. get: function () {
  5674. return Engine._DELAYLOADSTATE_NOTLOADED;
  5675. },
  5676. enumerable: true,
  5677. configurable: true
  5678. });
  5679. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5680. get: function () {
  5681. return Engine._TEXTUREFORMAT_ALPHA;
  5682. },
  5683. enumerable: true,
  5684. configurable: true
  5685. });
  5686. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5687. get: function () {
  5688. return Engine._TEXTUREFORMAT_LUMINANCE;
  5689. },
  5690. enumerable: true,
  5691. configurable: true
  5692. });
  5693. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5694. get: function () {
  5695. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5696. },
  5697. enumerable: true,
  5698. configurable: true
  5699. });
  5700. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5701. get: function () {
  5702. return Engine._TEXTUREFORMAT_RGB;
  5703. },
  5704. enumerable: true,
  5705. configurable: true
  5706. });
  5707. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5708. get: function () {
  5709. return Engine._TEXTUREFORMAT_RGBA;
  5710. },
  5711. enumerable: true,
  5712. configurable: true
  5713. });
  5714. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5715. get: function () {
  5716. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5717. },
  5718. enumerable: true,
  5719. configurable: true
  5720. });
  5721. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5722. get: function () {
  5723. return Engine._TEXTURETYPE_FLOAT;
  5724. },
  5725. enumerable: true,
  5726. configurable: true
  5727. });
  5728. Object.defineProperty(Engine, "Version", {
  5729. get: function () {
  5730. return "2.3.0-alpha";
  5731. },
  5732. enumerable: true,
  5733. configurable: true
  5734. });
  5735. Engine.prototype._prepareWorkingCanvas = function () {
  5736. if (this._workingCanvas) {
  5737. return;
  5738. }
  5739. this._workingCanvas = document.createElement("canvas");
  5740. this._workingContext = this._workingCanvas.getContext("2d");
  5741. };
  5742. Engine.prototype.getGlInfo = function () {
  5743. return {
  5744. vendor: this._glVendor,
  5745. renderer: this._glRenderer,
  5746. version: this._glVersion
  5747. };
  5748. };
  5749. Engine.prototype.getAspectRatio = function (camera) {
  5750. var viewport = camera.viewport;
  5751. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5752. };
  5753. Engine.prototype.getRenderWidth = function () {
  5754. if (this._currentRenderTarget) {
  5755. return this._currentRenderTarget._width;
  5756. }
  5757. return this._renderingCanvas.width;
  5758. };
  5759. Engine.prototype.getRenderHeight = function () {
  5760. if (this._currentRenderTarget) {
  5761. return this._currentRenderTarget._height;
  5762. }
  5763. return this._renderingCanvas.height;
  5764. };
  5765. Engine.prototype.getRenderingCanvas = function () {
  5766. return this._renderingCanvas;
  5767. };
  5768. Engine.prototype.getRenderingCanvasClientRect = function () {
  5769. return this._renderingCanvas.getBoundingClientRect();
  5770. };
  5771. Engine.prototype.setHardwareScalingLevel = function (level) {
  5772. this._hardwareScalingLevel = level;
  5773. this.resize();
  5774. };
  5775. Engine.prototype.getHardwareScalingLevel = function () {
  5776. return this._hardwareScalingLevel;
  5777. };
  5778. Engine.prototype.getLoadedTexturesCache = function () {
  5779. return this._loadedTexturesCache;
  5780. };
  5781. Engine.prototype.getCaps = function () {
  5782. return this._caps;
  5783. };
  5784. Object.defineProperty(Engine.prototype, "drawCalls", {
  5785. get: function () {
  5786. return this._drawCalls;
  5787. },
  5788. enumerable: true,
  5789. configurable: true
  5790. });
  5791. // Methods
  5792. Engine.prototype.resetDrawCalls = function () {
  5793. this._drawCalls = 0;
  5794. };
  5795. Engine.prototype.setDepthFunctionToGreater = function () {
  5796. this._depthCullingState.depthFunc = this._gl.GREATER;
  5797. };
  5798. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5799. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5800. };
  5801. Engine.prototype.setDepthFunctionToLess = function () {
  5802. this._depthCullingState.depthFunc = this._gl.LESS;
  5803. };
  5804. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5805. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5806. };
  5807. /**
  5808. * stop executing a render loop function and remove it from the execution array
  5809. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5810. */
  5811. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5812. if (!renderFunction) {
  5813. this._activeRenderLoops = [];
  5814. return;
  5815. }
  5816. var index = this._activeRenderLoops.indexOf(renderFunction);
  5817. if (index >= 0) {
  5818. this._activeRenderLoops.splice(index, 1);
  5819. }
  5820. };
  5821. Engine.prototype._renderLoop = function () {
  5822. var _this = this;
  5823. var shouldRender = true;
  5824. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5825. shouldRender = false;
  5826. }
  5827. if (shouldRender) {
  5828. // Start new frame
  5829. this.beginFrame();
  5830. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5831. var renderFunction = this._activeRenderLoops[index];
  5832. renderFunction();
  5833. }
  5834. // Present
  5835. this.endFrame();
  5836. }
  5837. if (this._activeRenderLoops.length > 0) {
  5838. // Register new frame
  5839. BABYLON.Tools.QueueNewFrame(function () {
  5840. _this._renderLoop();
  5841. });
  5842. }
  5843. else {
  5844. this._renderingQueueLaunched = false;
  5845. }
  5846. };
  5847. /**
  5848. * Register and execute a render loop. The engine can have more than one render function.
  5849. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5850. * @example
  5851. * engine.runRenderLoop(function () {
  5852. * scene.render()
  5853. * })
  5854. */
  5855. Engine.prototype.runRenderLoop = function (renderFunction) {
  5856. var _this = this;
  5857. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5858. return;
  5859. }
  5860. this._activeRenderLoops.push(renderFunction);
  5861. if (!this._renderingQueueLaunched) {
  5862. this._renderingQueueLaunched = true;
  5863. BABYLON.Tools.QueueNewFrame(function () {
  5864. _this._renderLoop();
  5865. });
  5866. }
  5867. };
  5868. /**
  5869. * Toggle full screen mode.
  5870. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5871. */
  5872. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5873. if (this.isFullscreen) {
  5874. BABYLON.Tools.ExitFullscreen();
  5875. }
  5876. else {
  5877. this._pointerLockRequested = requestPointerLock;
  5878. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5879. }
  5880. };
  5881. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5882. this.applyStates();
  5883. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5884. if (this._depthCullingState.depthMask) {
  5885. this._gl.clearDepth(1.0);
  5886. }
  5887. var mode = 0;
  5888. if (backBuffer)
  5889. mode |= this._gl.COLOR_BUFFER_BIT;
  5890. if (depthStencil && this._depthCullingState.depthMask)
  5891. mode |= this._gl.DEPTH_BUFFER_BIT;
  5892. this._gl.clear(mode);
  5893. };
  5894. /**
  5895. * Set the WebGL's viewport
  5896. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5897. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5898. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5899. */
  5900. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5901. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5902. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5903. var x = viewport.x || 0;
  5904. var y = viewport.y || 0;
  5905. this._cachedViewport = viewport;
  5906. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5907. };
  5908. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5909. this._cachedViewport = null;
  5910. this._gl.viewport(x, y, width, height);
  5911. };
  5912. Engine.prototype.beginFrame = function () {
  5913. this._measureFps();
  5914. };
  5915. Engine.prototype.endFrame = function () {
  5916. //this.flushFramebuffer();
  5917. };
  5918. /**
  5919. * resize the view according to the canvas' size.
  5920. * @example
  5921. * window.addEventListener("resize", function () {
  5922. * engine.resize();
  5923. * });
  5924. */
  5925. Engine.prototype.resize = function () {
  5926. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5927. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5928. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5929. };
  5930. /**
  5931. * force a specific size of the canvas
  5932. * @param {number} width - the new canvas' width
  5933. * @param {number} height - the new canvas' height
  5934. */
  5935. Engine.prototype.setSize = function (width, height) {
  5936. this._renderingCanvas.width = width;
  5937. this._renderingCanvas.height = height;
  5938. for (var index = 0; index < this.scenes.length; index++) {
  5939. var scene = this.scenes[index];
  5940. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5941. var cam = scene.cameras[camIndex];
  5942. cam._currentRenderId = 0;
  5943. }
  5944. }
  5945. };
  5946. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5947. this._currentRenderTarget = texture;
  5948. var gl = this._gl;
  5949. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5950. if (texture.isCube) {
  5951. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5952. }
  5953. else {
  5954. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5955. }
  5956. this._gl.viewport(0, 0, texture._width, texture._height);
  5957. this.wipeCaches();
  5958. };
  5959. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5960. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5961. this._currentRenderTarget = null;
  5962. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5963. var gl = this._gl;
  5964. gl.bindTexture(gl.TEXTURE_2D, texture);
  5965. gl.generateMipmap(gl.TEXTURE_2D);
  5966. gl.bindTexture(gl.TEXTURE_2D, null);
  5967. }
  5968. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5969. };
  5970. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5971. if (texture.generateMipMaps) {
  5972. var gl = this._gl;
  5973. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5974. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5975. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5976. }
  5977. };
  5978. Engine.prototype.flushFramebuffer = function () {
  5979. this._gl.flush();
  5980. };
  5981. Engine.prototype.restoreDefaultFramebuffer = function () {
  5982. this._currentRenderTarget = null;
  5983. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5984. this.setViewport(this._cachedViewport);
  5985. this.wipeCaches();
  5986. };
  5987. // VBOs
  5988. Engine.prototype._resetVertexBufferBinding = function () {
  5989. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5990. this._cachedVertexBuffers = null;
  5991. };
  5992. Engine.prototype.createVertexBuffer = function (vertices) {
  5993. var vbo = this._gl.createBuffer();
  5994. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5995. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5996. this._resetVertexBufferBinding();
  5997. vbo.references = 1;
  5998. return vbo;
  5999. };
  6000. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6001. var vbo = this._gl.createBuffer();
  6002. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6003. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6004. this._resetVertexBufferBinding();
  6005. vbo.references = 1;
  6006. return vbo;
  6007. };
  6008. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6009. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6010. if (offset === undefined) {
  6011. offset = 0;
  6012. }
  6013. if (vertices instanceof Float32Array) {
  6014. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6015. }
  6016. else {
  6017. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6018. }
  6019. this._resetVertexBufferBinding();
  6020. };
  6021. Engine.prototype._resetIndexBufferBinding = function () {
  6022. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6023. this._cachedIndexBuffer = null;
  6024. };
  6025. Engine.prototype.createIndexBuffer = function (indices) {
  6026. var vbo = this._gl.createBuffer();
  6027. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6028. // Check for 32 bits indices
  6029. var arrayBuffer;
  6030. var need32Bits = false;
  6031. if (this._caps.uintIndices) {
  6032. for (var index = 0; index < indices.length; index++) {
  6033. if (indices[index] > 65535) {
  6034. need32Bits = true;
  6035. break;
  6036. }
  6037. }
  6038. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6039. }
  6040. else {
  6041. arrayBuffer = new Uint16Array(indices);
  6042. }
  6043. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6044. this._resetIndexBufferBinding();
  6045. vbo.references = 1;
  6046. vbo.is32Bits = need32Bits;
  6047. return vbo;
  6048. };
  6049. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6050. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6051. this._cachedVertexBuffers = vertexBuffer;
  6052. this._cachedEffectForVertexBuffers = effect;
  6053. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6054. var offset = 0;
  6055. for (var index = 0; index < vertexDeclaration.length; index++) {
  6056. var order = effect.getAttributeLocation(index);
  6057. if (order >= 0) {
  6058. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6059. }
  6060. offset += vertexDeclaration[index] * 4;
  6061. }
  6062. }
  6063. if (this._cachedIndexBuffer !== indexBuffer) {
  6064. this._cachedIndexBuffer = indexBuffer;
  6065. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6066. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6067. }
  6068. };
  6069. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6070. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6071. this._cachedVertexBuffers = vertexBuffers;
  6072. this._cachedEffectForVertexBuffers = effect;
  6073. var attributes = effect.getAttributesNames();
  6074. for (var index = 0; index < attributes.length; index++) {
  6075. var order = effect.getAttributeLocation(index);
  6076. if (order >= 0) {
  6077. var vertexBuffer = vertexBuffers[attributes[index]];
  6078. if (!vertexBuffer) {
  6079. continue;
  6080. }
  6081. var stride = vertexBuffer.getStrideSize();
  6082. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6083. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6084. }
  6085. }
  6086. }
  6087. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6088. this._cachedIndexBuffer = indexBuffer;
  6089. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6090. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6091. }
  6092. };
  6093. Engine.prototype._releaseBuffer = function (buffer) {
  6094. buffer.references--;
  6095. if (buffer.references === 0) {
  6096. this._gl.deleteBuffer(buffer);
  6097. return true;
  6098. }
  6099. return false;
  6100. };
  6101. Engine.prototype.createInstancesBuffer = function (capacity) {
  6102. var buffer = this._gl.createBuffer();
  6103. buffer.capacity = capacity;
  6104. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6105. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6106. return buffer;
  6107. };
  6108. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6109. this._gl.deleteBuffer(buffer);
  6110. };
  6111. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6112. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6113. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6114. for (var index = 0; index < 4; index++) {
  6115. var offsetLocation = offsetLocations[index];
  6116. this._gl.enableVertexAttribArray(offsetLocation);
  6117. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6118. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6119. }
  6120. };
  6121. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6122. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6123. for (var index = 0; index < 4; index++) {
  6124. var offsetLocation = offsetLocations[index];
  6125. this._gl.disableVertexAttribArray(offsetLocation);
  6126. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6127. }
  6128. };
  6129. Engine.prototype.applyStates = function () {
  6130. this._depthCullingState.apply(this._gl);
  6131. this._alphaState.apply(this._gl);
  6132. };
  6133. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6134. // Apply states
  6135. this.applyStates();
  6136. this._drawCalls++;
  6137. // Render
  6138. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6139. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6140. if (instancesCount) {
  6141. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6142. return;
  6143. }
  6144. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6145. };
  6146. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6147. // Apply states
  6148. this.applyStates();
  6149. this._drawCalls++;
  6150. if (instancesCount) {
  6151. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6152. return;
  6153. }
  6154. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6155. };
  6156. // Shaders
  6157. Engine.prototype._releaseEffect = function (effect) {
  6158. if (this._compiledEffects[effect._key]) {
  6159. delete this._compiledEffects[effect._key];
  6160. if (effect.getProgram()) {
  6161. this._gl.deleteProgram(effect.getProgram());
  6162. }
  6163. }
  6164. };
  6165. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6166. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6167. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6168. var name = vertex + "+" + fragment + "@" + defines;
  6169. if (this._compiledEffects[name]) {
  6170. return this._compiledEffects[name];
  6171. }
  6172. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6173. effect._key = name;
  6174. this._compiledEffects[name] = effect;
  6175. return effect;
  6176. };
  6177. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6178. if (uniformsNames === void 0) { uniformsNames = []; }
  6179. if (samplers === void 0) { samplers = []; }
  6180. if (defines === void 0) { defines = ""; }
  6181. return this.createEffect({
  6182. vertex: "particles",
  6183. fragmentElement: fragmentName
  6184. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6185. };
  6186. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6187. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6188. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6189. var shaderProgram = this._gl.createProgram();
  6190. this._gl.attachShader(shaderProgram, vertexShader);
  6191. this._gl.attachShader(shaderProgram, fragmentShader);
  6192. this._gl.linkProgram(shaderProgram);
  6193. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6194. if (!linked) {
  6195. var error = this._gl.getProgramInfoLog(shaderProgram);
  6196. if (error) {
  6197. throw new Error(error);
  6198. }
  6199. }
  6200. this._gl.deleteShader(vertexShader);
  6201. this._gl.deleteShader(fragmentShader);
  6202. return shaderProgram;
  6203. };
  6204. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6205. var results = [];
  6206. for (var index = 0; index < uniformsNames.length; index++) {
  6207. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6208. }
  6209. return results;
  6210. };
  6211. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6212. var results = [];
  6213. for (var index = 0; index < attributesNames.length; index++) {
  6214. try {
  6215. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6216. }
  6217. catch (e) {
  6218. results.push(-1);
  6219. }
  6220. }
  6221. return results;
  6222. };
  6223. Engine.prototype.enableEffect = function (effect) {
  6224. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6225. if (effect && effect.onBind) {
  6226. effect.onBind(effect);
  6227. }
  6228. return;
  6229. }
  6230. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6231. // Use program
  6232. this._gl.useProgram(effect.getProgram());
  6233. for (var i in this._vertexAttribArrays) {
  6234. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6235. continue;
  6236. }
  6237. this._vertexAttribArrays[i] = false;
  6238. this._gl.disableVertexAttribArray(i);
  6239. }
  6240. var attributesCount = effect.getAttributesCount();
  6241. for (var index = 0; index < attributesCount; index++) {
  6242. // Attributes
  6243. var order = effect.getAttributeLocation(index);
  6244. if (order >= 0) {
  6245. this._vertexAttribArrays[order] = true;
  6246. this._gl.enableVertexAttribArray(order);
  6247. }
  6248. }
  6249. this._currentEffect = effect;
  6250. if (effect.onBind) {
  6251. effect.onBind(effect);
  6252. }
  6253. };
  6254. Engine.prototype.setArray = function (uniform, array) {
  6255. if (!uniform)
  6256. return;
  6257. this._gl.uniform1fv(uniform, array);
  6258. };
  6259. Engine.prototype.setArray2 = function (uniform, array) {
  6260. if (!uniform || array.length % 2 !== 0)
  6261. return;
  6262. this._gl.uniform2fv(uniform, array);
  6263. };
  6264. Engine.prototype.setArray3 = function (uniform, array) {
  6265. if (!uniform || array.length % 3 !== 0)
  6266. return;
  6267. this._gl.uniform3fv(uniform, array);
  6268. };
  6269. Engine.prototype.setArray4 = function (uniform, array) {
  6270. if (!uniform || array.length % 4 !== 0)
  6271. return;
  6272. this._gl.uniform4fv(uniform, array);
  6273. };
  6274. Engine.prototype.setMatrices = function (uniform, matrices) {
  6275. if (!uniform)
  6276. return;
  6277. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6278. };
  6279. Engine.prototype.setMatrix = function (uniform, matrix) {
  6280. if (!uniform)
  6281. return;
  6282. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6283. };
  6284. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6285. if (!uniform)
  6286. return;
  6287. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6288. };
  6289. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6290. if (!uniform)
  6291. return;
  6292. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6293. };
  6294. Engine.prototype.setFloat = function (uniform, value) {
  6295. if (!uniform)
  6296. return;
  6297. this._gl.uniform1f(uniform, value);
  6298. };
  6299. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6300. if (!uniform)
  6301. return;
  6302. this._gl.uniform2f(uniform, x, y);
  6303. };
  6304. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6305. if (!uniform)
  6306. return;
  6307. this._gl.uniform3f(uniform, x, y, z);
  6308. };
  6309. Engine.prototype.setBool = function (uniform, bool) {
  6310. if (!uniform)
  6311. return;
  6312. this._gl.uniform1i(uniform, bool);
  6313. };
  6314. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6315. if (!uniform)
  6316. return;
  6317. this._gl.uniform4f(uniform, x, y, z, w);
  6318. };
  6319. Engine.prototype.setColor3 = function (uniform, color3) {
  6320. if (!uniform)
  6321. return;
  6322. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6323. };
  6324. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6325. if (!uniform)
  6326. return;
  6327. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6328. };
  6329. // States
  6330. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6331. if (zOffset === void 0) { zOffset = 0; }
  6332. if (reverseSide === void 0) { reverseSide = false; }
  6333. // Culling
  6334. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6335. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6336. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6337. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6338. if (culling) {
  6339. this._depthCullingState.cullFace = cullFace;
  6340. this._depthCullingState.cull = true;
  6341. }
  6342. else {
  6343. this._depthCullingState.cull = false;
  6344. }
  6345. }
  6346. // Z offset
  6347. this._depthCullingState.zOffset = zOffset;
  6348. };
  6349. Engine.prototype.setDepthBuffer = function (enable) {
  6350. this._depthCullingState.depthTest = enable;
  6351. };
  6352. Engine.prototype.getDepthWrite = function () {
  6353. return this._depthCullingState.depthMask;
  6354. };
  6355. Engine.prototype.setDepthWrite = function (enable) {
  6356. this._depthCullingState.depthMask = enable;
  6357. };
  6358. Engine.prototype.setColorWrite = function (enable) {
  6359. this._gl.colorMask(enable, enable, enable, enable);
  6360. };
  6361. Engine.prototype.setAlphaMode = function (mode) {
  6362. if (this._alphaMode === mode) {
  6363. return;
  6364. }
  6365. switch (mode) {
  6366. case Engine.ALPHA_DISABLE:
  6367. this.setDepthWrite(true);
  6368. this._alphaState.alphaBlend = false;
  6369. break;
  6370. case Engine.ALPHA_COMBINE:
  6371. this.setDepthWrite(false);
  6372. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6373. this._alphaState.alphaBlend = true;
  6374. break;
  6375. case Engine.ALPHA_ONEONE:
  6376. this.setDepthWrite(false);
  6377. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6378. this._alphaState.alphaBlend = true;
  6379. break;
  6380. case Engine.ALPHA_ADD:
  6381. this.setDepthWrite(false);
  6382. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6383. this._alphaState.alphaBlend = true;
  6384. break;
  6385. case Engine.ALPHA_SUBTRACT:
  6386. this.setDepthWrite(false);
  6387. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6388. this._alphaState.alphaBlend = true;
  6389. break;
  6390. case Engine.ALPHA_MULTIPLY:
  6391. this.setDepthWrite(false);
  6392. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6393. this._alphaState.alphaBlend = true;
  6394. break;
  6395. case Engine.ALPHA_MAXIMIZED:
  6396. this.setDepthWrite(false);
  6397. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6398. this._alphaState.alphaBlend = true;
  6399. break;
  6400. }
  6401. this._alphaMode = mode;
  6402. };
  6403. Engine.prototype.getAlphaMode = function () {
  6404. return this._alphaMode;
  6405. };
  6406. Engine.prototype.setAlphaTesting = function (enable) {
  6407. this._alphaTest = enable;
  6408. };
  6409. Engine.prototype.getAlphaTesting = function () {
  6410. return this._alphaTest;
  6411. };
  6412. // Textures
  6413. Engine.prototype.wipeCaches = function () {
  6414. this._activeTexturesCache = [];
  6415. this._currentEffect = null;
  6416. this._depthCullingState.reset();
  6417. this._alphaState.reset();
  6418. this._cachedVertexBuffers = null;
  6419. this._cachedIndexBuffer = null;
  6420. this._cachedEffectForVertexBuffers = null;
  6421. };
  6422. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6423. var gl = this._gl;
  6424. gl.bindTexture(gl.TEXTURE_2D, texture);
  6425. var magFilter = gl.NEAREST;
  6426. var minFilter = gl.NEAREST;
  6427. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6428. magFilter = gl.LINEAR;
  6429. minFilter = gl.LINEAR;
  6430. }
  6431. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6432. magFilter = gl.LINEAR;
  6433. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6434. }
  6435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6437. gl.bindTexture(gl.TEXTURE_2D, null);
  6438. texture.samplingMode = samplingMode;
  6439. };
  6440. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6441. var _this = this;
  6442. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6443. if (onLoad === void 0) { onLoad = null; }
  6444. if (onError === void 0) { onError = null; }
  6445. if (buffer === void 0) { buffer = null; }
  6446. var texture = this._gl.createTexture();
  6447. var extension;
  6448. var fromData = false;
  6449. if (url.substr(0, 5) === "data:") {
  6450. fromData = true;
  6451. }
  6452. if (!fromData)
  6453. extension = url.substr(url.length - 4, 4).toLowerCase();
  6454. else {
  6455. var oldUrl = url;
  6456. fromData = oldUrl.split(':');
  6457. url = oldUrl;
  6458. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6459. }
  6460. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6461. var isTGA = (extension === ".tga");
  6462. scene._addPendingData(texture);
  6463. texture.url = url;
  6464. texture.noMipmap = noMipmap;
  6465. texture.references = 1;
  6466. texture.samplingMode = samplingMode;
  6467. this._loadedTexturesCache.push(texture);
  6468. var onerror = function () {
  6469. scene._removePendingData(texture);
  6470. if (onError) {
  6471. onError();
  6472. }
  6473. };
  6474. var callback;
  6475. if (isTGA) {
  6476. callback = function (arrayBuffer) {
  6477. var data = new Uint8Array(arrayBuffer);
  6478. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6479. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6480. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6481. if (onLoad) {
  6482. onLoad();
  6483. }
  6484. }, samplingMode);
  6485. };
  6486. if (!(fromData instanceof Array))
  6487. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6488. callback(arrayBuffer);
  6489. }, onerror, scene.database, true);
  6490. else
  6491. callback(buffer);
  6492. }
  6493. else if (isDDS) {
  6494. callback = function (data) {
  6495. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6496. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6497. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6498. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6499. if (onLoad) {
  6500. onLoad();
  6501. }
  6502. }, samplingMode);
  6503. };
  6504. if (!(fromData instanceof Array))
  6505. BABYLON.Tools.LoadFile(url, function (data) {
  6506. callback(data);
  6507. }, onerror, scene.database, true);
  6508. else
  6509. callback(buffer);
  6510. }
  6511. else {
  6512. var onload = function (img) {
  6513. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6514. var isPot = (img.width === potWidth && img.height === potHeight);
  6515. if (!isPot) {
  6516. _this._prepareWorkingCanvas();
  6517. _this._workingCanvas.width = potWidth;
  6518. _this._workingCanvas.height = potHeight;
  6519. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6520. _this._workingContext.imageSmoothingEnabled = false;
  6521. _this._workingContext.mozImageSmoothingEnabled = false;
  6522. _this._workingContext.oImageSmoothingEnabled = false;
  6523. _this._workingContext.webkitImageSmoothingEnabled = false;
  6524. _this._workingContext.msImageSmoothingEnabled = false;
  6525. }
  6526. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6527. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6528. _this._workingContext.imageSmoothingEnabled = true;
  6529. _this._workingContext.mozImageSmoothingEnabled = true;
  6530. _this._workingContext.oImageSmoothingEnabled = true;
  6531. _this._workingContext.webkitImageSmoothingEnabled = true;
  6532. _this._workingContext.msImageSmoothingEnabled = true;
  6533. }
  6534. }
  6535. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6536. if (onLoad) {
  6537. onLoad();
  6538. }
  6539. }, samplingMode);
  6540. };
  6541. if (!(fromData instanceof Array))
  6542. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6543. else
  6544. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6545. }
  6546. return texture;
  6547. };
  6548. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6549. if (compression === void 0) { compression = null; }
  6550. var internalFormat = this._gl.RGBA;
  6551. switch (format) {
  6552. case Engine.TEXTUREFORMAT_ALPHA:
  6553. internalFormat = this._gl.ALPHA;
  6554. break;
  6555. case Engine.TEXTUREFORMAT_LUMINANCE:
  6556. internalFormat = this._gl.LUMINANCE;
  6557. break;
  6558. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6559. internalFormat = this._gl.LUMINANCE_ALPHA;
  6560. break;
  6561. case Engine.TEXTUREFORMAT_RGB:
  6562. internalFormat = this._gl.RGB;
  6563. break;
  6564. case Engine.TEXTUREFORMAT_RGBA:
  6565. internalFormat = this._gl.RGBA;
  6566. break;
  6567. }
  6568. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6569. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6570. if (compression) {
  6571. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6572. }
  6573. else {
  6574. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6575. }
  6576. if (texture.generateMipMaps) {
  6577. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6578. }
  6579. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6580. this._activeTexturesCache = [];
  6581. texture.isReady = true;
  6582. };
  6583. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6584. if (compression === void 0) { compression = null; }
  6585. var texture = this._gl.createTexture();
  6586. texture._baseWidth = width;
  6587. texture._baseHeight = height;
  6588. texture._width = width;
  6589. texture._height = height;
  6590. texture.references = 1;
  6591. this.updateRawTexture(texture, data, format, invertY, compression);
  6592. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6593. // Filters
  6594. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6595. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6596. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6597. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6598. texture.samplingMode = samplingMode;
  6599. this._loadedTexturesCache.push(texture);
  6600. return texture;
  6601. };
  6602. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6603. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6604. var texture = this._gl.createTexture();
  6605. texture._baseWidth = width;
  6606. texture._baseHeight = height;
  6607. if (forceExponantOfTwo) {
  6608. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6609. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6610. }
  6611. this._activeTexturesCache = [];
  6612. texture._width = width;
  6613. texture._height = height;
  6614. texture.isReady = false;
  6615. texture.generateMipMaps = generateMipMaps;
  6616. texture.references = 1;
  6617. texture.samplingMode = samplingMode;
  6618. this.updateTextureSamplingMode(samplingMode, texture);
  6619. this._loadedTexturesCache.push(texture);
  6620. return texture;
  6621. };
  6622. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6623. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6624. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6626. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6627. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6628. };
  6629. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6630. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6631. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6632. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6633. if (texture.generateMipMaps) {
  6634. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6635. }
  6636. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6637. this._activeTexturesCache = [];
  6638. texture.isReady = true;
  6639. };
  6640. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6641. if (texture._isDisabled) {
  6642. return;
  6643. }
  6644. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6645. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6646. try {
  6647. // Testing video texture support
  6648. if (this._videoTextureSupported === undefined) {
  6649. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6650. if (this._gl.getError() !== 0) {
  6651. this._videoTextureSupported = false;
  6652. }
  6653. else {
  6654. this._videoTextureSupported = true;
  6655. }
  6656. }
  6657. // Copy video through the current working canvas if video texture is not supported
  6658. if (!this._videoTextureSupported) {
  6659. if (!texture._workingCanvas) {
  6660. texture._workingCanvas = document.createElement("canvas");
  6661. texture._workingContext = texture._workingCanvas.getContext("2d");
  6662. texture._workingCanvas.width = texture._width;
  6663. texture._workingCanvas.height = texture._height;
  6664. }
  6665. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6666. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6667. }
  6668. else {
  6669. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6670. }
  6671. if (texture.generateMipMaps) {
  6672. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6673. }
  6674. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6675. this._activeTexturesCache = [];
  6676. texture.isReady = true;
  6677. }
  6678. catch (ex) {
  6679. // Something unexpected
  6680. // Let's disable the texture
  6681. texture._isDisabled = true;
  6682. }
  6683. };
  6684. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6685. // old version had a "generateMipMaps" arg instead of options.
  6686. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6687. // in the same way, generateDepthBuffer is defaulted to true
  6688. var generateMipMaps = false;
  6689. var generateDepthBuffer = true;
  6690. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6691. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6692. if (options !== undefined) {
  6693. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6694. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6695. type = options.type === undefined ? type : options.type;
  6696. if (options.samplingMode !== undefined) {
  6697. samplingMode = options.samplingMode;
  6698. }
  6699. if (type === Engine.TEXTURETYPE_FLOAT) {
  6700. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6701. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6702. }
  6703. }
  6704. var gl = this._gl;
  6705. var texture = gl.createTexture();
  6706. gl.bindTexture(gl.TEXTURE_2D, texture);
  6707. var width = size.width || size;
  6708. var height = size.height || size;
  6709. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6710. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6711. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6712. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6713. }
  6714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6715. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6716. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6717. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6718. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6719. var depthBuffer;
  6720. // Create the depth buffer
  6721. if (generateDepthBuffer) {
  6722. depthBuffer = gl.createRenderbuffer();
  6723. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6724. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6725. }
  6726. // Create the framebuffer
  6727. var framebuffer = gl.createFramebuffer();
  6728. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6729. if (generateDepthBuffer) {
  6730. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6731. }
  6732. if (generateMipMaps) {
  6733. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6734. }
  6735. // Unbind
  6736. gl.bindTexture(gl.TEXTURE_2D, null);
  6737. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6738. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6739. texture._framebuffer = framebuffer;
  6740. if (generateDepthBuffer) {
  6741. texture._depthBuffer = depthBuffer;
  6742. }
  6743. texture._width = width;
  6744. texture._height = height;
  6745. texture.isReady = true;
  6746. texture.generateMipMaps = generateMipMaps;
  6747. texture.references = 1;
  6748. texture.samplingMode = samplingMode;
  6749. this._activeTexturesCache = [];
  6750. this._loadedTexturesCache.push(texture);
  6751. return texture;
  6752. };
  6753. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6754. var gl = this._gl;
  6755. var texture = gl.createTexture();
  6756. var generateMipMaps = true;
  6757. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6758. if (options !== undefined) {
  6759. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6760. if (options.samplingMode !== undefined) {
  6761. samplingMode = options.samplingMode;
  6762. }
  6763. }
  6764. texture.isCube = true;
  6765. texture.references = 1;
  6766. texture.generateMipMaps = generateMipMaps;
  6767. texture.references = 1;
  6768. texture.samplingMode = samplingMode;
  6769. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6770. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6771. for (var face = 0; face < 6; face++) {
  6772. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6773. }
  6774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6778. // Create the depth buffer
  6779. var depthBuffer = gl.createRenderbuffer();
  6780. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6781. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6782. // Create the framebuffer
  6783. var framebuffer = gl.createFramebuffer();
  6784. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6785. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6786. // Unbind
  6787. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6788. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6789. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6790. texture._framebuffer = framebuffer;
  6791. texture._depthBuffer = depthBuffer;
  6792. this._activeTexturesCache = [];
  6793. texture._width = size;
  6794. texture._height = size;
  6795. texture.isReady = true;
  6796. return texture;
  6797. };
  6798. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6799. var _this = this;
  6800. var gl = this._gl;
  6801. var texture = gl.createTexture();
  6802. texture.isCube = true;
  6803. texture.url = rootUrl;
  6804. texture.references = 1;
  6805. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6806. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6807. if (isDDS) {
  6808. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6809. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6810. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6811. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6812. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6813. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6814. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6815. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6816. }
  6817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6821. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6822. _this._activeTexturesCache = [];
  6823. texture._width = info.width;
  6824. texture._height = info.height;
  6825. texture.isReady = true;
  6826. }, null, null, true);
  6827. }
  6828. else {
  6829. cascadeLoad(rootUrl, scene, function (imgs) {
  6830. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6831. var height = width;
  6832. _this._prepareWorkingCanvas();
  6833. _this._workingCanvas.width = width;
  6834. _this._workingCanvas.height = height;
  6835. var faces = [
  6836. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6837. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6838. ];
  6839. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6840. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6841. for (var index = 0; index < faces.length; index++) {
  6842. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6843. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6844. }
  6845. if (!noMipmap) {
  6846. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6847. }
  6848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6852. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6853. _this._activeTexturesCache = [];
  6854. texture._width = width;
  6855. texture._height = height;
  6856. texture.isReady = true;
  6857. }, extensions);
  6858. }
  6859. return texture;
  6860. };
  6861. Engine.prototype._releaseTexture = function (texture) {
  6862. var gl = this._gl;
  6863. if (texture._framebuffer) {
  6864. gl.deleteFramebuffer(texture._framebuffer);
  6865. }
  6866. if (texture._depthBuffer) {
  6867. gl.deleteRenderbuffer(texture._depthBuffer);
  6868. }
  6869. gl.deleteTexture(texture);
  6870. // Unbind channels
  6871. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6872. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6873. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6874. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6875. this._activeTexturesCache[channel] = null;
  6876. }
  6877. var index = this._loadedTexturesCache.indexOf(texture);
  6878. if (index !== -1) {
  6879. this._loadedTexturesCache.splice(index, 1);
  6880. }
  6881. };
  6882. Engine.prototype.bindSamplers = function (effect) {
  6883. this._gl.useProgram(effect.getProgram());
  6884. var samplers = effect.getSamplers();
  6885. for (var index = 0; index < samplers.length; index++) {
  6886. var uniform = effect.getUniform(samplers[index]);
  6887. this._gl.uniform1i(uniform, index);
  6888. }
  6889. this._currentEffect = null;
  6890. };
  6891. Engine.prototype._bindTexture = function (channel, texture) {
  6892. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6893. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6894. this._activeTexturesCache[channel] = null;
  6895. };
  6896. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6897. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6898. };
  6899. Engine.prototype.setTexture = function (channel, texture) {
  6900. if (channel < 0) {
  6901. return;
  6902. }
  6903. // Not ready?
  6904. if (!texture || !texture.isReady()) {
  6905. if (this._activeTexturesCache[channel] != null) {
  6906. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6907. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6908. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6909. this._activeTexturesCache[channel] = null;
  6910. }
  6911. return;
  6912. }
  6913. // Video
  6914. if (texture instanceof BABYLON.VideoTexture) {
  6915. if (texture.update()) {
  6916. this._activeTexturesCache[channel] = null;
  6917. }
  6918. }
  6919. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6920. texture.delayLoad();
  6921. return;
  6922. }
  6923. if (this._activeTexturesCache[channel] === texture) {
  6924. return;
  6925. }
  6926. this._activeTexturesCache[channel] = texture;
  6927. var internalTexture = texture.getInternalTexture();
  6928. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6929. if (internalTexture.isCube) {
  6930. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6931. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6932. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6933. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6934. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6935. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6936. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6937. }
  6938. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6939. }
  6940. else {
  6941. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6942. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6943. internalTexture._cachedWrapU = texture.wrapU;
  6944. switch (texture.wrapU) {
  6945. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6946. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6947. break;
  6948. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6949. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6950. break;
  6951. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6952. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6953. break;
  6954. }
  6955. }
  6956. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6957. internalTexture._cachedWrapV = texture.wrapV;
  6958. switch (texture.wrapV) {
  6959. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6960. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6961. break;
  6962. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6963. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6964. break;
  6965. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6966. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6967. break;
  6968. }
  6969. }
  6970. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6971. }
  6972. };
  6973. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6974. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6975. var value = texture.anisotropicFilteringLevel;
  6976. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6977. value = 1;
  6978. }
  6979. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6980. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6981. texture._cachedAnisotropicFilteringLevel = value;
  6982. }
  6983. };
  6984. Engine.prototype.readPixels = function (x, y, width, height) {
  6985. var data = new Uint8Array(height * width * 4);
  6986. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6987. return data;
  6988. };
  6989. Engine.prototype.releaseInternalTexture = function (texture) {
  6990. if (!texture) {
  6991. return;
  6992. }
  6993. texture.references--;
  6994. // Final reference ?
  6995. if (texture.references === 0) {
  6996. var texturesCache = this.getLoadedTexturesCache();
  6997. var index = texturesCache.indexOf(texture);
  6998. if (index > -1) {
  6999. texturesCache.splice(index, 1);
  7000. }
  7001. this._releaseTexture(texture);
  7002. }
  7003. };
  7004. // Dispose
  7005. Engine.prototype.dispose = function () {
  7006. this.hideLoadingUI();
  7007. this.stopRenderLoop();
  7008. // Release scenes
  7009. while (this.scenes.length) {
  7010. this.scenes[0].dispose();
  7011. }
  7012. // Release audio engine
  7013. Engine.audioEngine.dispose();
  7014. // Release effects
  7015. for (var name in this._compiledEffects) {
  7016. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7017. }
  7018. // Unbind
  7019. for (var i in this._vertexAttribArrays) {
  7020. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  7021. continue;
  7022. }
  7023. this._gl.disableVertexAttribArray(i);
  7024. }
  7025. this._gl = null;
  7026. // Events
  7027. window.removeEventListener("blur", this._onBlur);
  7028. window.removeEventListener("focus", this._onFocus);
  7029. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7030. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7031. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7032. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7033. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7034. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7035. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7036. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7037. };
  7038. // Loading screen
  7039. Engine.prototype.displayLoadingUI = function () {
  7040. this._loadingScreen.displayLoadingUI();
  7041. };
  7042. Engine.prototype.hideLoadingUI = function () {
  7043. this._loadingScreen.hideLoadingUI();
  7044. };
  7045. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7046. get: function () {
  7047. return this._loadingScreen;
  7048. },
  7049. set: function (loadingScreen) {
  7050. this._loadingScreen = loadingScreen;
  7051. },
  7052. enumerable: true,
  7053. configurable: true
  7054. });
  7055. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7056. set: function (text) {
  7057. this._loadingScreen.loadingUIText = text;
  7058. },
  7059. enumerable: true,
  7060. configurable: true
  7061. });
  7062. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7063. set: function (color) {
  7064. this._loadingScreen.loadingUIBackgroundColor = color;
  7065. },
  7066. enumerable: true,
  7067. configurable: true
  7068. });
  7069. // FPS
  7070. Engine.prototype.getFps = function () {
  7071. return this.fps;
  7072. };
  7073. Engine.prototype.getDeltaTime = function () {
  7074. return this.deltaTime;
  7075. };
  7076. Engine.prototype._measureFps = function () {
  7077. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7078. var length = this.previousFramesDuration.length;
  7079. if (length >= 2) {
  7080. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7081. }
  7082. if (length >= this.fpsRange) {
  7083. if (length > this.fpsRange) {
  7084. this.previousFramesDuration.splice(0, 1);
  7085. length = this.previousFramesDuration.length;
  7086. }
  7087. var sum = 0;
  7088. for (var id = 0; id < length - 1; id++) {
  7089. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7090. }
  7091. this.fps = 1000.0 / (sum / (length - 1));
  7092. }
  7093. };
  7094. // Statics
  7095. Engine.isSupported = function () {
  7096. try {
  7097. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7098. if (navigator.isCocoonJS) {
  7099. return true;
  7100. }
  7101. var tempcanvas = document.createElement("canvas");
  7102. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7103. return gl != null && !!window.WebGLRenderingContext;
  7104. }
  7105. catch (e) {
  7106. return false;
  7107. }
  7108. };
  7109. // Const statics
  7110. Engine._ALPHA_DISABLE = 0;
  7111. Engine._ALPHA_ADD = 1;
  7112. Engine._ALPHA_COMBINE = 2;
  7113. Engine._ALPHA_SUBTRACT = 3;
  7114. Engine._ALPHA_MULTIPLY = 4;
  7115. Engine._ALPHA_MAXIMIZED = 5;
  7116. Engine._ALPHA_ONEONE = 6;
  7117. Engine._DELAYLOADSTATE_NONE = 0;
  7118. Engine._DELAYLOADSTATE_LOADED = 1;
  7119. Engine._DELAYLOADSTATE_LOADING = 2;
  7120. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7121. Engine._TEXTUREFORMAT_ALPHA = 0;
  7122. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7123. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7124. Engine._TEXTUREFORMAT_RGB = 4;
  7125. Engine._TEXTUREFORMAT_RGBA = 5;
  7126. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7127. Engine._TEXTURETYPE_FLOAT = 1;
  7128. // Updatable statics so stick with vars here
  7129. Engine.Epsilon = 0.001;
  7130. Engine.CollisionsEpsilon = 0.001;
  7131. Engine.CodeRepository = "src/";
  7132. Engine.ShadersRepository = "src/Shaders/";
  7133. return Engine;
  7134. })();
  7135. BABYLON.Engine = Engine;
  7136. })(BABYLON || (BABYLON = {}));
  7137. var BABYLON;
  7138. (function (BABYLON) {
  7139. /**
  7140. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7141. */
  7142. var Node = (function () {
  7143. /**
  7144. * @constructor
  7145. * @param {string} name - the name and id to be given to this node
  7146. * @param {BABYLON.Scene} the scene this node will be added to
  7147. */
  7148. function Node(name, scene) {
  7149. this.state = "";
  7150. this.animations = new Array();
  7151. this._childrenFlag = -1;
  7152. this._isEnabled = true;
  7153. this._isReady = true;
  7154. this._currentRenderId = -1;
  7155. this._parentRenderId = -1;
  7156. this.name = name;
  7157. this.id = name;
  7158. this._scene = scene;
  7159. this._initCache();
  7160. }
  7161. Node.prototype.getScene = function () {
  7162. return this._scene;
  7163. };
  7164. Node.prototype.getEngine = function () {
  7165. return this._scene.getEngine();
  7166. };
  7167. // override it in derived class
  7168. Node.prototype.getWorldMatrix = function () {
  7169. return BABYLON.Matrix.Identity();
  7170. };
  7171. // override it in derived class if you add new variables to the cache
  7172. // and call the parent class method
  7173. Node.prototype._initCache = function () {
  7174. this._cache = {};
  7175. this._cache.parent = undefined;
  7176. };
  7177. Node.prototype.updateCache = function (force) {
  7178. if (!force && this.isSynchronized())
  7179. return;
  7180. this._cache.parent = this.parent;
  7181. this._updateCache();
  7182. };
  7183. // override it in derived class if you add new variables to the cache
  7184. // and call the parent class method if !ignoreParentClass
  7185. Node.prototype._updateCache = function (ignoreParentClass) {
  7186. };
  7187. // override it in derived class if you add new variables to the cache
  7188. Node.prototype._isSynchronized = function () {
  7189. return true;
  7190. };
  7191. Node.prototype._markSyncedWithParent = function () {
  7192. this._parentRenderId = this.parent._currentRenderId;
  7193. };
  7194. Node.prototype.isSynchronizedWithParent = function () {
  7195. if (!this.parent) {
  7196. return true;
  7197. }
  7198. if (this._parentRenderId !== this.parent._currentRenderId) {
  7199. return false;
  7200. }
  7201. return this.parent.isSynchronized();
  7202. };
  7203. Node.prototype.isSynchronized = function (updateCache) {
  7204. var check = this.hasNewParent();
  7205. check = check || !this.isSynchronizedWithParent();
  7206. check = check || !this._isSynchronized();
  7207. if (updateCache)
  7208. this.updateCache(true);
  7209. return !check;
  7210. };
  7211. Node.prototype.hasNewParent = function (update) {
  7212. if (this._cache.parent === this.parent)
  7213. return false;
  7214. if (update)
  7215. this._cache.parent = this.parent;
  7216. return true;
  7217. };
  7218. /**
  7219. * Is this node ready to be used/rendered
  7220. * @return {boolean} is it ready
  7221. */
  7222. Node.prototype.isReady = function () {
  7223. return this._isReady;
  7224. };
  7225. /**
  7226. * Is this node enabled.
  7227. * If the node has a parent and is enabled, the parent will be inspected as well.
  7228. * @return {boolean} whether this node (and its parent) is enabled.
  7229. * @see setEnabled
  7230. */
  7231. Node.prototype.isEnabled = function () {
  7232. if (!this._isEnabled) {
  7233. return false;
  7234. }
  7235. if (this.parent) {
  7236. return this.parent.isEnabled();
  7237. }
  7238. return true;
  7239. };
  7240. /**
  7241. * Set the enabled state of this node.
  7242. * @param {boolean} value - the new enabled state
  7243. * @see isEnabled
  7244. */
  7245. Node.prototype.setEnabled = function (value) {
  7246. this._isEnabled = value;
  7247. };
  7248. /**
  7249. * Is this node a descendant of the given node.
  7250. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7251. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7252. * @see parent
  7253. */
  7254. Node.prototype.isDescendantOf = function (ancestor) {
  7255. if (this.parent) {
  7256. if (this.parent === ancestor) {
  7257. return true;
  7258. }
  7259. return this.parent.isDescendantOf(ancestor);
  7260. }
  7261. return false;
  7262. };
  7263. Node.prototype._getDescendants = function (list, results) {
  7264. for (var index = 0; index < list.length; index++) {
  7265. var item = list[index];
  7266. if (item.isDescendantOf(this)) {
  7267. results.push(item);
  7268. }
  7269. }
  7270. };
  7271. /**
  7272. * Will return all nodes that have this node as parent.
  7273. * @return {BABYLON.Node[]} all children nodes of all types.
  7274. */
  7275. Node.prototype.getDescendants = function () {
  7276. var results = [];
  7277. this._getDescendants(this._scene.meshes, results);
  7278. this._getDescendants(this._scene.lights, results);
  7279. this._getDescendants(this._scene.cameras, results);
  7280. return results;
  7281. };
  7282. Node.prototype._setReady = function (state) {
  7283. if (state == this._isReady) {
  7284. return;
  7285. }
  7286. if (!state) {
  7287. this._isReady = false;
  7288. return;
  7289. }
  7290. this._isReady = true;
  7291. if (this.onReady) {
  7292. this.onReady(this);
  7293. }
  7294. };
  7295. return Node;
  7296. })();
  7297. BABYLON.Node = Node;
  7298. })(BABYLON || (BABYLON = {}));
  7299. var BABYLON;
  7300. (function (BABYLON) {
  7301. var FilesInput = (function () {
  7302. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7303. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7304. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7305. this._engine = p_engine;
  7306. this._canvas = p_canvas;
  7307. this._currentScene = p_scene;
  7308. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7309. this._progressCallback = p_progressCallback;
  7310. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7311. this._textureLoadingCallback = p_textureLoadingCallback;
  7312. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7313. }
  7314. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7315. var _this = this;
  7316. if (p_elementToMonitor) {
  7317. this._elementToMonitor = p_elementToMonitor;
  7318. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7319. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7320. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7321. }
  7322. };
  7323. FilesInput.prototype.renderFunction = function () {
  7324. if (this._additionnalRenderLoopLogicCallback) {
  7325. this._additionnalRenderLoopLogicCallback();
  7326. }
  7327. if (this._currentScene) {
  7328. if (this._textureLoadingCallback) {
  7329. var remaining = this._currentScene.getWaitingItemsCount();
  7330. if (remaining > 0) {
  7331. this._textureLoadingCallback(remaining);
  7332. }
  7333. }
  7334. this._currentScene.render();
  7335. }
  7336. };
  7337. FilesInput.prototype.drag = function (e) {
  7338. e.stopPropagation();
  7339. e.preventDefault();
  7340. };
  7341. FilesInput.prototype.drop = function (eventDrop) {
  7342. eventDrop.stopPropagation();
  7343. eventDrop.preventDefault();
  7344. this.loadFiles(eventDrop);
  7345. };
  7346. FilesInput.prototype.loadFiles = function (event) {
  7347. if (this._startingProcessingFilesCallback)
  7348. this._startingProcessingFilesCallback();
  7349. // Handling data transfer via drag'n'drop
  7350. if (event && event.dataTransfer && event.dataTransfer.files) {
  7351. this._filesToLoad = event.dataTransfer.files;
  7352. }
  7353. // Handling files from input files
  7354. if (event && event.target && event.target.files) {
  7355. this._filesToLoad = event.target.files;
  7356. }
  7357. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7358. for (var i = 0; i < this._filesToLoad.length; i++) {
  7359. switch (this._filesToLoad[i].type) {
  7360. case "image/jpeg":
  7361. case "image/png":
  7362. case "image/bmp":
  7363. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7364. break;
  7365. case "image/targa":
  7366. case "image/vnd.ms-dds":
  7367. case "audio/wav":
  7368. case "audio/x-wav":
  7369. case "audio/mp3":
  7370. case "audio/mpeg":
  7371. case "audio/mpeg3":
  7372. case "audio/x-mpeg-3":
  7373. case "audio/ogg":
  7374. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7375. break;
  7376. default:
  7377. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7378. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7379. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7380. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7381. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7382. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7383. this._sceneFileToLoad = this._filesToLoad[i];
  7384. }
  7385. break;
  7386. }
  7387. }
  7388. this.reload();
  7389. }
  7390. };
  7391. FilesInput.prototype.reload = function () {
  7392. var _this = this;
  7393. var that = this;
  7394. // If a ".babylon" file has been provided
  7395. if (this._sceneFileToLoad) {
  7396. if (this._currentScene) {
  7397. if (BABYLON.Tools.errorsCount > 0) {
  7398. BABYLON.Tools.ClearLogCache();
  7399. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7400. }
  7401. this._engine.stopRenderLoop();
  7402. this._currentScene.dispose();
  7403. }
  7404. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7405. that._currentScene = newScene;
  7406. // Wait for textures and shaders to be ready
  7407. that._currentScene.executeWhenReady(function () {
  7408. // Attach camera to canvas inputs
  7409. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7410. that._currentScene.createDefaultCameraOrLight();
  7411. }
  7412. that._currentScene.activeCamera.attachControl(that._canvas);
  7413. if (that._sceneLoadedCallback) {
  7414. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7415. }
  7416. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7417. });
  7418. }, function (progress) {
  7419. if (_this._progressCallback) {
  7420. _this._progressCallback(progress);
  7421. }
  7422. });
  7423. }
  7424. else {
  7425. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7426. }
  7427. };
  7428. FilesInput.FilesTextures = new Array();
  7429. FilesInput.FilesToLoad = new Array();
  7430. return FilesInput;
  7431. })();
  7432. BABYLON.FilesInput = FilesInput;
  7433. })(BABYLON || (BABYLON = {}));
  7434. var BABYLON;
  7435. (function (BABYLON) {
  7436. var IntersectionInfo = (function () {
  7437. function IntersectionInfo(bu, bv, distance) {
  7438. this.bu = bu;
  7439. this.bv = bv;
  7440. this.distance = distance;
  7441. this.faceId = 0;
  7442. this.subMeshId = 0;
  7443. }
  7444. return IntersectionInfo;
  7445. })();
  7446. BABYLON.IntersectionInfo = IntersectionInfo;
  7447. var PickingInfo = (function () {
  7448. function PickingInfo() {
  7449. this.hit = false;
  7450. this.distance = 0;
  7451. this.pickedPoint = null;
  7452. this.pickedMesh = null;
  7453. this.bu = 0;
  7454. this.bv = 0;
  7455. this.faceId = -1;
  7456. this.subMeshId = 0;
  7457. this.pickedSprite = null;
  7458. }
  7459. // Methods
  7460. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7461. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7462. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7463. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7464. return null;
  7465. }
  7466. var indices = this.pickedMesh.getIndices();
  7467. var result;
  7468. if (useVerticesNormals) {
  7469. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7470. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7471. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7472. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7473. normal0 = normal0.scale(this.bu);
  7474. normal1 = normal1.scale(this.bv);
  7475. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7476. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7477. }
  7478. else {
  7479. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7480. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7481. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7482. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7483. var p1p2 = vertex1.subtract(vertex2);
  7484. var p3p2 = vertex3.subtract(vertex2);
  7485. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7486. }
  7487. if (useWorldCoordinates) {
  7488. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7489. }
  7490. return BABYLON.Vector3.Normalize(result);
  7491. };
  7492. PickingInfo.prototype.getTextureCoordinates = function () {
  7493. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7494. return null;
  7495. }
  7496. var indices = this.pickedMesh.getIndices();
  7497. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7498. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7499. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7500. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7501. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7502. uv1 = uv1.scale(this.bu);
  7503. uv2 = uv2.scale(this.bv);
  7504. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7505. };
  7506. return PickingInfo;
  7507. })();
  7508. BABYLON.PickingInfo = PickingInfo;
  7509. })(BABYLON || (BABYLON = {}));
  7510. var BABYLON;
  7511. (function (BABYLON) {
  7512. var BoundingSphere = (function () {
  7513. function BoundingSphere(minimum, maximum) {
  7514. this.minimum = minimum;
  7515. this.maximum = maximum;
  7516. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7517. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7518. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7519. this.radius = distance * 0.5;
  7520. this.centerWorld = BABYLON.Vector3.Zero();
  7521. this._update(BABYLON.Matrix.Identity());
  7522. }
  7523. // Methods
  7524. BoundingSphere.prototype._update = function (world) {
  7525. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7526. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7527. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7528. };
  7529. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7530. for (var i = 0; i < 6; i++) {
  7531. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7532. return false;
  7533. }
  7534. return true;
  7535. };
  7536. BoundingSphere.prototype.intersectsPoint = function (point) {
  7537. var x = this.centerWorld.x - point.x;
  7538. var y = this.centerWorld.y - point.y;
  7539. var z = this.centerWorld.z - point.z;
  7540. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7541. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7542. return false;
  7543. return true;
  7544. };
  7545. // Statics
  7546. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7547. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7548. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7549. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7550. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7551. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7552. return false;
  7553. return true;
  7554. };
  7555. return BoundingSphere;
  7556. })();
  7557. BABYLON.BoundingSphere = BoundingSphere;
  7558. })(BABYLON || (BABYLON = {}));
  7559. var BABYLON;
  7560. (function (BABYLON) {
  7561. var BoundingBox = (function () {
  7562. function BoundingBox(minimum, maximum) {
  7563. this.minimum = minimum;
  7564. this.maximum = maximum;
  7565. this.vectors = new Array();
  7566. this.vectorsWorld = new Array();
  7567. // Bounding vectors
  7568. this.vectors.push(this.minimum.clone());
  7569. this.vectors.push(this.maximum.clone());
  7570. this.vectors.push(this.minimum.clone());
  7571. this.vectors[2].x = this.maximum.x;
  7572. this.vectors.push(this.minimum.clone());
  7573. this.vectors[3].y = this.maximum.y;
  7574. this.vectors.push(this.minimum.clone());
  7575. this.vectors[4].z = this.maximum.z;
  7576. this.vectors.push(this.maximum.clone());
  7577. this.vectors[5].z = this.minimum.z;
  7578. this.vectors.push(this.maximum.clone());
  7579. this.vectors[6].x = this.minimum.x;
  7580. this.vectors.push(this.maximum.clone());
  7581. this.vectors[7].y = this.minimum.y;
  7582. // OBB
  7583. this.center = this.maximum.add(this.minimum).scale(0.5);
  7584. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7585. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7586. // World
  7587. for (var index = 0; index < this.vectors.length; index++) {
  7588. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7589. }
  7590. this.minimumWorld = BABYLON.Vector3.Zero();
  7591. this.maximumWorld = BABYLON.Vector3.Zero();
  7592. this._update(BABYLON.Matrix.Identity());
  7593. }
  7594. // Methods
  7595. BoundingBox.prototype.getWorldMatrix = function () {
  7596. return this._worldMatrix;
  7597. };
  7598. BoundingBox.prototype._update = function (world) {
  7599. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7600. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7601. for (var index = 0; index < this.vectors.length; index++) {
  7602. var v = this.vectorsWorld[index];
  7603. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7604. if (v.x < this.minimumWorld.x)
  7605. this.minimumWorld.x = v.x;
  7606. if (v.y < this.minimumWorld.y)
  7607. this.minimumWorld.y = v.y;
  7608. if (v.z < this.minimumWorld.z)
  7609. this.minimumWorld.z = v.z;
  7610. if (v.x > this.maximumWorld.x)
  7611. this.maximumWorld.x = v.x;
  7612. if (v.y > this.maximumWorld.y)
  7613. this.maximumWorld.y = v.y;
  7614. if (v.z > this.maximumWorld.z)
  7615. this.maximumWorld.z = v.z;
  7616. }
  7617. // OBB
  7618. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7619. this.center.scaleInPlace(0.5);
  7620. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7621. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7622. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7623. this._worldMatrix = world;
  7624. };
  7625. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7626. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7627. };
  7628. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7629. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7630. };
  7631. BoundingBox.prototype.intersectsPoint = function (point) {
  7632. var delta = -BABYLON.Engine.Epsilon;
  7633. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7634. return false;
  7635. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7636. return false;
  7637. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7638. return false;
  7639. return true;
  7640. };
  7641. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7642. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7643. };
  7644. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7645. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7646. return false;
  7647. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7648. return false;
  7649. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7650. return false;
  7651. return true;
  7652. };
  7653. // Statics
  7654. BoundingBox.Intersects = function (box0, box1) {
  7655. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7656. return false;
  7657. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7658. return false;
  7659. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7660. return false;
  7661. return true;
  7662. };
  7663. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7664. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7665. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7666. return (num <= (sphereRadius * sphereRadius));
  7667. };
  7668. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7669. for (var p = 0; p < 6; p++) {
  7670. for (var i = 0; i < 8; i++) {
  7671. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7672. return false;
  7673. }
  7674. }
  7675. }
  7676. return true;
  7677. };
  7678. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7679. for (var p = 0; p < 6; p++) {
  7680. var inCount = 8;
  7681. for (var i = 0; i < 8; i++) {
  7682. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7683. --inCount;
  7684. }
  7685. else {
  7686. break;
  7687. }
  7688. }
  7689. if (inCount === 0)
  7690. return false;
  7691. }
  7692. return true;
  7693. };
  7694. return BoundingBox;
  7695. })();
  7696. BABYLON.BoundingBox = BoundingBox;
  7697. })(BABYLON || (BABYLON = {}));
  7698. var BABYLON;
  7699. (function (BABYLON) {
  7700. var computeBoxExtents = function (axis, box) {
  7701. var p = BABYLON.Vector3.Dot(box.center, axis);
  7702. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7703. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7704. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7705. var r = r0 + r1 + r2;
  7706. return {
  7707. min: p - r,
  7708. max: p + r
  7709. };
  7710. };
  7711. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7712. var axisOverlap = function (axis, box0, box1) {
  7713. var result0 = computeBoxExtents(axis, box0);
  7714. var result1 = computeBoxExtents(axis, box1);
  7715. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7716. };
  7717. var BoundingInfo = (function () {
  7718. function BoundingInfo(minimum, maximum) {
  7719. this.minimum = minimum;
  7720. this.maximum = maximum;
  7721. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7722. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7723. }
  7724. // Methods
  7725. BoundingInfo.prototype._update = function (world) {
  7726. this.boundingBox._update(world);
  7727. this.boundingSphere._update(world);
  7728. };
  7729. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7730. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7731. return false;
  7732. return this.boundingBox.isInFrustum(frustumPlanes);
  7733. };
  7734. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7735. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7736. };
  7737. BoundingInfo.prototype._checkCollision = function (collider) {
  7738. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7739. };
  7740. BoundingInfo.prototype.intersectsPoint = function (point) {
  7741. if (!this.boundingSphere.centerWorld) {
  7742. return false;
  7743. }
  7744. if (!this.boundingSphere.intersectsPoint(point)) {
  7745. return false;
  7746. }
  7747. if (!this.boundingBox.intersectsPoint(point)) {
  7748. return false;
  7749. }
  7750. return true;
  7751. };
  7752. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7753. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7754. return false;
  7755. }
  7756. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7757. return false;
  7758. }
  7759. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7760. return false;
  7761. }
  7762. if (!precise) {
  7763. return true;
  7764. }
  7765. var box0 = this.boundingBox;
  7766. var box1 = boundingInfo.boundingBox;
  7767. if (!axisOverlap(box0.directions[0], box0, box1))
  7768. return false;
  7769. if (!axisOverlap(box0.directions[1], box0, box1))
  7770. return false;
  7771. if (!axisOverlap(box0.directions[2], box0, box1))
  7772. return false;
  7773. if (!axisOverlap(box1.directions[0], box0, box1))
  7774. return false;
  7775. if (!axisOverlap(box1.directions[1], box0, box1))
  7776. return false;
  7777. if (!axisOverlap(box1.directions[2], box0, box1))
  7778. return false;
  7779. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7780. return false;
  7781. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7782. return false;
  7783. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7784. return false;
  7785. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7786. return false;
  7787. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7788. return false;
  7789. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7790. return false;
  7791. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7792. return false;
  7793. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7794. return false;
  7795. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7796. return false;
  7797. return true;
  7798. };
  7799. return BoundingInfo;
  7800. })();
  7801. BABYLON.BoundingInfo = BoundingInfo;
  7802. })(BABYLON || (BABYLON = {}));
  7803. var BABYLON;
  7804. (function (BABYLON) {
  7805. var AbstractMesh = (function (_super) {
  7806. __extends(AbstractMesh, _super);
  7807. function AbstractMesh(name, scene) {
  7808. var _this = this;
  7809. _super.call(this, name, scene);
  7810. // Properties
  7811. this.definedFacingForward = true; // orientation for POV movement & rotation
  7812. this.position = new BABYLON.Vector3(0, 0, 0);
  7813. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7814. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7815. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7816. this.visibility = 1.0;
  7817. this.alphaIndex = Number.MAX_VALUE;
  7818. this.infiniteDistance = false;
  7819. this.isVisible = true;
  7820. this.isPickable = true;
  7821. this.showBoundingBox = false;
  7822. this.showSubMeshesBoundingBox = false;
  7823. this.onDispose = null;
  7824. this.isBlocker = false;
  7825. this.renderingGroupId = 0;
  7826. this.receiveShadows = false;
  7827. this.renderOutline = false;
  7828. this.outlineColor = BABYLON.Color3.Red();
  7829. this.outlineWidth = 0.02;
  7830. this.renderOverlay = false;
  7831. this.overlayColor = BABYLON.Color3.Red();
  7832. this.overlayAlpha = 0.5;
  7833. this.hasVertexAlpha = false;
  7834. this.useVertexColors = true;
  7835. this.applyFog = true;
  7836. this.computeBonesUsingShaders = true;
  7837. this.scalingDeterminant = 1;
  7838. this.useOctreeForRenderingSelection = true;
  7839. this.useOctreeForPicking = true;
  7840. this.useOctreeForCollisions = true;
  7841. this.layerMask = 0x0FFFFFFF;
  7842. this.alwaysSelectAsActiveMesh = false;
  7843. // Physics
  7844. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7845. // Collisions
  7846. this._checkCollisions = false;
  7847. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7848. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7849. this._collider = new BABYLON.Collider();
  7850. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7851. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7852. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7853. // Edges
  7854. this.edgesWidth = 1;
  7855. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7856. // Cache
  7857. this._localScaling = BABYLON.Matrix.Zero();
  7858. this._localRotation = BABYLON.Matrix.Zero();
  7859. this._localTranslation = BABYLON.Matrix.Zero();
  7860. this._localBillboard = BABYLON.Matrix.Zero();
  7861. this._localPivotScaling = BABYLON.Matrix.Zero();
  7862. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7863. this._localWorld = BABYLON.Matrix.Zero();
  7864. this._worldMatrix = BABYLON.Matrix.Zero();
  7865. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7866. this._absolutePosition = BABYLON.Vector3.Zero();
  7867. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7868. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7869. this._isDirty = false;
  7870. this._pivotMatrix = BABYLON.Matrix.Identity();
  7871. this._isDisposed = false;
  7872. this._renderId = 0;
  7873. this._intersectionsInProgress = new Array();
  7874. this._onAfterWorldMatrixUpdate = new Array();
  7875. this._isWorldMatrixFrozen = false;
  7876. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7877. if (collidedMesh === void 0) { collidedMesh = null; }
  7878. //TODO move this to the collision coordinator!
  7879. if (_this.getScene().workerCollisions)
  7880. newPosition.multiplyInPlace(_this._collider.radius);
  7881. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7882. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7883. _this.position.addInPlace(_this._diffPositionForCollisions);
  7884. }
  7885. if (_this.onCollide && collidedMesh) {
  7886. _this.onCollide(collidedMesh);
  7887. }
  7888. };
  7889. scene.addMesh(this);
  7890. }
  7891. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7892. get: function () {
  7893. return AbstractMesh._BILLBOARDMODE_NONE;
  7894. },
  7895. enumerable: true,
  7896. configurable: true
  7897. });
  7898. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7899. get: function () {
  7900. return AbstractMesh._BILLBOARDMODE_X;
  7901. },
  7902. enumerable: true,
  7903. configurable: true
  7904. });
  7905. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7906. get: function () {
  7907. return AbstractMesh._BILLBOARDMODE_Y;
  7908. },
  7909. enumerable: true,
  7910. configurable: true
  7911. });
  7912. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7913. get: function () {
  7914. return AbstractMesh._BILLBOARDMODE_Z;
  7915. },
  7916. enumerable: true,
  7917. configurable: true
  7918. });
  7919. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7920. get: function () {
  7921. return AbstractMesh._BILLBOARDMODE_ALL;
  7922. },
  7923. enumerable: true,
  7924. configurable: true
  7925. });
  7926. // Methods
  7927. AbstractMesh.prototype.disableEdgesRendering = function () {
  7928. if (this._edgesRenderer !== undefined) {
  7929. this._edgesRenderer.dispose();
  7930. this._edgesRenderer = undefined;
  7931. }
  7932. };
  7933. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7934. if (epsilon === void 0) { epsilon = 0.95; }
  7935. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7936. this.disableEdgesRendering();
  7937. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7938. };
  7939. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7940. get: function () {
  7941. return false;
  7942. },
  7943. enumerable: true,
  7944. configurable: true
  7945. });
  7946. AbstractMesh.prototype.getLOD = function (camera) {
  7947. return this;
  7948. };
  7949. AbstractMesh.prototype.getTotalVertices = function () {
  7950. return 0;
  7951. };
  7952. AbstractMesh.prototype.getIndices = function () {
  7953. return null;
  7954. };
  7955. AbstractMesh.prototype.getVerticesData = function (kind) {
  7956. return null;
  7957. };
  7958. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7959. return false;
  7960. };
  7961. AbstractMesh.prototype.getBoundingInfo = function () {
  7962. if (this._masterMesh) {
  7963. return this._masterMesh.getBoundingInfo();
  7964. }
  7965. if (!this._boundingInfo) {
  7966. this._updateBoundingInfo();
  7967. }
  7968. return this._boundingInfo;
  7969. };
  7970. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7971. get: function () {
  7972. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7973. },
  7974. enumerable: true,
  7975. configurable: true
  7976. });
  7977. AbstractMesh.prototype._preActivate = function () {
  7978. };
  7979. AbstractMesh.prototype._activate = function (renderId) {
  7980. this._renderId = renderId;
  7981. };
  7982. AbstractMesh.prototype.getWorldMatrix = function () {
  7983. if (this._masterMesh) {
  7984. return this._masterMesh.getWorldMatrix();
  7985. }
  7986. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7987. this.computeWorldMatrix();
  7988. }
  7989. return this._worldMatrix;
  7990. };
  7991. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7992. get: function () {
  7993. return this._worldMatrix;
  7994. },
  7995. enumerable: true,
  7996. configurable: true
  7997. });
  7998. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7999. get: function () {
  8000. return this._absolutePosition;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8006. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8007. this.computeWorldMatrix(true);
  8008. this._isWorldMatrixFrozen = true;
  8009. };
  8010. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8011. this._isWorldMatrixFrozen = false;
  8012. this.computeWorldMatrix(true);
  8013. };
  8014. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8015. get: function () {
  8016. return this._isWorldMatrixFrozen;
  8017. },
  8018. enumerable: true,
  8019. configurable: true
  8020. });
  8021. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8022. axis.normalize();
  8023. if (!this.rotationQuaternion) {
  8024. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8025. this.rotation = BABYLON.Vector3.Zero();
  8026. }
  8027. var rotationQuaternion;
  8028. if (!space || space === BABYLON.Space.LOCAL) {
  8029. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8030. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8031. }
  8032. else {
  8033. if (this.parent) {
  8034. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8035. invertParentWorldMatrix.invert();
  8036. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8037. }
  8038. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8039. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8040. }
  8041. };
  8042. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8043. var displacementVector = axis.scale(distance);
  8044. if (!space || space === BABYLON.Space.LOCAL) {
  8045. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8046. this.setPositionWithLocalVector(tempV3);
  8047. }
  8048. else {
  8049. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8050. }
  8051. };
  8052. AbstractMesh.prototype.getAbsolutePosition = function () {
  8053. this.computeWorldMatrix();
  8054. return this._absolutePosition;
  8055. };
  8056. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8057. if (!absolutePosition) {
  8058. return;
  8059. }
  8060. var absolutePositionX;
  8061. var absolutePositionY;
  8062. var absolutePositionZ;
  8063. if (absolutePosition.x === undefined) {
  8064. if (arguments.length < 3) {
  8065. return;
  8066. }
  8067. absolutePositionX = arguments[0];
  8068. absolutePositionY = arguments[1];
  8069. absolutePositionZ = arguments[2];
  8070. }
  8071. else {
  8072. absolutePositionX = absolutePosition.x;
  8073. absolutePositionY = absolutePosition.y;
  8074. absolutePositionZ = absolutePosition.z;
  8075. }
  8076. if (this.parent) {
  8077. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8078. invertParentWorldMatrix.invert();
  8079. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8080. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8081. }
  8082. else {
  8083. this.position.x = absolutePositionX;
  8084. this.position.y = absolutePositionY;
  8085. this.position.z = absolutePositionZ;
  8086. }
  8087. };
  8088. // ================================== Point of View Movement =================================
  8089. /**
  8090. * Perform relative position change from the point of view of behind the front of the mesh.
  8091. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8092. * Supports definition of mesh facing forward or backward.
  8093. * @param {number} amountRight
  8094. * @param {number} amountUp
  8095. * @param {number} amountForward
  8096. */
  8097. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8098. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8099. };
  8100. /**
  8101. * Calculate relative position change from the point of view of behind the front of the mesh.
  8102. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8103. * Supports definition of mesh facing forward or backward.
  8104. * @param {number} amountRight
  8105. * @param {number} amountUp
  8106. * @param {number} amountForward
  8107. */
  8108. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8109. var rotMatrix = new BABYLON.Matrix();
  8110. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8111. rotQuaternion.toRotationMatrix(rotMatrix);
  8112. var translationDelta = BABYLON.Vector3.Zero();
  8113. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8114. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8115. return translationDelta;
  8116. };
  8117. // ================================== Point of View Rotation =================================
  8118. /**
  8119. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8120. * Supports definition of mesh facing forward or backward.
  8121. * @param {number} flipBack
  8122. * @param {number} twirlClockwise
  8123. * @param {number} tiltRight
  8124. */
  8125. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8126. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8127. };
  8128. /**
  8129. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8130. * Supports definition of mesh facing forward or backward.
  8131. * @param {number} flipBack
  8132. * @param {number} twirlClockwise
  8133. * @param {number} tiltRight
  8134. */
  8135. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8136. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8137. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8138. };
  8139. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8140. this._pivotMatrix = matrix;
  8141. this._cache.pivotMatrixUpdated = true;
  8142. };
  8143. AbstractMesh.prototype.getPivotMatrix = function () {
  8144. return this._pivotMatrix;
  8145. };
  8146. AbstractMesh.prototype._isSynchronized = function () {
  8147. if (this._isDirty) {
  8148. return false;
  8149. }
  8150. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8151. return false;
  8152. if (this._cache.pivotMatrixUpdated) {
  8153. return false;
  8154. }
  8155. if (this.infiniteDistance) {
  8156. return false;
  8157. }
  8158. if (!this._cache.position.equals(this.position))
  8159. return false;
  8160. if (this.rotationQuaternion) {
  8161. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8162. return false;
  8163. }
  8164. else {
  8165. if (!this._cache.rotation.equals(this.rotation))
  8166. return false;
  8167. }
  8168. if (!this._cache.scaling.equals(this.scaling))
  8169. return false;
  8170. return true;
  8171. };
  8172. AbstractMesh.prototype._initCache = function () {
  8173. _super.prototype._initCache.call(this);
  8174. this._cache.localMatrixUpdated = false;
  8175. this._cache.position = BABYLON.Vector3.Zero();
  8176. this._cache.scaling = BABYLON.Vector3.Zero();
  8177. this._cache.rotation = BABYLON.Vector3.Zero();
  8178. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8179. };
  8180. AbstractMesh.prototype.markAsDirty = function (property) {
  8181. if (property === "rotation") {
  8182. this.rotationQuaternion = null;
  8183. }
  8184. this._currentRenderId = Number.MAX_VALUE;
  8185. this._isDirty = true;
  8186. };
  8187. AbstractMesh.prototype._updateBoundingInfo = function () {
  8188. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8189. this._boundingInfo._update(this.worldMatrixFromCache);
  8190. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8191. };
  8192. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8193. if (!this.subMeshes) {
  8194. return;
  8195. }
  8196. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8197. var subMesh = this.subMeshes[subIndex];
  8198. subMesh.updateBoundingInfo(matrix);
  8199. }
  8200. };
  8201. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8202. if (this._isWorldMatrixFrozen) {
  8203. return this._worldMatrix;
  8204. }
  8205. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8206. return this._worldMatrix;
  8207. }
  8208. this._cache.position.copyFrom(this.position);
  8209. this._cache.scaling.copyFrom(this.scaling);
  8210. this._cache.pivotMatrixUpdated = false;
  8211. this._currentRenderId = this.getScene().getRenderId();
  8212. this._isDirty = false;
  8213. // Scaling
  8214. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  8215. // Rotation
  8216. if (this.rotationQuaternion) {
  8217. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8218. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8219. }
  8220. else {
  8221. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8222. this._cache.rotation.copyFrom(this.rotation);
  8223. }
  8224. // Translation
  8225. if (this.infiniteDistance && !this.parent) {
  8226. var camera = this.getScene().activeCamera;
  8227. if (camera) {
  8228. var cameraWorldMatrix = camera.getWorldMatrix();
  8229. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8230. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8231. }
  8232. }
  8233. else {
  8234. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8235. }
  8236. // Composing transformations
  8237. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8238. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8239. // Billboarding
  8240. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8241. var localPosition = this.position.clone();
  8242. var zero = this.getScene().activeCamera.globalPosition.clone();
  8243. if (this.parent && this.parent.position) {
  8244. localPosition.addInPlace(this.parent.position);
  8245. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8246. }
  8247. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8248. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8249. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8250. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8251. zero.y = localPosition.y + 0.001;
  8252. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8253. zero.z = localPosition.z + 0.001;
  8254. }
  8255. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8256. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8257. this._localBillboard.invert();
  8258. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8259. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8260. }
  8261. // Local world
  8262. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8263. // Parent
  8264. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8265. this._markSyncedWithParent();
  8266. if (this._meshToBoneReferal) {
  8267. if (!this._localMeshReferalTransform) {
  8268. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8269. }
  8270. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8271. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8272. }
  8273. else {
  8274. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8275. }
  8276. }
  8277. else {
  8278. this._worldMatrix.copyFrom(this._localWorld);
  8279. }
  8280. // Bounding info
  8281. this._updateBoundingInfo();
  8282. // Absolute position
  8283. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8284. // Callbacks
  8285. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8286. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8287. }
  8288. return this._worldMatrix;
  8289. };
  8290. /**
  8291. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8292. * @param func: callback function to add
  8293. */
  8294. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8295. this._onAfterWorldMatrixUpdate.push(func);
  8296. };
  8297. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8298. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8299. if (index > -1) {
  8300. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8301. }
  8302. };
  8303. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8304. this.computeWorldMatrix();
  8305. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8306. };
  8307. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8308. this.computeWorldMatrix();
  8309. var invLocalWorldMatrix = this._localWorld.clone();
  8310. invLocalWorldMatrix.invert();
  8311. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8312. };
  8313. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8314. this.computeWorldMatrix(true);
  8315. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8316. };
  8317. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8318. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8319. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8320. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8321. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8322. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8323. /// <returns>Mesh oriented towards targetMesh</returns>
  8324. yawCor = yawCor || 0; // default to zero if undefined
  8325. pitchCor = pitchCor || 0;
  8326. rollCor = rollCor || 0;
  8327. var dv = targetPoint.subtract(this.position);
  8328. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8329. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8330. var pitch = Math.atan2(dv.y, len);
  8331. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8332. };
  8333. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8334. this._meshToBoneReferal = affectedMesh;
  8335. this.parent = bone;
  8336. if (bone.getWorldMatrix().determinant() < 0) {
  8337. this.scalingDeterminant *= -1;
  8338. }
  8339. };
  8340. AbstractMesh.prototype.detachFromBone = function () {
  8341. if (this.parent.getWorldMatrix().determinant() < 0) {
  8342. this.scalingDeterminant *= -1;
  8343. }
  8344. this._meshToBoneReferal = null;
  8345. this.parent = null;
  8346. };
  8347. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8348. return this._boundingInfo.isInFrustum(frustumPlanes);
  8349. };
  8350. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8351. if (!camera) {
  8352. camera = this.getScene().activeCamera;
  8353. }
  8354. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8355. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8356. return false;
  8357. }
  8358. return true;
  8359. };
  8360. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8361. if (!this._boundingInfo || !mesh._boundingInfo) {
  8362. return false;
  8363. }
  8364. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8365. };
  8366. AbstractMesh.prototype.intersectsPoint = function (point) {
  8367. if (!this._boundingInfo) {
  8368. return false;
  8369. }
  8370. return this._boundingInfo.intersectsPoint(point);
  8371. };
  8372. // Physics
  8373. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8374. var physicsEngine = this.getScene().getPhysicsEngine();
  8375. if (!physicsEngine) {
  8376. return null;
  8377. }
  8378. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8379. if (impostor.impostor) {
  8380. // Old API
  8381. options = impostor;
  8382. impostor = impostor.impostor;
  8383. }
  8384. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8385. physicsEngine._unregisterMesh(this);
  8386. return null;
  8387. }
  8388. if (!options) {
  8389. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8390. }
  8391. else {
  8392. if (!options.mass && options.mass !== 0)
  8393. options.mass = 0;
  8394. if (!options.friction && options.friction !== 0)
  8395. options.friction = 0.2;
  8396. if (!options.restitution && options.restitution !== 0)
  8397. options.restitution = 0.2;
  8398. }
  8399. this._physicImpostor = impostor;
  8400. this._physicsMass = options.mass;
  8401. this._physicsFriction = options.friction;
  8402. this._physicRestitution = options.restitution;
  8403. return physicsEngine._registerMesh(this, impostor, options);
  8404. };
  8405. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8406. if (!this._physicImpostor) {
  8407. return BABYLON.PhysicsEngine.NoImpostor;
  8408. }
  8409. return this._physicImpostor;
  8410. };
  8411. AbstractMesh.prototype.getPhysicsMass = function () {
  8412. if (!this._physicsMass) {
  8413. return 0;
  8414. }
  8415. return this._physicsMass;
  8416. };
  8417. AbstractMesh.prototype.getPhysicsFriction = function () {
  8418. if (!this._physicsFriction) {
  8419. return 0;
  8420. }
  8421. return this._physicsFriction;
  8422. };
  8423. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8424. if (!this._physicRestitution) {
  8425. return 0;
  8426. }
  8427. return this._physicRestitution;
  8428. };
  8429. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8430. if (!camera) {
  8431. camera = this.getScene().activeCamera;
  8432. }
  8433. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8434. };
  8435. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8436. if (!camera) {
  8437. camera = this.getScene().activeCamera;
  8438. }
  8439. return this.absolutePosition.subtract(camera.position).length();
  8440. };
  8441. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8442. if (!this._physicImpostor) {
  8443. return;
  8444. }
  8445. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8446. };
  8447. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8448. if (!this._physicImpostor) {
  8449. return;
  8450. }
  8451. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8452. };
  8453. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8454. if (!this._physicImpostor) {
  8455. return;
  8456. }
  8457. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8458. };
  8459. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8460. // Collisions
  8461. get: function () {
  8462. return this._checkCollisions;
  8463. },
  8464. set: function (collisionEnabled) {
  8465. this._checkCollisions = collisionEnabled;
  8466. if (this.getScene().workerCollisions) {
  8467. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8468. }
  8469. },
  8470. enumerable: true,
  8471. configurable: true
  8472. });
  8473. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8474. var globalPosition = this.getAbsolutePosition();
  8475. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8476. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8477. this._collider.radius = this.ellipsoid;
  8478. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8479. };
  8480. // Submeshes octree
  8481. /**
  8482. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8483. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8484. */
  8485. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8486. if (maxCapacity === void 0) { maxCapacity = 64; }
  8487. if (maxDepth === void 0) { maxDepth = 2; }
  8488. if (!this._submeshesOctree) {
  8489. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8490. }
  8491. this.computeWorldMatrix(true);
  8492. // Update octree
  8493. var bbox = this.getBoundingInfo().boundingBox;
  8494. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8495. return this._submeshesOctree;
  8496. };
  8497. // Collisions
  8498. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8499. this._generatePointsArray();
  8500. // Transformation
  8501. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8502. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8503. subMesh._lastColliderWorldVertices = [];
  8504. subMesh._trianglePlanes = [];
  8505. var start = subMesh.verticesStart;
  8506. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8507. for (var i = start; i < end; i++) {
  8508. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8509. }
  8510. }
  8511. // Collide
  8512. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8513. if (collider.collisionFound) {
  8514. collider.collidedMesh = this;
  8515. }
  8516. };
  8517. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8518. var subMeshes;
  8519. var len;
  8520. // Octrees
  8521. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8522. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8523. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8524. len = intersections.length;
  8525. subMeshes = intersections.data;
  8526. }
  8527. else {
  8528. subMeshes = this.subMeshes;
  8529. len = subMeshes.length;
  8530. }
  8531. for (var index = 0; index < len; index++) {
  8532. var subMesh = subMeshes[index];
  8533. // Bounding test
  8534. if (len > 1 && !subMesh._checkCollision(collider))
  8535. continue;
  8536. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8537. }
  8538. };
  8539. AbstractMesh.prototype._checkCollision = function (collider) {
  8540. // Bounding box test
  8541. if (!this._boundingInfo._checkCollision(collider))
  8542. return;
  8543. // Transformation matrix
  8544. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8545. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8546. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8547. };
  8548. // Picking
  8549. AbstractMesh.prototype._generatePointsArray = function () {
  8550. return false;
  8551. };
  8552. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8553. var pickingInfo = new BABYLON.PickingInfo();
  8554. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8555. return pickingInfo;
  8556. }
  8557. if (!this._generatePointsArray()) {
  8558. return pickingInfo;
  8559. }
  8560. var intersectInfo = null;
  8561. // Octrees
  8562. var subMeshes;
  8563. var len;
  8564. if (this._submeshesOctree && this.useOctreeForPicking) {
  8565. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8566. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8567. len = intersections.length;
  8568. subMeshes = intersections.data;
  8569. }
  8570. else {
  8571. subMeshes = this.subMeshes;
  8572. len = subMeshes.length;
  8573. }
  8574. for (var index = 0; index < len; index++) {
  8575. var subMesh = subMeshes[index];
  8576. // Bounding test
  8577. if (len > 1 && !subMesh.canIntersects(ray))
  8578. continue;
  8579. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8580. if (currentIntersectInfo) {
  8581. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8582. intersectInfo = currentIntersectInfo;
  8583. intersectInfo.subMeshId = index;
  8584. if (fastCheck) {
  8585. break;
  8586. }
  8587. }
  8588. }
  8589. }
  8590. if (intersectInfo) {
  8591. // Get picked point
  8592. var world = this.getWorldMatrix();
  8593. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8594. var direction = ray.direction.clone();
  8595. direction = direction.scale(intersectInfo.distance);
  8596. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8597. var pickedPoint = worldOrigin.add(worldDirection);
  8598. // Return result
  8599. pickingInfo.hit = true;
  8600. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8601. pickingInfo.pickedPoint = pickedPoint;
  8602. pickingInfo.pickedMesh = this;
  8603. pickingInfo.bu = intersectInfo.bu;
  8604. pickingInfo.bv = intersectInfo.bv;
  8605. pickingInfo.faceId = intersectInfo.faceId;
  8606. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8607. return pickingInfo;
  8608. }
  8609. return pickingInfo;
  8610. };
  8611. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8612. return null;
  8613. };
  8614. AbstractMesh.prototype.releaseSubMeshes = function () {
  8615. if (this.subMeshes) {
  8616. while (this.subMeshes.length) {
  8617. this.subMeshes[0].dispose();
  8618. }
  8619. }
  8620. else {
  8621. this.subMeshes = new Array();
  8622. }
  8623. };
  8624. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8625. var index;
  8626. // Physics
  8627. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8628. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8629. }
  8630. // Intersections in progress
  8631. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8632. var other = this._intersectionsInProgress[index];
  8633. var pos = other._intersectionsInProgress.indexOf(this);
  8634. other._intersectionsInProgress.splice(pos, 1);
  8635. }
  8636. this._intersectionsInProgress = [];
  8637. // Edges
  8638. if (this._edgesRenderer) {
  8639. this._edgesRenderer.dispose();
  8640. this._edgesRenderer = null;
  8641. }
  8642. // SubMeshes
  8643. this.releaseSubMeshes();
  8644. // Remove from scene
  8645. this.getScene().removeMesh(this);
  8646. if (!doNotRecurse) {
  8647. // Particles
  8648. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8649. if (this.getScene().particleSystems[index].emitter === this) {
  8650. this.getScene().particleSystems[index].dispose();
  8651. index--;
  8652. }
  8653. }
  8654. // Children
  8655. var objects = this.getScene().meshes.slice(0);
  8656. for (index = 0; index < objects.length; index++) {
  8657. if (objects[index].parent === this) {
  8658. objects[index].dispose();
  8659. }
  8660. }
  8661. }
  8662. else {
  8663. for (index = 0; index < this.getScene().meshes.length; index++) {
  8664. var obj = this.getScene().meshes[index];
  8665. if (obj.parent === this) {
  8666. obj.parent = null;
  8667. obj.computeWorldMatrix(true);
  8668. }
  8669. }
  8670. }
  8671. this._onAfterWorldMatrixUpdate = [];
  8672. this._isDisposed = true;
  8673. // Callback
  8674. if (this.onDispose) {
  8675. this.onDispose();
  8676. }
  8677. };
  8678. // Statics
  8679. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8680. AbstractMesh._BILLBOARDMODE_X = 1;
  8681. AbstractMesh._BILLBOARDMODE_Y = 2;
  8682. AbstractMesh._BILLBOARDMODE_Z = 4;
  8683. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8684. return AbstractMesh;
  8685. })(BABYLON.Node);
  8686. BABYLON.AbstractMesh = AbstractMesh;
  8687. })(BABYLON || (BABYLON = {}));
  8688. var BABYLON;
  8689. (function (BABYLON) {
  8690. var Light = (function (_super) {
  8691. __extends(Light, _super);
  8692. function Light(name, scene) {
  8693. _super.call(this, name, scene);
  8694. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8695. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8696. this.intensity = 1.0;
  8697. this.range = Number.MAX_VALUE;
  8698. this.includeOnlyWithLayerMask = 0;
  8699. this.includedOnlyMeshes = new Array();
  8700. this.excludedMeshes = new Array();
  8701. this.excludeWithLayerMask = 0;
  8702. this._excludedMeshesIds = new Array();
  8703. this._includedOnlyMeshesIds = new Array();
  8704. scene.addLight(this);
  8705. }
  8706. Light.prototype.getShadowGenerator = function () {
  8707. return this._shadowGenerator;
  8708. };
  8709. Light.prototype.getAbsolutePosition = function () {
  8710. return BABYLON.Vector3.Zero();
  8711. };
  8712. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8713. };
  8714. Light.prototype._getWorldMatrix = function () {
  8715. return BABYLON.Matrix.Identity();
  8716. };
  8717. Light.prototype.canAffectMesh = function (mesh) {
  8718. if (!mesh) {
  8719. return true;
  8720. }
  8721. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8722. return false;
  8723. }
  8724. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8725. return false;
  8726. }
  8727. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8728. return false;
  8729. }
  8730. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8731. return false;
  8732. }
  8733. return true;
  8734. };
  8735. Light.prototype.getWorldMatrix = function () {
  8736. this._currentRenderId = this.getScene().getRenderId();
  8737. var worldMatrix = this._getWorldMatrix();
  8738. if (this.parent && this.parent.getWorldMatrix) {
  8739. if (!this._parentedWorldMatrix) {
  8740. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8741. }
  8742. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8743. this._markSyncedWithParent();
  8744. return this._parentedWorldMatrix;
  8745. }
  8746. return worldMatrix;
  8747. };
  8748. Light.prototype.dispose = function () {
  8749. if (this._shadowGenerator) {
  8750. this._shadowGenerator.dispose();
  8751. this._shadowGenerator = null;
  8752. }
  8753. // Remove from scene
  8754. this.getScene().removeLight(this);
  8755. };
  8756. return Light;
  8757. })(BABYLON.Node);
  8758. BABYLON.Light = Light;
  8759. })(BABYLON || (BABYLON = {}));
  8760. var BABYLON;
  8761. (function (BABYLON) {
  8762. var PointLight = (function (_super) {
  8763. __extends(PointLight, _super);
  8764. function PointLight(name, position, scene) {
  8765. _super.call(this, name, scene);
  8766. this.position = position;
  8767. }
  8768. PointLight.prototype.getAbsolutePosition = function () {
  8769. return this._transformedPosition ? this._transformedPosition : this.position;
  8770. };
  8771. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8772. if (this.parent && this.parent.getWorldMatrix) {
  8773. if (!this._transformedPosition) {
  8774. this._transformedPosition = BABYLON.Vector3.Zero();
  8775. }
  8776. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8777. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8778. return;
  8779. }
  8780. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8781. };
  8782. PointLight.prototype.getShadowGenerator = function () {
  8783. return null;
  8784. };
  8785. PointLight.prototype._getWorldMatrix = function () {
  8786. if (!this._worldMatrix) {
  8787. this._worldMatrix = BABYLON.Matrix.Identity();
  8788. }
  8789. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8790. return this._worldMatrix;
  8791. };
  8792. return PointLight;
  8793. })(BABYLON.Light);
  8794. BABYLON.PointLight = PointLight;
  8795. })(BABYLON || (BABYLON = {}));
  8796. var BABYLON;
  8797. (function (BABYLON) {
  8798. var SpotLight = (function (_super) {
  8799. __extends(SpotLight, _super);
  8800. function SpotLight(name, position, direction, angle, exponent, scene) {
  8801. _super.call(this, name, scene);
  8802. this.position = position;
  8803. this.direction = direction;
  8804. this.angle = angle;
  8805. this.exponent = exponent;
  8806. }
  8807. SpotLight.prototype.getAbsolutePosition = function () {
  8808. return this.transformedPosition ? this.transformedPosition : this.position;
  8809. };
  8810. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8811. var activeCamera = this.getScene().activeCamera;
  8812. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8813. };
  8814. SpotLight.prototype.supportsVSM = function () {
  8815. return true;
  8816. };
  8817. SpotLight.prototype.needRefreshPerFrame = function () {
  8818. return false;
  8819. };
  8820. SpotLight.prototype.setDirectionToTarget = function (target) {
  8821. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8822. return this.direction;
  8823. };
  8824. SpotLight.prototype.computeTransformedPosition = function () {
  8825. if (this.parent && this.parent.getWorldMatrix) {
  8826. if (!this.transformedPosition) {
  8827. this.transformedPosition = BABYLON.Vector3.Zero();
  8828. }
  8829. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8830. return true;
  8831. }
  8832. return false;
  8833. };
  8834. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8835. var normalizeDirection;
  8836. if (this.parent && this.parent.getWorldMatrix) {
  8837. if (!this._transformedDirection) {
  8838. this._transformedDirection = BABYLON.Vector3.Zero();
  8839. }
  8840. this.computeTransformedPosition();
  8841. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8842. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8843. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8844. }
  8845. else {
  8846. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8847. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8848. }
  8849. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8850. };
  8851. SpotLight.prototype._getWorldMatrix = function () {
  8852. if (!this._worldMatrix) {
  8853. this._worldMatrix = BABYLON.Matrix.Identity();
  8854. }
  8855. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8856. return this._worldMatrix;
  8857. };
  8858. return SpotLight;
  8859. })(BABYLON.Light);
  8860. BABYLON.SpotLight = SpotLight;
  8861. })(BABYLON || (BABYLON = {}));
  8862. var BABYLON;
  8863. (function (BABYLON) {
  8864. var HemisphericLight = (function (_super) {
  8865. __extends(HemisphericLight, _super);
  8866. function HemisphericLight(name, direction, scene) {
  8867. _super.call(this, name, scene);
  8868. this.direction = direction;
  8869. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8870. }
  8871. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8872. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8873. return this.direction;
  8874. };
  8875. HemisphericLight.prototype.getShadowGenerator = function () {
  8876. return null;
  8877. };
  8878. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8879. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8880. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8881. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8882. };
  8883. HemisphericLight.prototype._getWorldMatrix = function () {
  8884. if (!this._worldMatrix) {
  8885. this._worldMatrix = BABYLON.Matrix.Identity();
  8886. }
  8887. return this._worldMatrix;
  8888. };
  8889. return HemisphericLight;
  8890. })(BABYLON.Light);
  8891. BABYLON.HemisphericLight = HemisphericLight;
  8892. })(BABYLON || (BABYLON = {}));
  8893. var BABYLON;
  8894. (function (BABYLON) {
  8895. var DirectionalLight = (function (_super) {
  8896. __extends(DirectionalLight, _super);
  8897. function DirectionalLight(name, direction, scene) {
  8898. _super.call(this, name, scene);
  8899. this.direction = direction;
  8900. this.shadowOrthoScale = 0.5;
  8901. this.position = direction.scale(-1);
  8902. }
  8903. DirectionalLight.prototype.getAbsolutePosition = function () {
  8904. return this.transformedPosition ? this.transformedPosition : this.position;
  8905. };
  8906. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8907. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8908. return this.direction;
  8909. };
  8910. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8911. var orthoLeft = Number.MAX_VALUE;
  8912. var orthoRight = Number.MIN_VALUE;
  8913. var orthoTop = Number.MIN_VALUE;
  8914. var orthoBottom = Number.MAX_VALUE;
  8915. var tempVector3 = BABYLON.Vector3.Zero();
  8916. var activeCamera = this.getScene().activeCamera;
  8917. // Check extends
  8918. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8919. var mesh = renderList[meshIndex];
  8920. if (!mesh) {
  8921. continue;
  8922. }
  8923. var boundingInfo = mesh.getBoundingInfo();
  8924. if (!boundingInfo) {
  8925. continue;
  8926. }
  8927. var boundingBox = boundingInfo.boundingBox;
  8928. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8929. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8930. if (tempVector3.x < orthoLeft)
  8931. orthoLeft = tempVector3.x;
  8932. if (tempVector3.y < orthoBottom)
  8933. orthoBottom = tempVector3.y;
  8934. if (tempVector3.x > orthoRight)
  8935. orthoRight = tempVector3.x;
  8936. if (tempVector3.y > orthoTop)
  8937. orthoTop = tempVector3.y;
  8938. }
  8939. }
  8940. var xOffset = orthoRight - orthoLeft;
  8941. var yOffset = orthoTop - orthoBottom;
  8942. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8943. };
  8944. DirectionalLight.prototype.supportsVSM = function () {
  8945. return true;
  8946. };
  8947. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8948. return true;
  8949. };
  8950. DirectionalLight.prototype.computeTransformedPosition = function () {
  8951. if (this.parent && this.parent.getWorldMatrix) {
  8952. if (!this.transformedPosition) {
  8953. this.transformedPosition = BABYLON.Vector3.Zero();
  8954. }
  8955. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8956. return true;
  8957. }
  8958. return false;
  8959. };
  8960. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8961. if (this.parent && this.parent.getWorldMatrix) {
  8962. if (!this._transformedDirection) {
  8963. this._transformedDirection = BABYLON.Vector3.Zero();
  8964. }
  8965. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8966. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8967. return;
  8968. }
  8969. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8970. };
  8971. DirectionalLight.prototype._getWorldMatrix = function () {
  8972. if (!this._worldMatrix) {
  8973. this._worldMatrix = BABYLON.Matrix.Identity();
  8974. }
  8975. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8976. return this._worldMatrix;
  8977. };
  8978. return DirectionalLight;
  8979. })(BABYLON.Light);
  8980. BABYLON.DirectionalLight = DirectionalLight;
  8981. })(BABYLON || (BABYLON = {}));
  8982. var BABYLON;
  8983. (function (BABYLON) {
  8984. var ShadowGenerator = (function () {
  8985. function ShadowGenerator(mapSize, light) {
  8986. var _this = this;
  8987. // Members
  8988. this._filter = ShadowGenerator.FILTER_NONE;
  8989. this.blurScale = 2;
  8990. this._blurBoxOffset = 0;
  8991. this._bias = 0.00005;
  8992. this._lightDirection = BABYLON.Vector3.Zero();
  8993. this._darkness = 0;
  8994. this._transparencyShadow = false;
  8995. this._viewMatrix = BABYLON.Matrix.Zero();
  8996. this._projectionMatrix = BABYLON.Matrix.Zero();
  8997. this._transformMatrix = BABYLON.Matrix.Zero();
  8998. this._worldViewProjection = BABYLON.Matrix.Zero();
  8999. this._light = light;
  9000. this._scene = light.getScene();
  9001. this._mapSize = mapSize;
  9002. light._shadowGenerator = this;
  9003. // Render target
  9004. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  9005. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9006. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9007. this._shadowMap.anisotropicFilteringLevel = 1;
  9008. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9009. this._shadowMap.renderParticles = false;
  9010. this._shadowMap.onAfterUnbind = function () {
  9011. if (!_this.useBlurVarianceShadowMap) {
  9012. return;
  9013. }
  9014. if (!_this._shadowMap2) {
  9015. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9016. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9017. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9018. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9019. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9020. _this._downSamplePostprocess.onApply = function (effect) {
  9021. effect.setTexture("textureSampler", _this._shadowMap);
  9022. };
  9023. _this.blurBoxOffset = 1;
  9024. }
  9025. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9026. };
  9027. // Custom render function
  9028. var renderSubMesh = function (subMesh) {
  9029. var mesh = subMesh.getRenderingMesh();
  9030. var scene = _this._scene;
  9031. var engine = scene.getEngine();
  9032. // Culling
  9033. engine.setState(subMesh.getMaterial().backFaceCulling);
  9034. // Managing instances
  9035. var batch = mesh._getInstancesRenderList(subMesh._id);
  9036. if (batch.mustReturn) {
  9037. return;
  9038. }
  9039. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  9040. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9041. engine.enableEffect(_this._effect);
  9042. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9043. var material = subMesh.getMaterial();
  9044. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9045. // Alpha test
  9046. if (material && material.needAlphaTesting()) {
  9047. var alphaTexture = material.getAlphaTestTexture();
  9048. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9049. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9050. }
  9051. // Bones
  9052. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9053. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  9054. }
  9055. // Draw
  9056. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9057. }
  9058. else {
  9059. // Need to reset refresh rate of the shadowMap
  9060. _this._shadowMap.resetRefreshCounter();
  9061. }
  9062. };
  9063. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9064. var index;
  9065. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9066. renderSubMesh(opaqueSubMeshes.data[index]);
  9067. }
  9068. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9069. renderSubMesh(alphaTestSubMeshes.data[index]);
  9070. }
  9071. if (_this._transparencyShadow) {
  9072. for (index = 0; index < transparentSubMeshes.length; index++) {
  9073. renderSubMesh(transparentSubMeshes.data[index]);
  9074. }
  9075. }
  9076. };
  9077. this._shadowMap.onClear = function (engine) {
  9078. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9079. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9080. }
  9081. else {
  9082. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9083. }
  9084. };
  9085. }
  9086. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9087. // Static
  9088. get: function () {
  9089. return ShadowGenerator._FILTER_NONE;
  9090. },
  9091. enumerable: true,
  9092. configurable: true
  9093. });
  9094. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9095. get: function () {
  9096. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9097. },
  9098. enumerable: true,
  9099. configurable: true
  9100. });
  9101. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9102. get: function () {
  9103. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9104. },
  9105. enumerable: true,
  9106. configurable: true
  9107. });
  9108. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9109. get: function () {
  9110. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9111. },
  9112. enumerable: true,
  9113. configurable: true
  9114. });
  9115. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9116. get: function () {
  9117. return this._bias;
  9118. },
  9119. set: function (bias) {
  9120. this._bias = bias;
  9121. },
  9122. enumerable: true,
  9123. configurable: true
  9124. });
  9125. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9126. get: function () {
  9127. return this._blurBoxOffset;
  9128. },
  9129. set: function (value) {
  9130. var _this = this;
  9131. if (this._blurBoxOffset === value) {
  9132. return;
  9133. }
  9134. this._blurBoxOffset = value;
  9135. if (this._boxBlurPostprocess) {
  9136. this._boxBlurPostprocess.dispose();
  9137. }
  9138. 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);
  9139. this._boxBlurPostprocess.onApply = function (effect) {
  9140. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9141. };
  9142. },
  9143. enumerable: true,
  9144. configurable: true
  9145. });
  9146. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9147. get: function () {
  9148. return this._filter;
  9149. },
  9150. set: function (value) {
  9151. if (this._filter === value) {
  9152. return;
  9153. }
  9154. this._filter = value;
  9155. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9156. this._shadowMap.anisotropicFilteringLevel = 16;
  9157. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9158. }
  9159. else {
  9160. this._shadowMap.anisotropicFilteringLevel = 1;
  9161. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9162. }
  9163. },
  9164. enumerable: true,
  9165. configurable: true
  9166. });
  9167. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9168. get: function () {
  9169. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9170. },
  9171. set: function (value) {
  9172. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9173. },
  9174. enumerable: true,
  9175. configurable: true
  9176. });
  9177. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9178. get: function () {
  9179. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9180. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9181. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9182. },
  9183. set: function (value) {
  9184. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9185. },
  9186. enumerable: true,
  9187. configurable: true
  9188. });
  9189. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9190. get: function () {
  9191. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9192. },
  9193. set: function (value) {
  9194. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9195. },
  9196. enumerable: true,
  9197. configurable: true
  9198. });
  9199. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9200. var defines = [];
  9201. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9202. defines.push("#define VSM");
  9203. }
  9204. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9205. var mesh = subMesh.getMesh();
  9206. var material = subMesh.getMaterial();
  9207. // Alpha test
  9208. if (material && material.needAlphaTesting()) {
  9209. defines.push("#define ALPHATEST");
  9210. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9211. attribs.push(BABYLON.VertexBuffer.UVKind);
  9212. defines.push("#define UV1");
  9213. }
  9214. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9215. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9216. defines.push("#define UV2");
  9217. }
  9218. }
  9219. // Bones
  9220. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9221. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9222. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9223. defines.push("#define BONES");
  9224. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9225. }
  9226. // Instances
  9227. if (useInstances) {
  9228. defines.push("#define INSTANCES");
  9229. attribs.push("world0");
  9230. attribs.push("world1");
  9231. attribs.push("world2");
  9232. attribs.push("world3");
  9233. }
  9234. // Get correct effect
  9235. var join = defines.join("\n");
  9236. if (this._cachedDefines !== join) {
  9237. this._cachedDefines = join;
  9238. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9239. }
  9240. return this._effect.isReady();
  9241. };
  9242. ShadowGenerator.prototype.getShadowMap = function () {
  9243. return this._shadowMap;
  9244. };
  9245. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9246. if (this._shadowMap2) {
  9247. return this._shadowMap2;
  9248. }
  9249. return this._shadowMap;
  9250. };
  9251. ShadowGenerator.prototype.getLight = function () {
  9252. return this._light;
  9253. };
  9254. // Methods
  9255. ShadowGenerator.prototype.getTransformMatrix = function () {
  9256. var scene = this._scene;
  9257. if (this._currentRenderID === scene.getRenderId()) {
  9258. return this._transformMatrix;
  9259. }
  9260. this._currentRenderID = scene.getRenderId();
  9261. var lightPosition = this._light.position;
  9262. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9263. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9264. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9265. }
  9266. if (this._light.computeTransformedPosition()) {
  9267. lightPosition = this._light.transformedPosition;
  9268. }
  9269. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9270. this._cachedPosition = lightPosition.clone();
  9271. this._cachedDirection = this._lightDirection.clone();
  9272. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9273. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9274. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9275. }
  9276. return this._transformMatrix;
  9277. };
  9278. ShadowGenerator.prototype.getDarkness = function () {
  9279. return this._darkness;
  9280. };
  9281. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9282. if (darkness >= 1.0)
  9283. this._darkness = 1.0;
  9284. else if (darkness <= 0.0)
  9285. this._darkness = 0.0;
  9286. else
  9287. this._darkness = darkness;
  9288. };
  9289. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9290. this._transparencyShadow = hasShadow;
  9291. };
  9292. ShadowGenerator.prototype._packHalf = function (depth) {
  9293. var scale = depth * 255.0;
  9294. var fract = scale - Math.floor(scale);
  9295. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9296. };
  9297. ShadowGenerator.prototype.dispose = function () {
  9298. this._shadowMap.dispose();
  9299. if (this._shadowMap2) {
  9300. this._shadowMap2.dispose();
  9301. }
  9302. if (this._downSamplePostprocess) {
  9303. this._downSamplePostprocess.dispose();
  9304. }
  9305. if (this._boxBlurPostprocess) {
  9306. this._boxBlurPostprocess.dispose();
  9307. }
  9308. };
  9309. ShadowGenerator._FILTER_NONE = 0;
  9310. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9311. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9312. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9313. return ShadowGenerator;
  9314. })();
  9315. BABYLON.ShadowGenerator = ShadowGenerator;
  9316. })(BABYLON || (BABYLON = {}));
  9317. var BABYLON;
  9318. (function (BABYLON) {
  9319. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9320. if (boxMin.x > sphereCenter.x + sphereRadius)
  9321. return false;
  9322. if (sphereCenter.x - sphereRadius > boxMax.x)
  9323. return false;
  9324. if (boxMin.y > sphereCenter.y + sphereRadius)
  9325. return false;
  9326. if (sphereCenter.y - sphereRadius > boxMax.y)
  9327. return false;
  9328. if (boxMin.z > sphereCenter.z + sphereRadius)
  9329. return false;
  9330. if (sphereCenter.z - sphereRadius > boxMax.z)
  9331. return false;
  9332. return true;
  9333. };
  9334. var getLowestRoot = function (a, b, c, maxR) {
  9335. var determinant = b * b - 4.0 * a * c;
  9336. var result = { root: 0, found: false };
  9337. if (determinant < 0)
  9338. return result;
  9339. var sqrtD = Math.sqrt(determinant);
  9340. var r1 = (-b - sqrtD) / (2.0 * a);
  9341. var r2 = (-b + sqrtD) / (2.0 * a);
  9342. if (r1 > r2) {
  9343. var temp = r2;
  9344. r2 = r1;
  9345. r1 = temp;
  9346. }
  9347. if (r1 > 0 && r1 < maxR) {
  9348. result.root = r1;
  9349. result.found = true;
  9350. return result;
  9351. }
  9352. if (r2 > 0 && r2 < maxR) {
  9353. result.root = r2;
  9354. result.found = true;
  9355. return result;
  9356. }
  9357. return result;
  9358. };
  9359. var Collider = (function () {
  9360. function Collider() {
  9361. this.radius = new BABYLON.Vector3(1, 1, 1);
  9362. this.retry = 0;
  9363. this.basePointWorld = BABYLON.Vector3.Zero();
  9364. this.velocityWorld = BABYLON.Vector3.Zero();
  9365. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9366. this._collisionPoint = BABYLON.Vector3.Zero();
  9367. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9368. this._tempVector = BABYLON.Vector3.Zero();
  9369. this._tempVector2 = BABYLON.Vector3.Zero();
  9370. this._tempVector3 = BABYLON.Vector3.Zero();
  9371. this._tempVector4 = BABYLON.Vector3.Zero();
  9372. this._edge = BABYLON.Vector3.Zero();
  9373. this._baseToVertex = BABYLON.Vector3.Zero();
  9374. this._destinationPoint = BABYLON.Vector3.Zero();
  9375. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9376. this._displacementVector = BABYLON.Vector3.Zero();
  9377. }
  9378. // Methods
  9379. Collider.prototype._initialize = function (source, dir, e) {
  9380. this.velocity = dir;
  9381. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9382. this.basePoint = source;
  9383. source.multiplyToRef(this.radius, this.basePointWorld);
  9384. dir.multiplyToRef(this.radius, this.velocityWorld);
  9385. this.velocityWorldLength = this.velocityWorld.length();
  9386. this.epsilon = e;
  9387. this.collisionFound = false;
  9388. };
  9389. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9390. pa.subtractToRef(point, this._tempVector);
  9391. pb.subtractToRef(point, this._tempVector2);
  9392. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9393. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9394. if (d < 0)
  9395. return false;
  9396. pc.subtractToRef(point, this._tempVector3);
  9397. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9398. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9399. if (d < 0)
  9400. return false;
  9401. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9402. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9403. return d >= 0;
  9404. };
  9405. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9406. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9407. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9408. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9409. return false;
  9410. }
  9411. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9412. return false;
  9413. return true;
  9414. };
  9415. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9416. var t0;
  9417. var embeddedInPlane = false;
  9418. //defensive programming, actually not needed.
  9419. if (!trianglePlaneArray) {
  9420. trianglePlaneArray = [];
  9421. }
  9422. if (!trianglePlaneArray[faceIndex]) {
  9423. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9424. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9425. }
  9426. var trianglePlane = trianglePlaneArray[faceIndex];
  9427. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9428. return;
  9429. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9430. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9431. if (normalDotVelocity == 0) {
  9432. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9433. return;
  9434. embeddedInPlane = true;
  9435. t0 = 0;
  9436. }
  9437. else {
  9438. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9439. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9440. if (t0 > t1) {
  9441. var temp = t1;
  9442. t1 = t0;
  9443. t0 = temp;
  9444. }
  9445. if (t0 > 1.0 || t1 < 0.0)
  9446. return;
  9447. if (t0 < 0)
  9448. t0 = 0;
  9449. if (t0 > 1.0)
  9450. t0 = 1.0;
  9451. }
  9452. this._collisionPoint.copyFromFloats(0, 0, 0);
  9453. var found = false;
  9454. var t = 1.0;
  9455. if (!embeddedInPlane) {
  9456. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9457. this.velocity.scaleToRef(t0, this._tempVector);
  9458. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9459. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9460. found = true;
  9461. t = t0;
  9462. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9463. }
  9464. }
  9465. if (!found) {
  9466. var velocitySquaredLength = this.velocity.lengthSquared();
  9467. var a = velocitySquaredLength;
  9468. this.basePoint.subtractToRef(p1, this._tempVector);
  9469. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9470. var c = this._tempVector.lengthSquared() - 1.0;
  9471. var lowestRoot = getLowestRoot(a, b, c, t);
  9472. if (lowestRoot.found) {
  9473. t = lowestRoot.root;
  9474. found = true;
  9475. this._collisionPoint.copyFrom(p1);
  9476. }
  9477. this.basePoint.subtractToRef(p2, this._tempVector);
  9478. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9479. c = this._tempVector.lengthSquared() - 1.0;
  9480. lowestRoot = getLowestRoot(a, b, c, t);
  9481. if (lowestRoot.found) {
  9482. t = lowestRoot.root;
  9483. found = true;
  9484. this._collisionPoint.copyFrom(p2);
  9485. }
  9486. this.basePoint.subtractToRef(p3, this._tempVector);
  9487. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9488. c = this._tempVector.lengthSquared() - 1.0;
  9489. lowestRoot = getLowestRoot(a, b, c, t);
  9490. if (lowestRoot.found) {
  9491. t = lowestRoot.root;
  9492. found = true;
  9493. this._collisionPoint.copyFrom(p3);
  9494. }
  9495. p2.subtractToRef(p1, this._edge);
  9496. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9497. var edgeSquaredLength = this._edge.lengthSquared();
  9498. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9499. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9500. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9501. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9502. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9503. lowestRoot = getLowestRoot(a, b, c, t);
  9504. if (lowestRoot.found) {
  9505. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9506. if (f >= 0.0 && f <= 1.0) {
  9507. t = lowestRoot.root;
  9508. found = true;
  9509. this._edge.scaleInPlace(f);
  9510. p1.addToRef(this._edge, this._collisionPoint);
  9511. }
  9512. }
  9513. p3.subtractToRef(p2, this._edge);
  9514. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9515. edgeSquaredLength = this._edge.lengthSquared();
  9516. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9517. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9518. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9519. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9520. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9521. lowestRoot = getLowestRoot(a, b, c, t);
  9522. if (lowestRoot.found) {
  9523. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9524. if (f >= 0.0 && f <= 1.0) {
  9525. t = lowestRoot.root;
  9526. found = true;
  9527. this._edge.scaleInPlace(f);
  9528. p2.addToRef(this._edge, this._collisionPoint);
  9529. }
  9530. }
  9531. p1.subtractToRef(p3, this._edge);
  9532. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9533. edgeSquaredLength = this._edge.lengthSquared();
  9534. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9535. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9536. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9537. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9538. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9539. lowestRoot = getLowestRoot(a, b, c, t);
  9540. if (lowestRoot.found) {
  9541. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9542. if (f >= 0.0 && f <= 1.0) {
  9543. t = lowestRoot.root;
  9544. found = true;
  9545. this._edge.scaleInPlace(f);
  9546. p3.addToRef(this._edge, this._collisionPoint);
  9547. }
  9548. }
  9549. }
  9550. if (found) {
  9551. var distToCollision = t * this.velocity.length();
  9552. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9553. if (!this.intersectionPoint) {
  9554. this.intersectionPoint = this._collisionPoint.clone();
  9555. }
  9556. else {
  9557. this.intersectionPoint.copyFrom(this._collisionPoint);
  9558. }
  9559. this.nearestDistance = distToCollision;
  9560. this.collisionFound = true;
  9561. }
  9562. }
  9563. };
  9564. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9565. for (var i = indexStart; i < indexEnd; i += 3) {
  9566. var p1 = pts[indices[i] - decal];
  9567. var p2 = pts[indices[i + 1] - decal];
  9568. var p3 = pts[indices[i + 2] - decal];
  9569. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9570. }
  9571. };
  9572. Collider.prototype._getResponse = function (pos, vel) {
  9573. pos.addToRef(vel, this._destinationPoint);
  9574. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9575. this.basePoint.addToRef(vel, pos);
  9576. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9577. this._slidePlaneNormal.normalize();
  9578. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9579. pos.addInPlace(this._displacementVector);
  9580. this.intersectionPoint.addInPlace(this._displacementVector);
  9581. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9582. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9583. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9584. };
  9585. return Collider;
  9586. })();
  9587. BABYLON.Collider = Collider;
  9588. })(BABYLON || (BABYLON = {}));
  9589. var BABYLON;
  9590. (function (BABYLON) {
  9591. //WebWorker code will be inserted to this variable.
  9592. BABYLON.CollisionWorker = "";
  9593. (function (WorkerTaskType) {
  9594. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9595. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9596. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9597. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9598. var WorkerTaskType = BABYLON.WorkerTaskType;
  9599. (function (WorkerReplyType) {
  9600. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9601. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9602. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9603. var WorkerReplyType = BABYLON.WorkerReplyType;
  9604. var CollisionCoordinatorWorker = (function () {
  9605. function CollisionCoordinatorWorker() {
  9606. var _this = this;
  9607. this._scaledPosition = BABYLON.Vector3.Zero();
  9608. this._scaledVelocity = BABYLON.Vector3.Zero();
  9609. this.onMeshUpdated = function (mesh) {
  9610. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9611. };
  9612. this.onGeometryUpdated = function (geometry) {
  9613. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9614. };
  9615. this._afterRender = function () {
  9616. if (!_this._init)
  9617. return;
  9618. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9619. return;
  9620. }
  9621. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9622. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9623. if (_this._runningUpdated > 4) {
  9624. return;
  9625. }
  9626. ++_this._runningUpdated;
  9627. var payload = {
  9628. updatedMeshes: _this._addUpdateMeshesList,
  9629. updatedGeometries: _this._addUpdateGeometriesList,
  9630. removedGeometries: _this._toRemoveGeometryArray,
  9631. removedMeshes: _this._toRemoveMeshesArray
  9632. };
  9633. var message = {
  9634. payload: payload,
  9635. taskType: WorkerTaskType.UPDATE
  9636. };
  9637. var serializable = [];
  9638. for (var id in payload.updatedGeometries) {
  9639. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9640. //prepare transferables
  9641. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9642. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9643. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9644. }
  9645. }
  9646. _this._worker.postMessage(message, serializable);
  9647. _this._addUpdateMeshesList = {};
  9648. _this._addUpdateGeometriesList = {};
  9649. _this._toRemoveGeometryArray = [];
  9650. _this._toRemoveMeshesArray = [];
  9651. };
  9652. this._onMessageFromWorker = function (e) {
  9653. var returnData = e.data;
  9654. if (returnData.error != WorkerReplyType.SUCCESS) {
  9655. //TODO what errors can be returned from the worker?
  9656. BABYLON.Tools.Warn("error returned from worker!");
  9657. return;
  9658. }
  9659. switch (returnData.taskType) {
  9660. case WorkerTaskType.INIT:
  9661. _this._init = true;
  9662. //Update the worked with ALL of the scene's current state
  9663. _this._scene.meshes.forEach(function (mesh) {
  9664. _this.onMeshAdded(mesh);
  9665. });
  9666. _this._scene.getGeometries().forEach(function (geometry) {
  9667. _this.onGeometryAdded(geometry);
  9668. });
  9669. break;
  9670. case WorkerTaskType.UPDATE:
  9671. _this._runningUpdated--;
  9672. break;
  9673. case WorkerTaskType.COLLIDE:
  9674. _this._runningCollisionTask = false;
  9675. var returnPayload = returnData.payload;
  9676. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9677. return;
  9678. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9679. //cleanup
  9680. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9681. break;
  9682. }
  9683. };
  9684. this._collisionsCallbackArray = [];
  9685. this._init = false;
  9686. this._runningUpdated = 0;
  9687. this._runningCollisionTask = false;
  9688. this._addUpdateMeshesList = {};
  9689. this._addUpdateGeometriesList = {};
  9690. this._toRemoveGeometryArray = [];
  9691. this._toRemoveMeshesArray = [];
  9692. }
  9693. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9694. if (!this._init)
  9695. return;
  9696. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9697. return;
  9698. position.divideToRef(collider.radius, this._scaledPosition);
  9699. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9700. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9701. var payload = {
  9702. collider: {
  9703. position: this._scaledPosition.asArray(),
  9704. velocity: this._scaledVelocity.asArray(),
  9705. radius: collider.radius.asArray()
  9706. },
  9707. collisionId: collisionIndex,
  9708. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9709. maximumRetry: maximumRetry
  9710. };
  9711. var message = {
  9712. payload: payload,
  9713. taskType: WorkerTaskType.COLLIDE
  9714. };
  9715. this._worker.postMessage(message);
  9716. };
  9717. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9718. this._scene = scene;
  9719. this._scene.registerAfterRender(this._afterRender);
  9720. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9721. this._worker = new Worker(workerUrl);
  9722. this._worker.onmessage = this._onMessageFromWorker;
  9723. var message = {
  9724. payload: {},
  9725. taskType: WorkerTaskType.INIT
  9726. };
  9727. this._worker.postMessage(message);
  9728. };
  9729. CollisionCoordinatorWorker.prototype.destroy = function () {
  9730. this._scene.unregisterAfterRender(this._afterRender);
  9731. this._worker.terminate();
  9732. };
  9733. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9734. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9735. this.onMeshUpdated(mesh);
  9736. };
  9737. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9738. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9739. };
  9740. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9741. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9742. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9743. this.onGeometryUpdated(geometry);
  9744. };
  9745. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9746. this._toRemoveGeometryArray.push(geometry.id);
  9747. };
  9748. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9749. var submeshes = [];
  9750. if (mesh.subMeshes) {
  9751. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9752. return {
  9753. position: idx,
  9754. verticesStart: sm.verticesStart,
  9755. verticesCount: sm.verticesCount,
  9756. indexStart: sm.indexStart,
  9757. indexCount: sm.indexCount,
  9758. hasMaterial: !!sm.getMaterial(),
  9759. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9760. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9761. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9762. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9763. };
  9764. });
  9765. }
  9766. var geometryId = null;
  9767. if (mesh instanceof BABYLON.Mesh) {
  9768. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9769. }
  9770. else if (mesh instanceof BABYLON.InstancedMesh) {
  9771. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9772. }
  9773. return {
  9774. uniqueId: mesh.uniqueId,
  9775. id: mesh.id,
  9776. name: mesh.name,
  9777. geometryId: geometryId,
  9778. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9779. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9780. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9781. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9782. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9783. subMeshes: submeshes,
  9784. checkCollisions: mesh.checkCollisions
  9785. };
  9786. };
  9787. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9788. return {
  9789. id: geometry.id,
  9790. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9791. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9792. indices: new Int32Array(geometry.getIndices() || []),
  9793. };
  9794. };
  9795. return CollisionCoordinatorWorker;
  9796. })();
  9797. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9798. var CollisionCoordinatorLegacy = (function () {
  9799. function CollisionCoordinatorLegacy() {
  9800. this._scaledPosition = BABYLON.Vector3.Zero();
  9801. this._scaledVelocity = BABYLON.Vector3.Zero();
  9802. this._finalPosition = BABYLON.Vector3.Zero();
  9803. }
  9804. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9805. position.divideToRef(collider.radius, this._scaledPosition);
  9806. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9807. collider.collidedMesh = null;
  9808. collider.retry = 0;
  9809. collider.initialVelocity = this._scaledVelocity;
  9810. collider.initialPosition = this._scaledPosition;
  9811. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9812. this._finalPosition.multiplyInPlace(collider.radius);
  9813. //run the callback
  9814. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9815. };
  9816. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9817. this._scene = scene;
  9818. };
  9819. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9820. //Legacy need no destruction method.
  9821. };
  9822. //No update in legacy mode
  9823. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9824. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9825. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9826. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9827. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9828. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9829. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9830. if (excludedMesh === void 0) { excludedMesh = null; }
  9831. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9832. if (collider.retry >= maximumRetry) {
  9833. finalPosition.copyFrom(position);
  9834. return;
  9835. }
  9836. collider._initialize(position, velocity, closeDistance);
  9837. // Check all meshes
  9838. for (var index = 0; index < this._scene.meshes.length; index++) {
  9839. var mesh = this._scene.meshes[index];
  9840. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9841. mesh._checkCollision(collider);
  9842. }
  9843. }
  9844. if (!collider.collisionFound) {
  9845. position.addToRef(velocity, finalPosition);
  9846. return;
  9847. }
  9848. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9849. collider._getResponse(position, velocity);
  9850. }
  9851. if (velocity.length() <= closeDistance) {
  9852. finalPosition.copyFrom(position);
  9853. return;
  9854. }
  9855. collider.retry++;
  9856. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9857. };
  9858. return CollisionCoordinatorLegacy;
  9859. })();
  9860. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9861. })(BABYLON || (BABYLON = {}));
  9862. var BABYLON;
  9863. (function (BABYLON) {
  9864. var VRCameraMetrics = (function () {
  9865. function VRCameraMetrics() {
  9866. this.compensateDistortion = true;
  9867. }
  9868. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9869. get: function () {
  9870. return this.hResolution / (2 * this.vResolution);
  9871. },
  9872. enumerable: true,
  9873. configurable: true
  9874. });
  9875. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9876. get: function () {
  9877. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9878. },
  9879. enumerable: true,
  9880. configurable: true
  9881. });
  9882. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9883. get: function () {
  9884. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9885. var h = (4 * meters) / this.hScreenSize;
  9886. return BABYLON.Matrix.Translation(h, 0, 0);
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9892. get: function () {
  9893. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9894. var h = (4 * meters) / this.hScreenSize;
  9895. return BABYLON.Matrix.Translation(-h, 0, 0);
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9901. get: function () {
  9902. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9903. },
  9904. enumerable: true,
  9905. configurable: true
  9906. });
  9907. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9908. get: function () {
  9909. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9910. },
  9911. enumerable: true,
  9912. configurable: true
  9913. });
  9914. VRCameraMetrics.GetDefault = function () {
  9915. var result = new VRCameraMetrics();
  9916. result.hResolution = 1280;
  9917. result.vResolution = 800;
  9918. result.hScreenSize = 0.149759993;
  9919. result.vScreenSize = 0.0935999975;
  9920. result.vScreenCenter = 0.0467999987,
  9921. result.eyeToScreenDistance = 0.0410000011;
  9922. result.lensSeparationDistance = 0.0635000020;
  9923. result.interpupillaryDistance = 0.0640000030;
  9924. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9925. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9926. result.postProcessScaleFactor = 1.714605507808412;
  9927. result.lensCenterOffset = 0.151976421;
  9928. return result;
  9929. };
  9930. return VRCameraMetrics;
  9931. })();
  9932. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9933. var Camera = (function (_super) {
  9934. __extends(Camera, _super);
  9935. function Camera(name, position, scene) {
  9936. _super.call(this, name, scene);
  9937. this.position = position;
  9938. // Members
  9939. this.upVector = BABYLON.Vector3.Up();
  9940. this.orthoLeft = null;
  9941. this.orthoRight = null;
  9942. this.orthoBottom = null;
  9943. this.orthoTop = null;
  9944. this.fov = 0.8;
  9945. this.minZ = 1.0;
  9946. this.maxZ = 10000.0;
  9947. this.inertia = 0.9;
  9948. this.mode = Camera.PERSPECTIVE_CAMERA;
  9949. this.isIntermediate = false;
  9950. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9951. this.layerMask = 0x0FFFFFFF;
  9952. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9953. // Camera rig members
  9954. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9955. this._rigCameras = new Array();
  9956. // Cache
  9957. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9958. this._projectionMatrix = new BABYLON.Matrix();
  9959. this._postProcesses = new Array();
  9960. this._postProcessesTakenIndices = [];
  9961. this._activeMeshes = new BABYLON.SmartArray(256);
  9962. this._globalPosition = BABYLON.Vector3.Zero();
  9963. scene.addCamera(this);
  9964. if (!scene.activeCamera) {
  9965. scene.activeCamera = this;
  9966. }
  9967. }
  9968. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9969. get: function () {
  9970. return Camera._PERSPECTIVE_CAMERA;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9976. get: function () {
  9977. return Camera._ORTHOGRAPHIC_CAMERA;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9983. get: function () {
  9984. return Camera._FOVMODE_VERTICAL_FIXED;
  9985. },
  9986. enumerable: true,
  9987. configurable: true
  9988. });
  9989. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9990. get: function () {
  9991. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9997. get: function () {
  9998. return Camera._RIG_MODE_NONE;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10004. get: function () {
  10005. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10011. get: function () {
  10012. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10013. },
  10014. enumerable: true,
  10015. configurable: true
  10016. });
  10017. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10018. get: function () {
  10019. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10025. get: function () {
  10026. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10027. },
  10028. enumerable: true,
  10029. configurable: true
  10030. });
  10031. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10032. get: function () {
  10033. return Camera._RIG_MODE_VR;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. Object.defineProperty(Camera.prototype, "globalPosition", {
  10039. get: function () {
  10040. return this._globalPosition;
  10041. },
  10042. enumerable: true,
  10043. configurable: true
  10044. });
  10045. Camera.prototype.getActiveMeshes = function () {
  10046. return this._activeMeshes;
  10047. };
  10048. Camera.prototype.isActiveMesh = function (mesh) {
  10049. return (this._activeMeshes.indexOf(mesh) !== -1);
  10050. };
  10051. //Cache
  10052. Camera.prototype._initCache = function () {
  10053. _super.prototype._initCache.call(this);
  10054. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10055. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10056. this._cache.mode = undefined;
  10057. this._cache.minZ = undefined;
  10058. this._cache.maxZ = undefined;
  10059. this._cache.fov = undefined;
  10060. this._cache.aspectRatio = undefined;
  10061. this._cache.orthoLeft = undefined;
  10062. this._cache.orthoRight = undefined;
  10063. this._cache.orthoBottom = undefined;
  10064. this._cache.orthoTop = undefined;
  10065. this._cache.renderWidth = undefined;
  10066. this._cache.renderHeight = undefined;
  10067. };
  10068. Camera.prototype._updateCache = function (ignoreParentClass) {
  10069. if (!ignoreParentClass) {
  10070. _super.prototype._updateCache.call(this);
  10071. }
  10072. var engine = this.getEngine();
  10073. this._cache.position.copyFrom(this.position);
  10074. this._cache.upVector.copyFrom(this.upVector);
  10075. this._cache.mode = this.mode;
  10076. this._cache.minZ = this.minZ;
  10077. this._cache.maxZ = this.maxZ;
  10078. this._cache.fov = this.fov;
  10079. this._cache.aspectRatio = engine.getAspectRatio(this);
  10080. this._cache.orthoLeft = this.orthoLeft;
  10081. this._cache.orthoRight = this.orthoRight;
  10082. this._cache.orthoBottom = this.orthoBottom;
  10083. this._cache.orthoTop = this.orthoTop;
  10084. this._cache.renderWidth = engine.getRenderWidth();
  10085. this._cache.renderHeight = engine.getRenderHeight();
  10086. };
  10087. Camera.prototype._updateFromScene = function () {
  10088. this.updateCache();
  10089. this._update();
  10090. };
  10091. // Synchronized
  10092. Camera.prototype._isSynchronized = function () {
  10093. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10094. };
  10095. Camera.prototype._isSynchronizedViewMatrix = function () {
  10096. if (!_super.prototype._isSynchronized.call(this))
  10097. return false;
  10098. return this._cache.position.equals(this.position)
  10099. && this._cache.upVector.equals(this.upVector)
  10100. && this.isSynchronizedWithParent();
  10101. };
  10102. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10103. var check = this._cache.mode === this.mode
  10104. && this._cache.minZ === this.minZ
  10105. && this._cache.maxZ === this.maxZ;
  10106. if (!check) {
  10107. return false;
  10108. }
  10109. var engine = this.getEngine();
  10110. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10111. check = this._cache.fov === this.fov
  10112. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10113. }
  10114. else {
  10115. check = this._cache.orthoLeft === this.orthoLeft
  10116. && this._cache.orthoRight === this.orthoRight
  10117. && this._cache.orthoBottom === this.orthoBottom
  10118. && this._cache.orthoTop === this.orthoTop
  10119. && this._cache.renderWidth === engine.getRenderWidth()
  10120. && this._cache.renderHeight === engine.getRenderHeight();
  10121. }
  10122. return check;
  10123. };
  10124. // Controls
  10125. Camera.prototype.attachControl = function (element) {
  10126. };
  10127. Camera.prototype.detachControl = function (element) {
  10128. };
  10129. Camera.prototype._update = function () {
  10130. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10131. this._updateRigCameras();
  10132. }
  10133. this._checkInputs();
  10134. };
  10135. Camera.prototype._checkInputs = function () {
  10136. };
  10137. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10138. if (insertAt === void 0) { insertAt = null; }
  10139. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10140. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10141. return 0;
  10142. }
  10143. if (insertAt == null || insertAt < 0) {
  10144. this._postProcesses.push(postProcess);
  10145. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10146. return this._postProcesses.length - 1;
  10147. }
  10148. var add = 0;
  10149. var i;
  10150. var start;
  10151. if (this._postProcesses[insertAt]) {
  10152. start = this._postProcesses.length - 1;
  10153. for (i = start; i >= insertAt + 1; --i) {
  10154. this._postProcesses[i + 1] = this._postProcesses[i];
  10155. }
  10156. add = 1;
  10157. }
  10158. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10159. if (this._postProcessesTakenIndices[i] < insertAt) {
  10160. continue;
  10161. }
  10162. start = this._postProcessesTakenIndices.length - 1;
  10163. for (var j = start; j >= i; --j) {
  10164. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10165. }
  10166. this._postProcessesTakenIndices[i] = insertAt;
  10167. break;
  10168. }
  10169. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10170. this._postProcessesTakenIndices.push(insertAt);
  10171. }
  10172. var result = insertAt + add;
  10173. this._postProcesses[result] = postProcess;
  10174. return result;
  10175. };
  10176. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10177. if (atIndices === void 0) { atIndices = null; }
  10178. var result = [];
  10179. var i;
  10180. var index;
  10181. if (!atIndices) {
  10182. var length = this._postProcesses.length;
  10183. for (i = 0; i < length; i++) {
  10184. if (this._postProcesses[i] !== postProcess) {
  10185. continue;
  10186. }
  10187. delete this._postProcesses[i];
  10188. index = this._postProcessesTakenIndices.indexOf(i);
  10189. this._postProcessesTakenIndices.splice(index, 1);
  10190. }
  10191. }
  10192. else {
  10193. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10194. for (i = 0; i < atIndices.length; i++) {
  10195. var foundPostProcess = this._postProcesses[atIndices[i]];
  10196. if (foundPostProcess !== postProcess) {
  10197. result.push(i);
  10198. continue;
  10199. }
  10200. delete this._postProcesses[atIndices[i]];
  10201. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10202. this._postProcessesTakenIndices.splice(index, 1);
  10203. }
  10204. }
  10205. return result;
  10206. };
  10207. Camera.prototype.getWorldMatrix = function () {
  10208. if (!this._worldMatrix) {
  10209. this._worldMatrix = BABYLON.Matrix.Identity();
  10210. }
  10211. var viewMatrix = this.getViewMatrix();
  10212. viewMatrix.invertToRef(this._worldMatrix);
  10213. return this._worldMatrix;
  10214. };
  10215. Camera.prototype._getViewMatrix = function () {
  10216. return BABYLON.Matrix.Identity();
  10217. };
  10218. Camera.prototype.getViewMatrix = function (force) {
  10219. this._computedViewMatrix = this._computeViewMatrix(force);
  10220. if (!force && this._isSynchronizedViewMatrix()) {
  10221. return this._computedViewMatrix;
  10222. }
  10223. if (!this.parent || !this.parent.getWorldMatrix) {
  10224. this._globalPosition.copyFrom(this.position);
  10225. }
  10226. else {
  10227. if (!this._worldMatrix) {
  10228. this._worldMatrix = BABYLON.Matrix.Identity();
  10229. }
  10230. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10231. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10232. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10233. this._computedViewMatrix.invert();
  10234. this._markSyncedWithParent();
  10235. }
  10236. this._currentRenderId = this.getScene().getRenderId();
  10237. return this._computedViewMatrix;
  10238. };
  10239. Camera.prototype._computeViewMatrix = function (force) {
  10240. if (!force && this._isSynchronizedViewMatrix()) {
  10241. return this._computedViewMatrix;
  10242. }
  10243. this._computedViewMatrix = this._getViewMatrix();
  10244. this._currentRenderId = this.getScene().getRenderId();
  10245. return this._computedViewMatrix;
  10246. };
  10247. Camera.prototype.getProjectionMatrix = function (force) {
  10248. if (!force && this._isSynchronizedProjectionMatrix()) {
  10249. return this._projectionMatrix;
  10250. }
  10251. var engine = this.getEngine();
  10252. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10253. if (this.minZ <= 0) {
  10254. this.minZ = 0.1;
  10255. }
  10256. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10257. return this._projectionMatrix;
  10258. }
  10259. var halfWidth = engine.getRenderWidth() / 2.0;
  10260. var halfHeight = engine.getRenderHeight() / 2.0;
  10261. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10262. return this._projectionMatrix;
  10263. };
  10264. Camera.prototype.dispose = function () {
  10265. // Remove from scene
  10266. this.getScene().removeCamera(this);
  10267. while (this._rigCameras.length > 0) {
  10268. this._rigCameras.pop().dispose();
  10269. }
  10270. // Postprocesses
  10271. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10272. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10273. }
  10274. };
  10275. // ---- Camera rigs section ----
  10276. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10277. while (this._rigCameras.length > 0) {
  10278. this._rigCameras.pop().dispose();
  10279. }
  10280. this.cameraRigMode = mode;
  10281. this._cameraRigParams = {};
  10282. switch (this.cameraRigMode) {
  10283. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10284. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10285. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10286. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10287. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10288. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10289. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10290. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10291. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10292. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10293. break;
  10294. }
  10295. var postProcesses = new Array();
  10296. switch (this.cameraRigMode) {
  10297. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10298. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10299. this._rigCameras[0].isIntermediate = true;
  10300. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10301. postProcesses[1].onApply = function (effect) {
  10302. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10303. };
  10304. break;
  10305. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10306. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10307. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10308. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10309. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10310. var secondCamIndex = 1 - firstCamIndex;
  10311. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10312. this._rigCameras[firstCamIndex].isIntermediate = true;
  10313. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10314. break;
  10315. case Camera.RIG_MODE_VR:
  10316. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10317. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10318. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10319. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10320. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10321. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10322. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10323. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10324. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10325. if (metrics.compensateDistortion) {
  10326. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10327. }
  10328. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10329. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10330. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10331. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10332. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10333. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10334. if (metrics.compensateDistortion) {
  10335. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10336. }
  10337. break;
  10338. }
  10339. this._update();
  10340. };
  10341. Camera.prototype._getVRProjectionMatrix = function () {
  10342. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10343. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10344. return this._projectionMatrix;
  10345. };
  10346. Camera.prototype.setCameraRigParameter = function (name, value) {
  10347. this._cameraRigParams[name] = value;
  10348. //provisionnally:
  10349. if (name === "interaxialDistance") {
  10350. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10351. }
  10352. };
  10353. /**
  10354. * May needs to be overridden by children so sub has required properties to be copied
  10355. */
  10356. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10357. return null;
  10358. };
  10359. /**
  10360. * May needs to be overridden by children
  10361. */
  10362. Camera.prototype._updateRigCameras = function () {
  10363. for (var i = 0; i < this._rigCameras.length; i++) {
  10364. this._rigCameras[i].minZ = this.minZ;
  10365. this._rigCameras[i].maxZ = this.maxZ;
  10366. this._rigCameras[i].fov = this.fov;
  10367. }
  10368. // only update viewport when ANAGLYPH
  10369. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10370. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10371. }
  10372. };
  10373. // Statics
  10374. Camera._PERSPECTIVE_CAMERA = 0;
  10375. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10376. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10377. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10378. Camera._RIG_MODE_NONE = 0;
  10379. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10380. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10381. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10382. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10383. Camera._RIG_MODE_VR = 20;
  10384. return Camera;
  10385. })(BABYLON.Node);
  10386. BABYLON.Camera = Camera;
  10387. })(BABYLON || (BABYLON = {}));
  10388. var BABYLON;
  10389. (function (BABYLON) {
  10390. var TargetCamera = (function (_super) {
  10391. __extends(TargetCamera, _super);
  10392. function TargetCamera(name, position, scene) {
  10393. _super.call(this, name, position, scene);
  10394. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10395. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10396. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10397. this.speed = 2.0;
  10398. this.noRotationConstraint = false;
  10399. this.lockedTarget = null;
  10400. this._currentTarget = BABYLON.Vector3.Zero();
  10401. this._viewMatrix = BABYLON.Matrix.Zero();
  10402. this._camMatrix = BABYLON.Matrix.Zero();
  10403. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10404. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10405. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10406. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10407. this._lookAtTemp = BABYLON.Matrix.Zero();
  10408. this._tempMatrix = BABYLON.Matrix.Zero();
  10409. }
  10410. TargetCamera.prototype.getFrontPosition = function (distance) {
  10411. var direction = this.getTarget().subtract(this.position);
  10412. direction.normalize();
  10413. direction.scaleInPlace(distance);
  10414. return this.globalPosition.add(direction);
  10415. };
  10416. TargetCamera.prototype._getLockedTargetPosition = function () {
  10417. if (!this.lockedTarget) {
  10418. return null;
  10419. }
  10420. return this.lockedTarget.position || this.lockedTarget;
  10421. };
  10422. // Cache
  10423. TargetCamera.prototype._initCache = function () {
  10424. _super.prototype._initCache.call(this);
  10425. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10426. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10427. };
  10428. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10429. if (!ignoreParentClass) {
  10430. _super.prototype._updateCache.call(this);
  10431. }
  10432. var lockedTargetPosition = this._getLockedTargetPosition();
  10433. if (!lockedTargetPosition) {
  10434. this._cache.lockedTarget = null;
  10435. }
  10436. else {
  10437. if (!this._cache.lockedTarget) {
  10438. this._cache.lockedTarget = lockedTargetPosition.clone();
  10439. }
  10440. else {
  10441. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10442. }
  10443. }
  10444. this._cache.rotation.copyFrom(this.rotation);
  10445. };
  10446. // Synchronized
  10447. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10448. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10449. return false;
  10450. }
  10451. var lockedTargetPosition = this._getLockedTargetPosition();
  10452. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10453. && this._cache.rotation.equals(this.rotation);
  10454. };
  10455. // Methods
  10456. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10457. var engine = this.getEngine();
  10458. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10459. };
  10460. // Target
  10461. TargetCamera.prototype.setTarget = function (target) {
  10462. this.upVector.normalize();
  10463. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10464. this._camMatrix.invert();
  10465. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10466. var vDir = target.subtract(this.position);
  10467. if (vDir.x >= 0.0) {
  10468. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10469. }
  10470. else {
  10471. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10472. }
  10473. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10474. if (isNaN(this.rotation.x)) {
  10475. this.rotation.x = 0;
  10476. }
  10477. if (isNaN(this.rotation.y)) {
  10478. this.rotation.y = 0;
  10479. }
  10480. if (isNaN(this.rotation.z)) {
  10481. this.rotation.z = 0;
  10482. }
  10483. };
  10484. TargetCamera.prototype.getTarget = function () {
  10485. return this._currentTarget;
  10486. };
  10487. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10488. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10489. };
  10490. TargetCamera.prototype._updatePosition = function () {
  10491. this.position.addInPlace(this.cameraDirection);
  10492. };
  10493. TargetCamera.prototype._checkInputs = function () {
  10494. var needToMove = this._decideIfNeedsToMove();
  10495. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10496. // Move
  10497. if (needToMove) {
  10498. this._updatePosition();
  10499. }
  10500. // Rotate
  10501. if (needToRotate) {
  10502. this.rotation.x += this.cameraRotation.x;
  10503. this.rotation.y += this.cameraRotation.y;
  10504. if (!this.noRotationConstraint) {
  10505. var limit = (Math.PI / 2) * 0.95;
  10506. if (this.rotation.x > limit)
  10507. this.rotation.x = limit;
  10508. if (this.rotation.x < -limit)
  10509. this.rotation.x = -limit;
  10510. }
  10511. }
  10512. // Inertia
  10513. if (needToMove) {
  10514. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10515. this.cameraDirection.x = 0;
  10516. }
  10517. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10518. this.cameraDirection.y = 0;
  10519. }
  10520. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10521. this.cameraDirection.z = 0;
  10522. }
  10523. this.cameraDirection.scaleInPlace(this.inertia);
  10524. }
  10525. if (needToRotate) {
  10526. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10527. this.cameraRotation.x = 0;
  10528. }
  10529. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10530. this.cameraRotation.y = 0;
  10531. }
  10532. this.cameraRotation.scaleInPlace(this.inertia);
  10533. }
  10534. _super.prototype._checkInputs.call(this);
  10535. };
  10536. TargetCamera.prototype._getViewMatrix = function () {
  10537. if (!this.lockedTarget) {
  10538. // Compute
  10539. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10540. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10541. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10542. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10543. this._lookAtTemp.invert();
  10544. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10545. }
  10546. else {
  10547. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10548. }
  10549. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10550. // Computing target and final matrix
  10551. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10552. }
  10553. else {
  10554. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10555. }
  10556. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10557. return this._viewMatrix;
  10558. };
  10559. TargetCamera.prototype._getVRViewMatrix = function () {
  10560. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10561. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10562. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10563. // Computing target and final matrix
  10564. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10565. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10566. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10567. return this._viewMatrix;
  10568. };
  10569. /**
  10570. * @override
  10571. * Override Camera.createRigCamera
  10572. */
  10573. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10574. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10575. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10576. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10577. rigCamera._cameraRigParams = {};
  10578. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10579. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10580. }
  10581. return rigCamera;
  10582. }
  10583. return null;
  10584. };
  10585. /**
  10586. * @override
  10587. * Override Camera._updateRigCameras
  10588. */
  10589. TargetCamera.prototype._updateRigCameras = function () {
  10590. switch (this.cameraRigMode) {
  10591. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10592. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10593. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10594. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10595. case BABYLON.Camera.RIG_MODE_VR:
  10596. var camLeft = this._rigCameras[0];
  10597. var camRight = this._rigCameras[1];
  10598. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10599. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10600. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10601. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10602. camLeft.position.copyFrom(this.position);
  10603. camRight.position.copyFrom(this.position);
  10604. }
  10605. else {
  10606. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10607. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10608. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10609. camLeft.setTarget(this.getTarget());
  10610. camRight.setTarget(this.getTarget());
  10611. }
  10612. break;
  10613. }
  10614. _super.prototype._updateRigCameras.call(this);
  10615. };
  10616. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10617. if (!this._rigCamTransformMatrix) {
  10618. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10619. }
  10620. var target = this.getTarget();
  10621. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10622. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10623. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10624. };
  10625. return TargetCamera;
  10626. })(BABYLON.Camera);
  10627. BABYLON.TargetCamera = TargetCamera;
  10628. })(BABYLON || (BABYLON = {}));
  10629. var BABYLON;
  10630. (function (BABYLON) {
  10631. var FreeCamera = (function (_super) {
  10632. __extends(FreeCamera, _super);
  10633. function FreeCamera(name, position, scene) {
  10634. var _this = this;
  10635. _super.call(this, name, position, scene);
  10636. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10637. this.keysUp = [38];
  10638. this.keysDown = [40];
  10639. this.keysLeft = [37];
  10640. this.keysRight = [39];
  10641. this.checkCollisions = false;
  10642. this.applyGravity = false;
  10643. this.angularSensibility = 2000.0;
  10644. this._keys = [];
  10645. this._collider = new BABYLON.Collider();
  10646. this._needMoveForGravity = false;
  10647. this._oldPosition = BABYLON.Vector3.Zero();
  10648. this._diffPosition = BABYLON.Vector3.Zero();
  10649. this._newPosition = BABYLON.Vector3.Zero();
  10650. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10651. if (collidedMesh === void 0) { collidedMesh = null; }
  10652. //TODO move this to the collision coordinator!
  10653. if (_this.getScene().workerCollisions)
  10654. newPosition.multiplyInPlace(_this._collider.radius);
  10655. var updatePosition = function (newPos) {
  10656. _this._newPosition.copyFrom(newPos);
  10657. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10658. var oldPosition = _this.position.clone();
  10659. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10660. _this.position.addInPlace(_this._diffPosition);
  10661. if (_this.onCollide && collidedMesh) {
  10662. _this.onCollide(collidedMesh);
  10663. }
  10664. }
  10665. };
  10666. updatePosition(newPosition);
  10667. };
  10668. }
  10669. // Controls
  10670. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10671. var _this = this;
  10672. var previousPosition;
  10673. var engine = this.getEngine();
  10674. if (this._attachedElement) {
  10675. return;
  10676. }
  10677. this._attachedElement = element;
  10678. if (this._onMouseDown === undefined) {
  10679. this._onMouseDown = function (evt) {
  10680. previousPosition = {
  10681. x: evt.clientX,
  10682. y: evt.clientY
  10683. };
  10684. if (!noPreventDefault) {
  10685. evt.preventDefault();
  10686. }
  10687. };
  10688. this._onMouseUp = function (evt) {
  10689. previousPosition = null;
  10690. if (!noPreventDefault) {
  10691. evt.preventDefault();
  10692. }
  10693. };
  10694. this._onMouseOut = function (evt) {
  10695. previousPosition = null;
  10696. _this._keys = [];
  10697. if (!noPreventDefault) {
  10698. evt.preventDefault();
  10699. }
  10700. };
  10701. this._onMouseMove = function (evt) {
  10702. if (!previousPosition && !engine.isPointerLock) {
  10703. return;
  10704. }
  10705. var offsetX;
  10706. var offsetY;
  10707. if (!engine.isPointerLock) {
  10708. offsetX = evt.clientX - previousPosition.x;
  10709. offsetY = evt.clientY - previousPosition.y;
  10710. }
  10711. else {
  10712. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10713. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10714. }
  10715. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10716. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10717. previousPosition = {
  10718. x: evt.clientX,
  10719. y: evt.clientY
  10720. };
  10721. if (!noPreventDefault) {
  10722. evt.preventDefault();
  10723. }
  10724. };
  10725. this._onKeyDown = function (evt) {
  10726. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10727. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10728. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10729. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10730. var index = _this._keys.indexOf(evt.keyCode);
  10731. if (index === -1) {
  10732. _this._keys.push(evt.keyCode);
  10733. }
  10734. if (!noPreventDefault) {
  10735. evt.preventDefault();
  10736. }
  10737. }
  10738. };
  10739. this._onKeyUp = function (evt) {
  10740. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10741. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10742. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10743. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10744. var index = _this._keys.indexOf(evt.keyCode);
  10745. if (index >= 0) {
  10746. _this._keys.splice(index, 1);
  10747. }
  10748. if (!noPreventDefault) {
  10749. evt.preventDefault();
  10750. }
  10751. }
  10752. };
  10753. this._onLostFocus = function () {
  10754. _this._keys = [];
  10755. };
  10756. this._reset = function () {
  10757. _this._keys = [];
  10758. previousPosition = null;
  10759. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10760. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10761. };
  10762. }
  10763. element.addEventListener("mousedown", this._onMouseDown, false);
  10764. element.addEventListener("mouseup", this._onMouseUp, false);
  10765. element.addEventListener("mouseout", this._onMouseOut, false);
  10766. element.addEventListener("mousemove", this._onMouseMove, false);
  10767. BABYLON.Tools.RegisterTopRootEvents([
  10768. { name: "keydown", handler: this._onKeyDown },
  10769. { name: "keyup", handler: this._onKeyUp },
  10770. { name: "blur", handler: this._onLostFocus }
  10771. ]);
  10772. };
  10773. FreeCamera.prototype.detachControl = function (element) {
  10774. if (this._attachedElement != element) {
  10775. return;
  10776. }
  10777. element.removeEventListener("mousedown", this._onMouseDown);
  10778. element.removeEventListener("mouseup", this._onMouseUp);
  10779. element.removeEventListener("mouseout", this._onMouseOut);
  10780. element.removeEventListener("mousemove", this._onMouseMove);
  10781. BABYLON.Tools.UnregisterTopRootEvents([
  10782. { name: "keydown", handler: this._onKeyDown },
  10783. { name: "keyup", handler: this._onKeyUp },
  10784. { name: "blur", handler: this._onLostFocus }
  10785. ]);
  10786. this._attachedElement = null;
  10787. if (this._reset) {
  10788. this._reset();
  10789. }
  10790. };
  10791. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10792. var globalPosition;
  10793. if (this.parent) {
  10794. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10795. }
  10796. else {
  10797. globalPosition = this.position;
  10798. }
  10799. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10800. this._collider.radius = this.ellipsoid;
  10801. //no need for clone, as long as gravity is not on.
  10802. var actualVelocity = velocity;
  10803. //add gravity to the velocity to prevent the dual-collision checking
  10804. if (this.applyGravity) {
  10805. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10806. actualVelocity = velocity.add(this.getScene().gravity);
  10807. }
  10808. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10809. };
  10810. FreeCamera.prototype._checkInputs = function () {
  10811. if (!this._localDirection) {
  10812. this._localDirection = BABYLON.Vector3.Zero();
  10813. this._transformedDirection = BABYLON.Vector3.Zero();
  10814. }
  10815. // Keyboard
  10816. for (var index = 0; index < this._keys.length; index++) {
  10817. var keyCode = this._keys[index];
  10818. var speed = this._computeLocalCameraSpeed();
  10819. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10820. this._localDirection.copyFromFloats(-speed, 0, 0);
  10821. }
  10822. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10823. this._localDirection.copyFromFloats(0, 0, speed);
  10824. }
  10825. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10826. this._localDirection.copyFromFloats(speed, 0, 0);
  10827. }
  10828. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10829. this._localDirection.copyFromFloats(0, 0, -speed);
  10830. }
  10831. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10832. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10833. this.cameraDirection.addInPlace(this._transformedDirection);
  10834. }
  10835. _super.prototype._checkInputs.call(this);
  10836. };
  10837. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10838. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10839. };
  10840. FreeCamera.prototype._updatePosition = function () {
  10841. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10842. this._collideWithWorld(this.cameraDirection);
  10843. }
  10844. else {
  10845. this.position.addInPlace(this.cameraDirection);
  10846. }
  10847. };
  10848. return FreeCamera;
  10849. })(BABYLON.TargetCamera);
  10850. BABYLON.FreeCamera = FreeCamera;
  10851. })(BABYLON || (BABYLON = {}));
  10852. var BABYLON;
  10853. (function (BABYLON) {
  10854. var FollowCamera = (function (_super) {
  10855. __extends(FollowCamera, _super);
  10856. function FollowCamera(name, position, scene) {
  10857. _super.call(this, name, position, scene);
  10858. this.radius = 12;
  10859. this.rotationOffset = 0;
  10860. this.heightOffset = 4;
  10861. this.cameraAcceleration = 0.05;
  10862. this.maxCameraSpeed = 20;
  10863. }
  10864. FollowCamera.prototype.getRadians = function (degrees) {
  10865. return degrees * Math.PI / 180;
  10866. };
  10867. FollowCamera.prototype.follow = function (cameraTarget) {
  10868. if (!cameraTarget)
  10869. return;
  10870. var yRotation;
  10871. if (cameraTarget.rotationQuaternion) {
  10872. var rotMatrix = new BABYLON.Matrix();
  10873. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10874. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10875. }
  10876. else {
  10877. yRotation = cameraTarget.rotation.y;
  10878. }
  10879. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10880. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10881. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10882. var dx = targetX - this.position.x;
  10883. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10884. var dz = (targetZ) - this.position.z;
  10885. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10886. var vy = dy * this.cameraAcceleration;
  10887. var vz = dz * this.cameraAcceleration * 2;
  10888. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10889. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10890. }
  10891. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10892. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10893. }
  10894. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10895. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10896. }
  10897. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10898. this.setTarget(cameraTarget.position);
  10899. };
  10900. FollowCamera.prototype._checkInputs = function () {
  10901. _super.prototype._checkInputs.call(this);
  10902. this.follow(this.target);
  10903. };
  10904. return FollowCamera;
  10905. })(BABYLON.TargetCamera);
  10906. BABYLON.FollowCamera = FollowCamera;
  10907. var ArcFollowCamera = (function (_super) {
  10908. __extends(ArcFollowCamera, _super);
  10909. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10910. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10911. this.alpha = alpha;
  10912. this.beta = beta;
  10913. this.radius = radius;
  10914. this.target = target;
  10915. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10916. this.follow();
  10917. }
  10918. ArcFollowCamera.prototype.follow = function () {
  10919. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10920. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10921. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10922. this.position = this.target.position.add(this._cartesianCoordinates);
  10923. this.setTarget(this.target.position);
  10924. };
  10925. ArcFollowCamera.prototype._checkInputs = function () {
  10926. _super.prototype._checkInputs.call(this);
  10927. this.follow();
  10928. };
  10929. return ArcFollowCamera;
  10930. })(BABYLON.TargetCamera);
  10931. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10932. })(BABYLON || (BABYLON = {}));
  10933. var BABYLON;
  10934. (function (BABYLON) {
  10935. // We're mainly based on the logic defined into the FreeCamera code
  10936. var TouchCamera = (function (_super) {
  10937. __extends(TouchCamera, _super);
  10938. function TouchCamera(name, position, scene) {
  10939. _super.call(this, name, position, scene);
  10940. this._offsetX = null;
  10941. this._offsetY = null;
  10942. this._pointerCount = 0;
  10943. this._pointerPressed = [];
  10944. this.angularSensibility = 200000.0;
  10945. this.moveSensibility = 500.0;
  10946. }
  10947. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10948. var _this = this;
  10949. var previousPosition;
  10950. if (this._attachedCanvas) {
  10951. return;
  10952. }
  10953. this._attachedCanvas = canvas;
  10954. if (this._onPointerDown === undefined) {
  10955. this._onPointerDown = function (evt) {
  10956. if (!noPreventDefault) {
  10957. evt.preventDefault();
  10958. }
  10959. _this._pointerPressed.push(evt.pointerId);
  10960. if (_this._pointerPressed.length !== 1) {
  10961. return;
  10962. }
  10963. previousPosition = {
  10964. x: evt.clientX,
  10965. y: evt.clientY
  10966. };
  10967. };
  10968. this._onPointerUp = function (evt) {
  10969. if (!noPreventDefault) {
  10970. evt.preventDefault();
  10971. }
  10972. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10973. if (index === -1) {
  10974. return;
  10975. }
  10976. _this._pointerPressed.splice(index, 1);
  10977. if (index != 0) {
  10978. return;
  10979. }
  10980. previousPosition = null;
  10981. _this._offsetX = null;
  10982. _this._offsetY = null;
  10983. };
  10984. this._onPointerMove = function (evt) {
  10985. if (!noPreventDefault) {
  10986. evt.preventDefault();
  10987. }
  10988. if (!previousPosition) {
  10989. return;
  10990. }
  10991. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10992. if (index != 0) {
  10993. return;
  10994. }
  10995. _this._offsetX = evt.clientX - previousPosition.x;
  10996. _this._offsetY = -(evt.clientY - previousPosition.y);
  10997. };
  10998. this._onLostFocus = function () {
  10999. _this._offsetX = null;
  11000. _this._offsetY = null;
  11001. };
  11002. }
  11003. canvas.addEventListener("pointerdown", this._onPointerDown);
  11004. canvas.addEventListener("pointerup", this._onPointerUp);
  11005. canvas.addEventListener("pointerout", this._onPointerUp);
  11006. canvas.addEventListener("pointermove", this._onPointerMove);
  11007. BABYLON.Tools.RegisterTopRootEvents([
  11008. { name: "blur", handler: this._onLostFocus }
  11009. ]);
  11010. };
  11011. TouchCamera.prototype.detachControl = function (canvas) {
  11012. if (this._attachedCanvas != canvas) {
  11013. return;
  11014. }
  11015. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11016. canvas.removeEventListener("pointerup", this._onPointerUp);
  11017. canvas.removeEventListener("pointerout", this._onPointerUp);
  11018. canvas.removeEventListener("pointermove", this._onPointerMove);
  11019. BABYLON.Tools.UnregisterTopRootEvents([
  11020. { name: "blur", handler: this._onLostFocus }
  11021. ]);
  11022. this._attachedCanvas = null;
  11023. };
  11024. TouchCamera.prototype._checkInputs = function () {
  11025. if (this._offsetX) {
  11026. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11027. if (this._pointerPressed.length > 1) {
  11028. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11029. }
  11030. else {
  11031. var speed = this._computeLocalCameraSpeed();
  11032. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11033. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11034. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11035. }
  11036. }
  11037. _super.prototype._checkInputs.call(this);
  11038. };
  11039. return TouchCamera;
  11040. })(BABYLON.FreeCamera);
  11041. BABYLON.TouchCamera = TouchCamera;
  11042. })(BABYLON || (BABYLON = {}));
  11043. var BABYLON;
  11044. (function (BABYLON) {
  11045. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11046. var ArcRotateCamera = (function (_super) {
  11047. __extends(ArcRotateCamera, _super);
  11048. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11049. var _this = this;
  11050. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11051. this.alpha = alpha;
  11052. this.beta = beta;
  11053. this.radius = radius;
  11054. this.target = target;
  11055. this.inertialAlphaOffset = 0;
  11056. this.inertialBetaOffset = 0;
  11057. this.inertialRadiusOffset = 0;
  11058. this.lowerAlphaLimit = null;
  11059. this.upperAlphaLimit = null;
  11060. this.lowerBetaLimit = 0.01;
  11061. this.upperBetaLimit = Math.PI;
  11062. this.lowerRadiusLimit = null;
  11063. this.upperRadiusLimit = null;
  11064. this.angularSensibilityX = 1000.0;
  11065. this.angularSensibilityY = 1000.0;
  11066. this.wheelPrecision = 3.0;
  11067. this.pinchPrecision = 2.0;
  11068. this.panningSensibility = 50.0;
  11069. this.inertialPanningX = 0;
  11070. this.inertialPanningY = 0;
  11071. this.keysUp = [38];
  11072. this.keysDown = [40];
  11073. this.keysLeft = [37];
  11074. this.keysRight = [39];
  11075. this.zoomOnFactor = 1;
  11076. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11077. this.pinchInwards = true;
  11078. this.allowUpsideDown = true;
  11079. this._keys = [];
  11080. this._viewMatrix = new BABYLON.Matrix();
  11081. this._isRightClick = false;
  11082. this._isCtrlPushed = false;
  11083. this.checkCollisions = false;
  11084. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11085. this._collider = new BABYLON.Collider();
  11086. this._previousPosition = BABYLON.Vector3.Zero();
  11087. this._collisionVelocity = BABYLON.Vector3.Zero();
  11088. this._newPosition = BABYLON.Vector3.Zero();
  11089. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11090. if (collidedMesh === void 0) { collidedMesh = null; }
  11091. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11092. newPosition.multiplyInPlace(_this._collider.radius);
  11093. }
  11094. if (!collidedMesh) {
  11095. _this._previousPosition.copyFrom(_this.position);
  11096. }
  11097. else {
  11098. _this.setPosition(_this.position);
  11099. if (_this.onCollide) {
  11100. _this.onCollide(collidedMesh);
  11101. }
  11102. }
  11103. // Recompute because of constraints
  11104. var cosa = Math.cos(_this.alpha);
  11105. var sina = Math.sin(_this.alpha);
  11106. var cosb = Math.cos(_this.beta);
  11107. var sinb = Math.sin(_this.beta);
  11108. var target = _this._getTargetPosition();
  11109. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11110. _this.position.copyFrom(_this._newPosition);
  11111. var up = _this.upVector;
  11112. if (_this.allowUpsideDown && _this.beta < 0) {
  11113. var up = up.clone();
  11114. up = up.negate();
  11115. }
  11116. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11117. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11118. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11119. _this._collisionTriggered = false;
  11120. };
  11121. if (!this.target) {
  11122. this.target = BABYLON.Vector3.Zero();
  11123. }
  11124. this.getViewMatrix();
  11125. }
  11126. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11127. //deprecated angularSensibility support
  11128. get: function () {
  11129. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11130. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11131. },
  11132. //deprecated angularSensibility support
  11133. set: function (value) {
  11134. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11135. this.angularSensibilityX = value;
  11136. this.angularSensibilityY = value;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. ArcRotateCamera.prototype._getTargetPosition = function () {
  11142. return this.target.position || this.target;
  11143. };
  11144. // Cache
  11145. ArcRotateCamera.prototype._initCache = function () {
  11146. _super.prototype._initCache.call(this);
  11147. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11148. this._cache.alpha = undefined;
  11149. this._cache.beta = undefined;
  11150. this._cache.radius = undefined;
  11151. this._cache.targetScreenOffset = undefined;
  11152. };
  11153. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11154. if (!ignoreParentClass) {
  11155. _super.prototype._updateCache.call(this);
  11156. }
  11157. this._cache.target.copyFrom(this._getTargetPosition());
  11158. this._cache.alpha = this.alpha;
  11159. this._cache.beta = this.beta;
  11160. this._cache.radius = this.radius;
  11161. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11162. };
  11163. // Synchronized
  11164. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11165. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11166. return false;
  11167. return this._cache.target.equals(this._getTargetPosition())
  11168. && this._cache.alpha === this.alpha
  11169. && this._cache.beta === this.beta
  11170. && this._cache.radius === this.radius
  11171. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11172. };
  11173. // Methods
  11174. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11175. var _this = this;
  11176. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11177. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11178. var previousPinchDistance = 0;
  11179. var pointers = new BABYLON.SmartCollection();
  11180. if (this._attachedElement) {
  11181. return;
  11182. }
  11183. this._attachedElement = element;
  11184. var engine = this.getEngine();
  11185. if (this._onPointerDown === undefined) {
  11186. this._onPointerDown = function (evt) {
  11187. // Manage panning with right click
  11188. _this._isRightClick = evt.button === 2 ? true : false;
  11189. // manage pointers
  11190. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11191. cacheSoloPointer = pointers.item(evt.pointerId);
  11192. if (!noPreventDefault) {
  11193. evt.preventDefault();
  11194. }
  11195. };
  11196. this._onPointerUp = function (evt) {
  11197. cacheSoloPointer = null;
  11198. previousPinchDistance = 0;
  11199. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11200. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11201. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11202. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11203. pointers.empty();
  11204. if (!noPreventDefault) {
  11205. evt.preventDefault();
  11206. }
  11207. };
  11208. this._onContextMenu = function (evt) {
  11209. evt.preventDefault();
  11210. };
  11211. this._onPointerMove = function (evt) {
  11212. if (!noPreventDefault) {
  11213. evt.preventDefault();
  11214. }
  11215. switch (pointers.count) {
  11216. case 1:
  11217. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11218. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11219. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11220. }
  11221. else {
  11222. var offsetX = evt.clientX - cacheSoloPointer.x;
  11223. var offsetY = evt.clientY - cacheSoloPointer.y;
  11224. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11225. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11226. }
  11227. cacheSoloPointer.x = evt.clientX;
  11228. cacheSoloPointer.y = evt.clientY;
  11229. break;
  11230. case 2:
  11231. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11232. pointers.item(evt.pointerId).x = evt.clientX;
  11233. pointers.item(evt.pointerId).y = evt.clientY;
  11234. var direction = _this.pinchInwards ? 1 : -1;
  11235. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11236. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11237. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11238. if (previousPinchDistance === 0) {
  11239. previousPinchDistance = pinchSquaredDistance;
  11240. return;
  11241. }
  11242. if (pinchSquaredDistance !== previousPinchDistance) {
  11243. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11244. previousPinchDistance = pinchSquaredDistance;
  11245. }
  11246. break;
  11247. default:
  11248. if (pointers.item(evt.pointerId)) {
  11249. pointers.item(evt.pointerId).x = evt.clientX;
  11250. pointers.item(evt.pointerId).y = evt.clientY;
  11251. }
  11252. }
  11253. };
  11254. this._onMouseMove = function (evt) {
  11255. if (!engine.isPointerLock) {
  11256. return;
  11257. }
  11258. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11259. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11260. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11261. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11262. if (!noPreventDefault) {
  11263. evt.preventDefault();
  11264. }
  11265. };
  11266. this._wheel = function (event) {
  11267. var delta = 0;
  11268. if (event.wheelDelta) {
  11269. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11270. }
  11271. else if (event.detail) {
  11272. delta = -event.detail / _this.wheelPrecision;
  11273. }
  11274. if (delta)
  11275. _this.inertialRadiusOffset += delta;
  11276. if (event.preventDefault) {
  11277. if (!noPreventDefault) {
  11278. event.preventDefault();
  11279. }
  11280. }
  11281. };
  11282. this._onKeyDown = function (evt) {
  11283. _this._isCtrlPushed = evt.ctrlKey;
  11284. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11285. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11286. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11287. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11288. var index = _this._keys.indexOf(evt.keyCode);
  11289. if (index === -1) {
  11290. _this._keys.push(evt.keyCode);
  11291. }
  11292. if (evt.preventDefault) {
  11293. if (!noPreventDefault) {
  11294. evt.preventDefault();
  11295. }
  11296. }
  11297. }
  11298. };
  11299. this._onKeyUp = function (evt) {
  11300. _this._isCtrlPushed = evt.ctrlKey;
  11301. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11302. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11303. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11304. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11305. var index = _this._keys.indexOf(evt.keyCode);
  11306. if (index >= 0) {
  11307. _this._keys.splice(index, 1);
  11308. }
  11309. if (evt.preventDefault) {
  11310. if (!noPreventDefault) {
  11311. evt.preventDefault();
  11312. }
  11313. }
  11314. }
  11315. };
  11316. this._onLostFocus = function () {
  11317. _this._keys = [];
  11318. pointers.empty();
  11319. previousPinchDistance = 0;
  11320. cacheSoloPointer = null;
  11321. };
  11322. this._onGestureStart = function (e) {
  11323. if (window.MSGesture === undefined) {
  11324. return;
  11325. }
  11326. if (!_this._MSGestureHandler) {
  11327. _this._MSGestureHandler = new MSGesture();
  11328. _this._MSGestureHandler.target = element;
  11329. }
  11330. _this._MSGestureHandler.addPointer(e.pointerId);
  11331. };
  11332. this._onGesture = function (e) {
  11333. _this.radius *= e.scale;
  11334. if (e.preventDefault) {
  11335. if (!noPreventDefault) {
  11336. e.stopPropagation();
  11337. e.preventDefault();
  11338. }
  11339. }
  11340. };
  11341. this._reset = function () {
  11342. _this._keys = [];
  11343. _this.inertialAlphaOffset = 0;
  11344. _this.inertialBetaOffset = 0;
  11345. _this.inertialRadiusOffset = 0;
  11346. pointers.empty();
  11347. previousPinchDistance = 0;
  11348. cacheSoloPointer = null;
  11349. };
  11350. }
  11351. if (!useCtrlForPanning) {
  11352. element.addEventListener("contextmenu", this._onContextMenu, false);
  11353. }
  11354. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11355. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11356. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11357. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11358. element.addEventListener("mousemove", this._onMouseMove, false);
  11359. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11360. element.addEventListener("MSGestureChange", this._onGesture, false);
  11361. element.addEventListener('mousewheel', this._wheel, false);
  11362. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11363. BABYLON.Tools.RegisterTopRootEvents([
  11364. { name: "keydown", handler: this._onKeyDown },
  11365. { name: "keyup", handler: this._onKeyUp },
  11366. { name: "blur", handler: this._onLostFocus }
  11367. ]);
  11368. };
  11369. ArcRotateCamera.prototype.detachControl = function (element) {
  11370. if (this._attachedElement !== element) {
  11371. return;
  11372. }
  11373. element.removeEventListener("contextmenu", this._onContextMenu);
  11374. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11375. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11376. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11377. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11378. element.removeEventListener("mousemove", this._onMouseMove);
  11379. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11380. element.removeEventListener("MSGestureChange", this._onGesture);
  11381. element.removeEventListener('mousewheel', this._wheel);
  11382. element.removeEventListener('DOMMouseScroll', this._wheel);
  11383. BABYLON.Tools.UnregisterTopRootEvents([
  11384. { name: "keydown", handler: this._onKeyDown },
  11385. { name: "keyup", handler: this._onKeyUp },
  11386. { name: "blur", handler: this._onLostFocus }
  11387. ]);
  11388. this._MSGestureHandler = null;
  11389. this._attachedElement = null;
  11390. if (this._reset) {
  11391. this._reset();
  11392. }
  11393. };
  11394. ArcRotateCamera.prototype._checkInputs = function () {
  11395. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11396. if (this._collisionTriggered) {
  11397. return;
  11398. }
  11399. // Keyboard
  11400. for (var index = 0; index < this._keys.length; index++) {
  11401. var keyCode = this._keys[index];
  11402. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11403. this.inertialAlphaOffset -= 0.01;
  11404. }
  11405. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11406. this.inertialBetaOffset -= 0.01;
  11407. }
  11408. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11409. this.inertialAlphaOffset += 0.01;
  11410. }
  11411. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11412. this.inertialBetaOffset += 0.01;
  11413. }
  11414. }
  11415. // Inertia
  11416. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11417. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11418. this.beta += this.inertialBetaOffset;
  11419. this.radius -= this.inertialRadiusOffset;
  11420. this.inertialAlphaOffset *= this.inertia;
  11421. this.inertialBetaOffset *= this.inertia;
  11422. this.inertialRadiusOffset *= this.inertia;
  11423. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11424. this.inertialAlphaOffset = 0;
  11425. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11426. this.inertialBetaOffset = 0;
  11427. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11428. this.inertialRadiusOffset = 0;
  11429. }
  11430. // Panning inertia
  11431. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11432. if (!this._localDirection) {
  11433. this._localDirection = BABYLON.Vector3.Zero();
  11434. this._transformedDirection = BABYLON.Vector3.Zero();
  11435. }
  11436. this.inertialPanningX *= this.inertia;
  11437. this.inertialPanningY *= this.inertia;
  11438. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11439. this.inertialPanningX = 0;
  11440. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11441. this.inertialPanningY = 0;
  11442. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11443. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11444. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11445. this.target.addInPlace(this._transformedDirection);
  11446. }
  11447. // Limits
  11448. this._checkLimits();
  11449. _super.prototype._checkInputs.call(this);
  11450. };
  11451. ArcRotateCamera.prototype._checkLimits = function () {
  11452. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11453. if (this.allowUpsideDown && this.beta > Math.PI) {
  11454. this.beta = this.beta - (2 * Math.PI);
  11455. }
  11456. }
  11457. else {
  11458. if (this.beta < this.lowerBetaLimit) {
  11459. this.beta = this.lowerBetaLimit;
  11460. }
  11461. }
  11462. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11463. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11464. this.beta = this.beta + (2 * Math.PI);
  11465. }
  11466. }
  11467. else {
  11468. if (this.beta > this.upperBetaLimit) {
  11469. this.beta = this.upperBetaLimit;
  11470. }
  11471. }
  11472. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11473. this.alpha = this.lowerAlphaLimit;
  11474. }
  11475. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11476. this.alpha = this.upperAlphaLimit;
  11477. }
  11478. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11479. this.radius = this.lowerRadiusLimit;
  11480. }
  11481. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11482. this.radius = this.upperRadiusLimit;
  11483. }
  11484. };
  11485. ArcRotateCamera.prototype.setPosition = function (position) {
  11486. var radiusv3 = position.subtract(this._getTargetPosition());
  11487. this.radius = radiusv3.length();
  11488. // Alpha
  11489. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11490. if (radiusv3.z < 0) {
  11491. this.alpha = 2 * Math.PI - this.alpha;
  11492. }
  11493. // Beta
  11494. this.beta = Math.acos(radiusv3.y / this.radius);
  11495. this._checkLimits();
  11496. };
  11497. ArcRotateCamera.prototype.setTarget = function (target) {
  11498. this.target = target;
  11499. };
  11500. ArcRotateCamera.prototype._getViewMatrix = function () {
  11501. // Compute
  11502. var cosa = Math.cos(this.alpha);
  11503. var sina = Math.sin(this.alpha);
  11504. var cosb = Math.cos(this.beta);
  11505. var sinb = Math.sin(this.beta);
  11506. var target = this._getTargetPosition();
  11507. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11508. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11509. this._collider.radius = this.collisionRadius;
  11510. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11511. this._collisionTriggered = true;
  11512. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11513. }
  11514. else {
  11515. this.position.copyFrom(this._newPosition);
  11516. var up = this.upVector;
  11517. if (this.allowUpsideDown && this.beta < 0) {
  11518. var up = up.clone();
  11519. up = up.negate();
  11520. }
  11521. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11522. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11523. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11524. }
  11525. return this._viewMatrix;
  11526. };
  11527. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11528. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11529. meshes = meshes || this.getScene().meshes;
  11530. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11531. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11532. this.radius = distance * this.zoomOnFactor;
  11533. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11534. };
  11535. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11536. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11537. var meshesOrMinMaxVector;
  11538. var distance;
  11539. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11540. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11541. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11542. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11543. }
  11544. else {
  11545. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11546. distance = meshesOrMinMaxVectorAndDistance.distance;
  11547. }
  11548. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11549. if (!doNotUpdateMaxZ) {
  11550. this.maxZ = distance * 2;
  11551. }
  11552. };
  11553. /**
  11554. * @override
  11555. * Override Camera.createRigCamera
  11556. */
  11557. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11558. switch (this.cameraRigMode) {
  11559. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11560. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11561. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11562. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11563. case BABYLON.Camera.RIG_MODE_VR:
  11564. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11565. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11566. }
  11567. };
  11568. /**
  11569. * @override
  11570. * Override Camera._updateRigCameras
  11571. */
  11572. ArcRotateCamera.prototype._updateRigCameras = function () {
  11573. switch (this.cameraRigMode) {
  11574. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11575. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11576. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11577. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11578. case BABYLON.Camera.RIG_MODE_VR:
  11579. var camLeft = this._rigCameras[0];
  11580. var camRight = this._rigCameras[1];
  11581. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11582. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11583. camLeft.beta = camRight.beta = this.beta;
  11584. camLeft.radius = camRight.radius = this.radius;
  11585. break;
  11586. }
  11587. _super.prototype._updateRigCameras.call(this);
  11588. };
  11589. return ArcRotateCamera;
  11590. })(BABYLON.TargetCamera);
  11591. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11592. })(BABYLON || (BABYLON = {}));
  11593. var BABYLON;
  11594. (function (BABYLON) {
  11595. // We're mainly based on the logic defined into the FreeCamera code
  11596. var DeviceOrientationCamera = (function (_super) {
  11597. __extends(DeviceOrientationCamera, _super);
  11598. function DeviceOrientationCamera(name, position, scene) {
  11599. var _this = this;
  11600. _super.call(this, name, position, scene);
  11601. this._offsetX = null;
  11602. this._offsetY = null;
  11603. this._orientationGamma = 0;
  11604. this._orientationBeta = 0;
  11605. this._initialOrientationGamma = 0;
  11606. this._initialOrientationBeta = 0;
  11607. this.angularSensibility = 10000.0;
  11608. this.moveSensibility = 50.0;
  11609. window.addEventListener("resize", function () {
  11610. _this._initialOrientationGamma = null;
  11611. }, false);
  11612. }
  11613. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11614. var _this = this;
  11615. if (this._attachedCanvas) {
  11616. return;
  11617. }
  11618. this._attachedCanvas = canvas;
  11619. if (!this._orientationChanged) {
  11620. this._orientationChanged = function (evt) {
  11621. if (!_this._initialOrientationGamma) {
  11622. _this._initialOrientationGamma = evt.gamma;
  11623. _this._initialOrientationBeta = evt.beta;
  11624. }
  11625. _this._orientationGamma = evt.gamma;
  11626. _this._orientationBeta = evt.beta;
  11627. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11628. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11629. };
  11630. }
  11631. window.addEventListener("deviceorientation", this._orientationChanged);
  11632. };
  11633. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11634. if (this._attachedCanvas != canvas) {
  11635. return;
  11636. }
  11637. window.removeEventListener("deviceorientation", this._orientationChanged);
  11638. this._attachedCanvas = null;
  11639. this._orientationGamma = 0;
  11640. this._orientationBeta = 0;
  11641. this._initialOrientationGamma = 0;
  11642. this._initialOrientationBeta = 0;
  11643. };
  11644. DeviceOrientationCamera.prototype._checkInputs = function () {
  11645. if (!this._offsetX) {
  11646. return;
  11647. }
  11648. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11649. var speed = this._computeLocalCameraSpeed();
  11650. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11651. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11652. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11653. _super.prototype._checkInputs.call(this);
  11654. };
  11655. return DeviceOrientationCamera;
  11656. })(BABYLON.FreeCamera);
  11657. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11658. })(BABYLON || (BABYLON = {}));
  11659. var BABYLON;
  11660. (function (BABYLON) {
  11661. var Gamepads = (function () {
  11662. function Gamepads(ongamedpadconnected) {
  11663. var _this = this;
  11664. this.babylonGamepads = [];
  11665. this.oneGamepadConnected = false;
  11666. this.isMonitoring = false;
  11667. this.gamepadEventSupported = 'GamepadEvent' in window;
  11668. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11669. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11670. 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=";
  11671. this._callbackGamepadConnected = ongamedpadconnected;
  11672. if (this.gamepadSupportAvailable) {
  11673. // Checking if the gamepad connected event is supported (like in Firefox)
  11674. if (this.gamepadEventSupported) {
  11675. window.addEventListener('gamepadconnected', function (evt) {
  11676. _this._onGamepadConnected(evt);
  11677. }, false);
  11678. window.addEventListener('gamepaddisconnected', function (evt) {
  11679. _this._onGamepadDisconnected(evt);
  11680. }, false);
  11681. }
  11682. else {
  11683. this._startMonitoringGamepads();
  11684. }
  11685. if (!this.oneGamepadConnected) {
  11686. this._insertGamepadDOMInstructions();
  11687. }
  11688. }
  11689. else {
  11690. this._insertGamepadDOMNotSupported();
  11691. }
  11692. }
  11693. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11694. Gamepads.gamepadDOMInfo = document.createElement("div");
  11695. var buttonAImage = document.createElement("img");
  11696. buttonAImage.src = this.buttonADataURL;
  11697. var spanMessage = document.createElement("span");
  11698. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11699. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11700. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11701. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11702. Gamepads.gamepadDOMInfo.style.width = "100%";
  11703. Gamepads.gamepadDOMInfo.style.height = "48px";
  11704. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11705. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11706. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11707. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11708. buttonAImage.style.position = "relative";
  11709. buttonAImage.style.bottom = "8px";
  11710. spanMessage.style.position = "relative";
  11711. spanMessage.style.fontSize = "32px";
  11712. spanMessage.style.bottom = "32px";
  11713. spanMessage.style.color = "green";
  11714. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11715. };
  11716. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11717. Gamepads.gamepadDOMInfo = document.createElement("div");
  11718. var spanMessage = document.createElement("span");
  11719. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11720. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11721. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11722. Gamepads.gamepadDOMInfo.style.width = "100%";
  11723. Gamepads.gamepadDOMInfo.style.height = "40px";
  11724. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11725. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11726. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11727. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11728. spanMessage.style.position = "relative";
  11729. spanMessage.style.fontSize = "32px";
  11730. spanMessage.style.color = "red";
  11731. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11732. };
  11733. Gamepads.prototype.dispose = function () {
  11734. if (Gamepads.gamepadDOMInfo) {
  11735. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11736. }
  11737. };
  11738. Gamepads.prototype._onGamepadConnected = function (evt) {
  11739. var newGamepad = this._addNewGamepad(evt.gamepad);
  11740. if (this._callbackGamepadConnected)
  11741. this._callbackGamepadConnected(newGamepad);
  11742. this._startMonitoringGamepads();
  11743. };
  11744. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11745. if (!this.oneGamepadConnected) {
  11746. this.oneGamepadConnected = true;
  11747. if (Gamepads.gamepadDOMInfo) {
  11748. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11749. Gamepads.gamepadDOMInfo = null;
  11750. }
  11751. }
  11752. var newGamepad;
  11753. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11754. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11755. }
  11756. else {
  11757. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11758. }
  11759. this.babylonGamepads.push(newGamepad);
  11760. return newGamepad;
  11761. };
  11762. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11763. // Remove the gamepad from the list of gamepads to monitor.
  11764. for (var i in this.babylonGamepads) {
  11765. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11766. this.babylonGamepads.splice(i, 1);
  11767. break;
  11768. }
  11769. }
  11770. // If no gamepads are left, stop the polling loop.
  11771. if (this.babylonGamepads.length == 0) {
  11772. this._stopMonitoringGamepads();
  11773. }
  11774. };
  11775. Gamepads.prototype._startMonitoringGamepads = function () {
  11776. if (!this.isMonitoring) {
  11777. this.isMonitoring = true;
  11778. this._checkGamepadsStatus();
  11779. }
  11780. };
  11781. Gamepads.prototype._stopMonitoringGamepads = function () {
  11782. this.isMonitoring = false;
  11783. };
  11784. Gamepads.prototype._checkGamepadsStatus = function () {
  11785. var _this = this;
  11786. // updating gamepad objects
  11787. this._updateGamepadObjects();
  11788. for (var i in this.babylonGamepads) {
  11789. this.babylonGamepads[i].update();
  11790. }
  11791. if (this.isMonitoring) {
  11792. if (window.requestAnimationFrame) {
  11793. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11794. }
  11795. else if (window.mozRequestAnimationFrame) {
  11796. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11797. }
  11798. else if (window.webkitRequestAnimationFrame) {
  11799. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11800. }
  11801. }
  11802. };
  11803. // This function is called only on Chrome, which does not yet support
  11804. // connection/disconnection events, but requires you to monitor
  11805. // an array for changes.
  11806. Gamepads.prototype._updateGamepadObjects = function () {
  11807. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11808. for (var i = 0; i < gamepads.length; i++) {
  11809. if (gamepads[i]) {
  11810. if (!(gamepads[i].index in this.babylonGamepads)) {
  11811. var newGamepad = this._addNewGamepad(gamepads[i]);
  11812. if (this._callbackGamepadConnected) {
  11813. this._callbackGamepadConnected(newGamepad);
  11814. }
  11815. }
  11816. else {
  11817. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11818. }
  11819. }
  11820. }
  11821. };
  11822. return Gamepads;
  11823. })();
  11824. BABYLON.Gamepads = Gamepads;
  11825. var StickValues = (function () {
  11826. function StickValues(x, y) {
  11827. this.x = x;
  11828. this.y = y;
  11829. }
  11830. return StickValues;
  11831. })();
  11832. BABYLON.StickValues = StickValues;
  11833. var Gamepad = (function () {
  11834. function Gamepad(id, index, browserGamepad) {
  11835. this.id = id;
  11836. this.index = index;
  11837. this.browserGamepad = browserGamepad;
  11838. if (this.browserGamepad.axes.length >= 2) {
  11839. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11840. }
  11841. if (this.browserGamepad.axes.length >= 4) {
  11842. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11843. }
  11844. }
  11845. Gamepad.prototype.onleftstickchanged = function (callback) {
  11846. this._onleftstickchanged = callback;
  11847. };
  11848. Gamepad.prototype.onrightstickchanged = function (callback) {
  11849. this._onrightstickchanged = callback;
  11850. };
  11851. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11852. get: function () {
  11853. return this._leftStick;
  11854. },
  11855. set: function (newValues) {
  11856. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11857. this._onleftstickchanged(newValues);
  11858. }
  11859. this._leftStick = newValues;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11865. get: function () {
  11866. return this._rightStick;
  11867. },
  11868. set: function (newValues) {
  11869. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11870. this._onrightstickchanged(newValues);
  11871. }
  11872. this._rightStick = newValues;
  11873. },
  11874. enumerable: true,
  11875. configurable: true
  11876. });
  11877. Gamepad.prototype.update = function () {
  11878. if (this._leftStick) {
  11879. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11880. }
  11881. if (this._rightStick) {
  11882. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11883. }
  11884. };
  11885. return Gamepad;
  11886. })();
  11887. BABYLON.Gamepad = Gamepad;
  11888. var GenericPad = (function (_super) {
  11889. __extends(GenericPad, _super);
  11890. function GenericPad(id, index, gamepad) {
  11891. _super.call(this, id, index, gamepad);
  11892. this.id = id;
  11893. this.index = index;
  11894. this.gamepad = gamepad;
  11895. this._buttons = new Array(gamepad.buttons.length);
  11896. }
  11897. GenericPad.prototype.onbuttondown = function (callback) {
  11898. this._onbuttondown = callback;
  11899. };
  11900. GenericPad.prototype.onbuttonup = function (callback) {
  11901. this._onbuttonup = callback;
  11902. };
  11903. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11904. if (newValue !== currentValue) {
  11905. if (this._onbuttondown && newValue === 1) {
  11906. this._onbuttondown(buttonIndex);
  11907. }
  11908. if (this._onbuttonup && newValue === 0) {
  11909. this._onbuttonup(buttonIndex);
  11910. }
  11911. }
  11912. return newValue;
  11913. };
  11914. GenericPad.prototype.update = function () {
  11915. _super.prototype.update.call(this);
  11916. for (var index = 0; index < this._buttons.length; index++) {
  11917. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11918. }
  11919. };
  11920. return GenericPad;
  11921. })(Gamepad);
  11922. BABYLON.GenericPad = GenericPad;
  11923. (function (Xbox360Button) {
  11924. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11925. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11926. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11927. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11928. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11929. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11930. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11931. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11932. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11933. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11934. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11935. var Xbox360Button = BABYLON.Xbox360Button;
  11936. (function (Xbox360Dpad) {
  11937. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11938. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11939. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11940. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11941. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11942. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11943. var Xbox360Pad = (function (_super) {
  11944. __extends(Xbox360Pad, _super);
  11945. function Xbox360Pad() {
  11946. _super.apply(this, arguments);
  11947. this._leftTrigger = 0;
  11948. this._rightTrigger = 0;
  11949. this._buttonA = 0;
  11950. this._buttonB = 0;
  11951. this._buttonX = 0;
  11952. this._buttonY = 0;
  11953. this._buttonBack = 0;
  11954. this._buttonStart = 0;
  11955. this._buttonLB = 0;
  11956. this._buttonRB = 0;
  11957. this._buttonLeftStick = 0;
  11958. this._buttonRightStick = 0;
  11959. this._dPadUp = 0;
  11960. this._dPadDown = 0;
  11961. this._dPadLeft = 0;
  11962. this._dPadRight = 0;
  11963. }
  11964. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11965. this._onlefttriggerchanged = callback;
  11966. };
  11967. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11968. this._onrighttriggerchanged = callback;
  11969. };
  11970. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11971. get: function () {
  11972. return this._leftTrigger;
  11973. },
  11974. set: function (newValue) {
  11975. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11976. this._onlefttriggerchanged(newValue);
  11977. }
  11978. this._leftTrigger = newValue;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11984. get: function () {
  11985. return this._rightTrigger;
  11986. },
  11987. set: function (newValue) {
  11988. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11989. this._onrighttriggerchanged(newValue);
  11990. }
  11991. this._rightTrigger = newValue;
  11992. },
  11993. enumerable: true,
  11994. configurable: true
  11995. });
  11996. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11997. this._onbuttondown = callback;
  11998. };
  11999. Xbox360Pad.prototype.onbuttonup = function (callback) {
  12000. this._onbuttonup = callback;
  12001. };
  12002. Xbox360Pad.prototype.ondpaddown = function (callback) {
  12003. this._ondpaddown = callback;
  12004. };
  12005. Xbox360Pad.prototype.ondpadup = function (callback) {
  12006. this._ondpadup = callback;
  12007. };
  12008. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  12009. if (newValue !== currentValue) {
  12010. if (this._onbuttondown && newValue === 1) {
  12011. this._onbuttondown(buttonType);
  12012. }
  12013. if (this._onbuttonup && newValue === 0) {
  12014. this._onbuttonup(buttonType);
  12015. }
  12016. }
  12017. return newValue;
  12018. };
  12019. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  12020. if (newValue !== currentValue) {
  12021. if (this._ondpaddown && newValue === 1) {
  12022. this._ondpaddown(buttonType);
  12023. }
  12024. if (this._ondpadup && newValue === 0) {
  12025. this._ondpadup(buttonType);
  12026. }
  12027. }
  12028. return newValue;
  12029. };
  12030. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  12031. get: function () {
  12032. return this._buttonA;
  12033. },
  12034. set: function (value) {
  12035. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  12041. get: function () {
  12042. return this._buttonB;
  12043. },
  12044. set: function (value) {
  12045. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  12046. },
  12047. enumerable: true,
  12048. configurable: true
  12049. });
  12050. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  12051. get: function () {
  12052. return this._buttonX;
  12053. },
  12054. set: function (value) {
  12055. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  12061. get: function () {
  12062. return this._buttonY;
  12063. },
  12064. set: function (value) {
  12065. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  12071. get: function () {
  12072. return this._buttonStart;
  12073. },
  12074. set: function (value) {
  12075. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  12081. get: function () {
  12082. return this._buttonBack;
  12083. },
  12084. set: function (value) {
  12085. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  12086. },
  12087. enumerable: true,
  12088. configurable: true
  12089. });
  12090. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  12091. get: function () {
  12092. return this._buttonLB;
  12093. },
  12094. set: function (value) {
  12095. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  12096. },
  12097. enumerable: true,
  12098. configurable: true
  12099. });
  12100. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  12101. get: function () {
  12102. return this._buttonRB;
  12103. },
  12104. set: function (value) {
  12105. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  12106. },
  12107. enumerable: true,
  12108. configurable: true
  12109. });
  12110. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  12111. get: function () {
  12112. return this._buttonLeftStick;
  12113. },
  12114. set: function (value) {
  12115. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  12116. },
  12117. enumerable: true,
  12118. configurable: true
  12119. });
  12120. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  12121. get: function () {
  12122. return this._buttonRightStick;
  12123. },
  12124. set: function (value) {
  12125. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12126. },
  12127. enumerable: true,
  12128. configurable: true
  12129. });
  12130. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12131. get: function () {
  12132. return this._dPadUp;
  12133. },
  12134. set: function (value) {
  12135. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12141. get: function () {
  12142. return this._dPadDown;
  12143. },
  12144. set: function (value) {
  12145. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12146. },
  12147. enumerable: true,
  12148. configurable: true
  12149. });
  12150. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12151. get: function () {
  12152. return this._dPadLeft;
  12153. },
  12154. set: function (value) {
  12155. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12161. get: function () {
  12162. return this._dPadRight;
  12163. },
  12164. set: function (value) {
  12165. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12166. },
  12167. enumerable: true,
  12168. configurable: true
  12169. });
  12170. Xbox360Pad.prototype.update = function () {
  12171. _super.prototype.update.call(this);
  12172. this.buttonA = this.browserGamepad.buttons[0].value;
  12173. this.buttonB = this.browserGamepad.buttons[1].value;
  12174. this.buttonX = this.browserGamepad.buttons[2].value;
  12175. this.buttonY = this.browserGamepad.buttons[3].value;
  12176. this.buttonLB = this.browserGamepad.buttons[4].value;
  12177. this.buttonRB = this.browserGamepad.buttons[5].value;
  12178. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12179. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12180. this.buttonBack = this.browserGamepad.buttons[8].value;
  12181. this.buttonStart = this.browserGamepad.buttons[9].value;
  12182. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12183. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12184. this.dPadUp = this.browserGamepad.buttons[12].value;
  12185. this.dPadDown = this.browserGamepad.buttons[13].value;
  12186. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12187. this.dPadRight = this.browserGamepad.buttons[15].value;
  12188. };
  12189. return Xbox360Pad;
  12190. })(Gamepad);
  12191. BABYLON.Xbox360Pad = Xbox360Pad;
  12192. })(BABYLON || (BABYLON = {}));
  12193. var BABYLON;
  12194. (function (BABYLON) {
  12195. // We're mainly based on the logic defined into the FreeCamera code
  12196. var GamepadCamera = (function (_super) {
  12197. __extends(GamepadCamera, _super);
  12198. function GamepadCamera(name, position, scene) {
  12199. var _this = this;
  12200. _super.call(this, name, position, scene);
  12201. this.angularSensibility = 200;
  12202. this.moveSensibility = 75;
  12203. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12204. }
  12205. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12206. // Only the first gamepad can control the camera
  12207. if (gamepad.index === 0) {
  12208. this._gamepad = gamepad;
  12209. }
  12210. };
  12211. GamepadCamera.prototype._checkInputs = function () {
  12212. if (this._gamepad) {
  12213. var LSValues = this._gamepad.leftStick;
  12214. var normalizedLX = LSValues.x / this.moveSensibility;
  12215. var normalizedLY = LSValues.y / this.moveSensibility;
  12216. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12217. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12218. var RSValues = this._gamepad.rightStick;
  12219. var normalizedRX = RSValues.x / this.angularSensibility;
  12220. var normalizedRY = RSValues.y / this.angularSensibility;
  12221. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12222. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12223. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12224. var speed = this._computeLocalCameraSpeed() * 50.0;
  12225. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12226. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12227. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12228. }
  12229. _super.prototype._checkInputs.call(this);
  12230. };
  12231. GamepadCamera.prototype.dispose = function () {
  12232. this._gamepads.dispose();
  12233. _super.prototype.dispose.call(this);
  12234. };
  12235. return GamepadCamera;
  12236. })(BABYLON.FreeCamera);
  12237. BABYLON.GamepadCamera = GamepadCamera;
  12238. })(BABYLON || (BABYLON = {}));
  12239. var BABYLON;
  12240. (function (BABYLON) {
  12241. var RenderingManager = (function () {
  12242. function RenderingManager(scene) {
  12243. this._renderingGroups = new Array();
  12244. this._scene = scene;
  12245. }
  12246. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12247. if (this._scene._activeParticleSystems.length === 0) {
  12248. return;
  12249. }
  12250. // Particles
  12251. var activeCamera = this._scene.activeCamera;
  12252. var beforeParticlesDate = BABYLON.Tools.Now;
  12253. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12254. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12255. if (particleSystem.renderingGroupId !== index) {
  12256. continue;
  12257. }
  12258. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12259. continue;
  12260. }
  12261. this._clearDepthBuffer();
  12262. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12263. this._scene._activeParticles += particleSystem.render();
  12264. }
  12265. }
  12266. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12267. };
  12268. RenderingManager.prototype._renderSprites = function (index) {
  12269. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12270. return;
  12271. }
  12272. // Sprites
  12273. var activeCamera = this._scene.activeCamera;
  12274. var beforeSpritessDate = BABYLON.Tools.Now;
  12275. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12276. var spriteManager = this._scene.spriteManagers[id];
  12277. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12278. this._clearDepthBuffer();
  12279. spriteManager.render();
  12280. }
  12281. }
  12282. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12283. };
  12284. RenderingManager.prototype._clearDepthBuffer = function () {
  12285. if (this._depthBufferAlreadyCleaned) {
  12286. return;
  12287. }
  12288. this._scene.getEngine().clear(0, false, true);
  12289. this._depthBufferAlreadyCleaned = true;
  12290. };
  12291. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12292. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12293. this._depthBufferAlreadyCleaned = false;
  12294. var renderingGroup = this._renderingGroups[index];
  12295. var needToStepBack = false;
  12296. if (renderingGroup) {
  12297. this._clearDepthBuffer();
  12298. if (!renderingGroup.render(customRenderFunction)) {
  12299. this._renderingGroups.splice(index, 1);
  12300. needToStepBack = true;
  12301. }
  12302. }
  12303. if (renderSprites) {
  12304. this._renderSprites(index);
  12305. }
  12306. if (renderParticles) {
  12307. this._renderParticles(index, activeMeshes);
  12308. }
  12309. if (needToStepBack) {
  12310. index--;
  12311. }
  12312. }
  12313. };
  12314. RenderingManager.prototype.reset = function () {
  12315. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12316. if (renderingGroup) {
  12317. renderingGroup.prepare();
  12318. }
  12319. });
  12320. };
  12321. RenderingManager.prototype.dispatch = function (subMesh) {
  12322. var mesh = subMesh.getMesh();
  12323. var renderingGroupId = mesh.renderingGroupId || 0;
  12324. if (!this._renderingGroups[renderingGroupId]) {
  12325. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12326. }
  12327. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12328. };
  12329. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12330. return RenderingManager;
  12331. })();
  12332. BABYLON.RenderingManager = RenderingManager;
  12333. })(BABYLON || (BABYLON = {}));
  12334. var BABYLON;
  12335. (function (BABYLON) {
  12336. var RenderingGroup = (function () {
  12337. function RenderingGroup(index, scene) {
  12338. this.index = index;
  12339. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12340. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12341. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12342. this._scene = scene;
  12343. }
  12344. RenderingGroup.prototype.render = function (customRenderFunction) {
  12345. if (customRenderFunction) {
  12346. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12347. return true;
  12348. }
  12349. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12350. return false;
  12351. }
  12352. var engine = this._scene.getEngine();
  12353. // Opaque
  12354. var subIndex;
  12355. var submesh;
  12356. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12357. submesh = this._opaqueSubMeshes.data[subIndex];
  12358. submesh.render(false);
  12359. }
  12360. // Alpha test
  12361. engine.setAlphaTesting(true);
  12362. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12363. submesh = this._alphaTestSubMeshes.data[subIndex];
  12364. submesh.render(false);
  12365. }
  12366. engine.setAlphaTesting(false);
  12367. // Transparent
  12368. if (this._transparentSubMeshes.length) {
  12369. // Sorting
  12370. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12371. submesh = this._transparentSubMeshes.data[subIndex];
  12372. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12373. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12374. }
  12375. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12376. sortedArray.sort(function (a, b) {
  12377. // Alpha index first
  12378. if (a._alphaIndex > b._alphaIndex) {
  12379. return 1;
  12380. }
  12381. if (a._alphaIndex < b._alphaIndex) {
  12382. return -1;
  12383. }
  12384. // Then distance to camera
  12385. if (a._distanceToCamera < b._distanceToCamera) {
  12386. return 1;
  12387. }
  12388. if (a._distanceToCamera > b._distanceToCamera) {
  12389. return -1;
  12390. }
  12391. return 0;
  12392. });
  12393. // Rendering
  12394. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12395. submesh = sortedArray[subIndex];
  12396. submesh.render(true);
  12397. }
  12398. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12399. }
  12400. return true;
  12401. };
  12402. RenderingGroup.prototype.prepare = function () {
  12403. this._opaqueSubMeshes.reset();
  12404. this._transparentSubMeshes.reset();
  12405. this._alphaTestSubMeshes.reset();
  12406. };
  12407. RenderingGroup.prototype.dispatch = function (subMesh) {
  12408. var material = subMesh.getMaterial();
  12409. var mesh = subMesh.getMesh();
  12410. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12411. this._transparentSubMeshes.push(subMesh);
  12412. }
  12413. else if (material.needAlphaTesting()) {
  12414. this._alphaTestSubMeshes.push(subMesh);
  12415. }
  12416. else {
  12417. this._opaqueSubMeshes.push(subMesh); // Opaque
  12418. }
  12419. };
  12420. return RenderingGroup;
  12421. })();
  12422. BABYLON.RenderingGroup = RenderingGroup;
  12423. })(BABYLON || (BABYLON = {}));
  12424. var BABYLON;
  12425. (function (BABYLON) {
  12426. /**
  12427. * Represents a scene to be rendered by the engine.
  12428. * @see http://doc.babylonjs.com/page.php?p=21911
  12429. */
  12430. var Scene = (function () {
  12431. /**
  12432. * @constructor
  12433. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12434. */
  12435. function Scene(engine) {
  12436. // Members
  12437. this.autoClear = true;
  12438. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12439. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12440. this.forceWireframe = false;
  12441. this.forcePointsCloud = false;
  12442. this.forceShowBoundingBoxes = false;
  12443. this.animationsEnabled = true;
  12444. 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
  12445. // Fog
  12446. /**
  12447. * is fog enabled on this scene.
  12448. * @type {boolean}
  12449. */
  12450. this.fogEnabled = true;
  12451. this.fogMode = Scene.FOGMODE_NONE;
  12452. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12453. this.fogDensity = 0.1;
  12454. this.fogStart = 0;
  12455. this.fogEnd = 1000.0;
  12456. // Lights
  12457. /**
  12458. * is shadow enabled on this scene.
  12459. * @type {boolean}
  12460. */
  12461. this.shadowsEnabled = true;
  12462. /**
  12463. * is light enabled on this scene.
  12464. * @type {boolean}
  12465. */
  12466. this.lightsEnabled = true;
  12467. /**
  12468. * All of the lights added to this scene.
  12469. * @see BABYLON.Light
  12470. * @type {BABYLON.Light[]}
  12471. */
  12472. this.lights = new Array();
  12473. // Cameras
  12474. /**
  12475. * All of the cameras added to this scene.
  12476. * @see BABYLON.Camera
  12477. * @type {BABYLON.Camera[]}
  12478. */
  12479. this.cameras = new Array();
  12480. this.activeCameras = new Array();
  12481. // Meshes
  12482. /**
  12483. * All of the (abstract) meshes added to this scene.
  12484. * @see BABYLON.AbstractMesh
  12485. * @type {BABYLON.AbstractMesh[]}
  12486. */
  12487. this.meshes = new Array();
  12488. // Geometries
  12489. this._geometries = new Array();
  12490. this.materials = new Array();
  12491. this.multiMaterials = new Array();
  12492. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12493. // Textures
  12494. this.texturesEnabled = true;
  12495. this.textures = new Array();
  12496. // Particles
  12497. this.particlesEnabled = true;
  12498. this.particleSystems = new Array();
  12499. // Sprites
  12500. this.spritesEnabled = true;
  12501. this.spriteManagers = new Array();
  12502. // Layers
  12503. this.layers = new Array();
  12504. // Skeletons
  12505. this.skeletonsEnabled = true;
  12506. this.skeletons = new Array();
  12507. // Lens flares
  12508. this.lensFlaresEnabled = true;
  12509. this.lensFlareSystems = new Array();
  12510. // Collisions
  12511. this.collisionsEnabled = true;
  12512. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12513. // Postprocesses
  12514. this.postProcessesEnabled = true;
  12515. // Customs render targets
  12516. this.renderTargetsEnabled = true;
  12517. this.dumpNextRenderTargets = false;
  12518. this.customRenderTargets = new Array();
  12519. // Imported meshes
  12520. this.importedMeshesFiles = new Array();
  12521. // Probes
  12522. this.probesEnabled = true;
  12523. this.reflectionProbes = new Array();
  12524. this._actionManagers = new Array();
  12525. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12526. // Procedural textures
  12527. this.proceduralTexturesEnabled = true;
  12528. this._proceduralTextures = new Array();
  12529. this.soundTracks = new Array();
  12530. this._audioEnabled = true;
  12531. this._headphone = false;
  12532. this._totalVertices = 0;
  12533. this._activeIndices = 0;
  12534. this._activeParticles = 0;
  12535. this._lastFrameDuration = 0;
  12536. this._evaluateActiveMeshesDuration = 0;
  12537. this._renderTargetsDuration = 0;
  12538. this._particlesDuration = 0;
  12539. this._renderDuration = 0;
  12540. this._spritesDuration = 0;
  12541. this._animationRatio = 0;
  12542. this._renderId = 0;
  12543. this._executeWhenReadyTimeoutId = -1;
  12544. this._toBeDisposed = new BABYLON.SmartArray(256);
  12545. this._onReadyCallbacks = new Array();
  12546. this._pendingData = []; //ANY
  12547. this._onBeforeRenderCallbacks = new Array();
  12548. this._onAfterRenderCallbacks = new Array();
  12549. this._activeMeshes = new BABYLON.SmartArray(256);
  12550. this._processedMaterials = new BABYLON.SmartArray(256);
  12551. this._renderTargets = new BABYLON.SmartArray(256);
  12552. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12553. this._activeSkeletons = new BABYLON.SmartArray(32);
  12554. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12555. this._activeBones = 0;
  12556. this._activeAnimatables = new Array();
  12557. this._transformMatrix = BABYLON.Matrix.Zero();
  12558. this._edgesRenderers = new BABYLON.SmartArray(16);
  12559. this._uniqueIdCounter = 0;
  12560. this._engine = engine;
  12561. engine.scenes.push(this);
  12562. this._renderingManager = new BABYLON.RenderingManager(this);
  12563. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12564. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12565. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12566. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12567. this.attachControl();
  12568. this._debugLayer = new BABYLON.DebugLayer(this);
  12569. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12570. //simplification queue
  12571. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12572. //collision coordinator initialization. For now legacy per default.
  12573. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12574. }
  12575. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12576. get: function () {
  12577. return Scene._FOGMODE_NONE;
  12578. },
  12579. enumerable: true,
  12580. configurable: true
  12581. });
  12582. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12583. get: function () {
  12584. return Scene._FOGMODE_EXP;
  12585. },
  12586. enumerable: true,
  12587. configurable: true
  12588. });
  12589. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12590. get: function () {
  12591. return Scene._FOGMODE_EXP2;
  12592. },
  12593. enumerable: true,
  12594. configurable: true
  12595. });
  12596. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12597. get: function () {
  12598. return Scene._FOGMODE_LINEAR;
  12599. },
  12600. enumerable: true,
  12601. configurable: true
  12602. });
  12603. Object.defineProperty(Scene.prototype, "debugLayer", {
  12604. // Properties
  12605. get: function () {
  12606. return this._debugLayer;
  12607. },
  12608. enumerable: true,
  12609. configurable: true
  12610. });
  12611. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12612. get: function () {
  12613. return this._workerCollisions;
  12614. },
  12615. set: function (enabled) {
  12616. enabled = (enabled && !!Worker);
  12617. this._workerCollisions = enabled;
  12618. if (this.collisionCoordinator) {
  12619. this.collisionCoordinator.destroy();
  12620. }
  12621. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12622. this.collisionCoordinator.init(this);
  12623. },
  12624. enumerable: true,
  12625. configurable: true
  12626. });
  12627. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12628. get: function () {
  12629. return this._selectionOctree;
  12630. },
  12631. enumerable: true,
  12632. configurable: true
  12633. });
  12634. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12635. /**
  12636. * The mesh that is currently under the pointer.
  12637. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12638. */
  12639. get: function () {
  12640. return this._meshUnderPointer;
  12641. },
  12642. enumerable: true,
  12643. configurable: true
  12644. });
  12645. Object.defineProperty(Scene.prototype, "pointerX", {
  12646. /**
  12647. * Current on-screen X position of the pointer
  12648. * @return {number} X position of the pointer
  12649. */
  12650. get: function () {
  12651. return this._pointerX;
  12652. },
  12653. enumerable: true,
  12654. configurable: true
  12655. });
  12656. Object.defineProperty(Scene.prototype, "pointerY", {
  12657. /**
  12658. * Current on-screen Y position of the pointer
  12659. * @return {number} Y position of the pointer
  12660. */
  12661. get: function () {
  12662. return this._pointerY;
  12663. },
  12664. enumerable: true,
  12665. configurable: true
  12666. });
  12667. Scene.prototype.getCachedMaterial = function () {
  12668. return this._cachedMaterial;
  12669. };
  12670. Scene.prototype.getBoundingBoxRenderer = function () {
  12671. return this._boundingBoxRenderer;
  12672. };
  12673. Scene.prototype.getOutlineRenderer = function () {
  12674. return this._outlineRenderer;
  12675. };
  12676. Scene.prototype.getEngine = function () {
  12677. return this._engine;
  12678. };
  12679. Scene.prototype.getTotalVertices = function () {
  12680. return this._totalVertices;
  12681. };
  12682. Scene.prototype.getActiveIndices = function () {
  12683. return this._activeIndices;
  12684. };
  12685. Scene.prototype.getActiveParticles = function () {
  12686. return this._activeParticles;
  12687. };
  12688. Scene.prototype.getActiveBones = function () {
  12689. return this._activeBones;
  12690. };
  12691. // Stats
  12692. Scene.prototype.getLastFrameDuration = function () {
  12693. return this._lastFrameDuration;
  12694. };
  12695. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12696. return this._evaluateActiveMeshesDuration;
  12697. };
  12698. Scene.prototype.getActiveMeshes = function () {
  12699. return this._activeMeshes;
  12700. };
  12701. Scene.prototype.getRenderTargetsDuration = function () {
  12702. return this._renderTargetsDuration;
  12703. };
  12704. Scene.prototype.getRenderDuration = function () {
  12705. return this._renderDuration;
  12706. };
  12707. Scene.prototype.getParticlesDuration = function () {
  12708. return this._particlesDuration;
  12709. };
  12710. Scene.prototype.getSpritesDuration = function () {
  12711. return this._spritesDuration;
  12712. };
  12713. Scene.prototype.getAnimationRatio = function () {
  12714. return this._animationRatio;
  12715. };
  12716. Scene.prototype.getRenderId = function () {
  12717. return this._renderId;
  12718. };
  12719. Scene.prototype.incrementRenderId = function () {
  12720. this._renderId++;
  12721. };
  12722. Scene.prototype._updatePointerPosition = function (evt) {
  12723. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12724. this._pointerX = evt.clientX - canvasRect.left;
  12725. this._pointerY = evt.clientY - canvasRect.top;
  12726. if (this.cameraToUseForPointers) {
  12727. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12728. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12729. }
  12730. };
  12731. // Pointers handling
  12732. Scene.prototype.attachControl = function () {
  12733. var _this = this;
  12734. var spritePredicate = function (sprite) {
  12735. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12736. };
  12737. this._onPointerMove = function (evt) {
  12738. var canvas = _this._engine.getRenderingCanvas();
  12739. _this._updatePointerPosition(evt);
  12740. // Meshes
  12741. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12742. if (pickResult.hit && pickResult.pickedMesh) {
  12743. _this._meshUnderPointer = pickResult.pickedMesh;
  12744. _this.setPointerOverMesh(pickResult.pickedMesh);
  12745. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12746. canvas.style.cursor = "pointer";
  12747. }
  12748. else {
  12749. canvas.style.cursor = "";
  12750. }
  12751. }
  12752. else {
  12753. // Sprites
  12754. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12755. if (pickResult.hit && pickResult.pickedSprite) {
  12756. canvas.style.cursor = "pointer";
  12757. return;
  12758. }
  12759. // Restore pointer
  12760. _this.setPointerOverMesh(null);
  12761. canvas.style.cursor = "";
  12762. _this._meshUnderPointer = null;
  12763. }
  12764. };
  12765. this._onPointerDown = function (evt) {
  12766. _this._updatePointerPosition(evt);
  12767. var predicate = null;
  12768. // Meshes
  12769. if (!_this.onPointerDown) {
  12770. predicate = function (mesh) {
  12771. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12772. };
  12773. }
  12774. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12775. if (pickResult.hit && pickResult.pickedMesh) {
  12776. if (pickResult.pickedMesh.actionManager) {
  12777. switch (evt.button) {
  12778. case 0:
  12779. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12780. break;
  12781. case 1:
  12782. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12783. break;
  12784. case 2:
  12785. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12786. break;
  12787. }
  12788. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12789. }
  12790. }
  12791. if (_this.onPointerDown) {
  12792. _this.onPointerDown(evt, pickResult);
  12793. }
  12794. // Sprites
  12795. if (_this.spriteManagers.length > 0) {
  12796. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12797. if (pickResult.hit && pickResult.pickedSprite) {
  12798. if (pickResult.pickedSprite.actionManager) {
  12799. switch (evt.button) {
  12800. case 0:
  12801. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12802. break;
  12803. case 1:
  12804. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12805. break;
  12806. case 2:
  12807. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12808. break;
  12809. }
  12810. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12811. }
  12812. }
  12813. }
  12814. };
  12815. this._onPointerUp = function (evt) {
  12816. var predicate = null;
  12817. _this._updatePointerPosition(evt);
  12818. if (!_this.onPointerUp) {
  12819. predicate = function (mesh) {
  12820. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12821. };
  12822. }
  12823. // Meshes
  12824. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12825. if (pickResult.hit && pickResult.pickedMesh) {
  12826. if (pickResult.pickedMesh.actionManager) {
  12827. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12828. }
  12829. }
  12830. if (_this.onPointerUp) {
  12831. _this.onPointerUp(evt, pickResult);
  12832. }
  12833. // Sprites
  12834. if (_this.spriteManagers.length > 0) {
  12835. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12836. if (pickResult.hit && pickResult.pickedSprite) {
  12837. if (pickResult.pickedSprite.actionManager) {
  12838. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12839. }
  12840. }
  12841. }
  12842. };
  12843. this._onKeyDown = function (evt) {
  12844. if (_this.actionManager) {
  12845. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12846. }
  12847. };
  12848. this._onKeyUp = function (evt) {
  12849. if (_this.actionManager) {
  12850. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12851. }
  12852. };
  12853. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12854. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12855. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12856. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12857. // Wheel
  12858. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12859. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12860. BABYLON.Tools.RegisterTopRootEvents([
  12861. { name: "keydown", handler: this._onKeyDown },
  12862. { name: "keyup", handler: this._onKeyUp }
  12863. ]);
  12864. };
  12865. Scene.prototype.detachControl = function () {
  12866. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12867. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12868. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12869. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12870. // Wheel
  12871. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12872. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12873. BABYLON.Tools.UnregisterTopRootEvents([
  12874. { name: "keydown", handler: this._onKeyDown },
  12875. { name: "keyup", handler: this._onKeyUp }
  12876. ]);
  12877. };
  12878. // Ready
  12879. Scene.prototype.isReady = function () {
  12880. if (this._pendingData.length > 0) {
  12881. return false;
  12882. }
  12883. var index;
  12884. for (index = 0; index < this._geometries.length; index++) {
  12885. var geometry = this._geometries[index];
  12886. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12887. return false;
  12888. }
  12889. }
  12890. for (index = 0; index < this.meshes.length; index++) {
  12891. var mesh = this.meshes[index];
  12892. if (!mesh.isReady()) {
  12893. return false;
  12894. }
  12895. var mat = mesh.material;
  12896. if (mat) {
  12897. if (!mat.isReady(mesh)) {
  12898. return false;
  12899. }
  12900. }
  12901. }
  12902. return true;
  12903. };
  12904. Scene.prototype.resetCachedMaterial = function () {
  12905. this._cachedMaterial = null;
  12906. };
  12907. Scene.prototype.registerBeforeRender = function (func) {
  12908. this._onBeforeRenderCallbacks.push(func);
  12909. };
  12910. Scene.prototype.unregisterBeforeRender = function (func) {
  12911. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12912. if (index > -1) {
  12913. this._onBeforeRenderCallbacks.splice(index, 1);
  12914. }
  12915. };
  12916. Scene.prototype.registerAfterRender = function (func) {
  12917. this._onAfterRenderCallbacks.push(func);
  12918. };
  12919. Scene.prototype.unregisterAfterRender = function (func) {
  12920. var index = this._onAfterRenderCallbacks.indexOf(func);
  12921. if (index > -1) {
  12922. this._onAfterRenderCallbacks.splice(index, 1);
  12923. }
  12924. };
  12925. Scene.prototype._addPendingData = function (data) {
  12926. this._pendingData.push(data);
  12927. };
  12928. Scene.prototype._removePendingData = function (data) {
  12929. var index = this._pendingData.indexOf(data);
  12930. if (index !== -1) {
  12931. this._pendingData.splice(index, 1);
  12932. }
  12933. };
  12934. Scene.prototype.getWaitingItemsCount = function () {
  12935. return this._pendingData.length;
  12936. };
  12937. /**
  12938. * Registers a function to be executed when the scene is ready.
  12939. * @param {Function} func - the function to be executed.
  12940. */
  12941. Scene.prototype.executeWhenReady = function (func) {
  12942. var _this = this;
  12943. this._onReadyCallbacks.push(func);
  12944. if (this._executeWhenReadyTimeoutId !== -1) {
  12945. return;
  12946. }
  12947. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12948. _this._checkIsReady();
  12949. }, 150);
  12950. };
  12951. Scene.prototype._checkIsReady = function () {
  12952. var _this = this;
  12953. if (this.isReady()) {
  12954. this._onReadyCallbacks.forEach(function (func) {
  12955. func();
  12956. });
  12957. this._onReadyCallbacks = [];
  12958. this._executeWhenReadyTimeoutId = -1;
  12959. return;
  12960. }
  12961. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12962. _this._checkIsReady();
  12963. }, 150);
  12964. };
  12965. // Animations
  12966. /**
  12967. * Will start the animation sequence of a given target
  12968. * @param target - the target
  12969. * @param {number} from - from which frame should animation start
  12970. * @param {number} to - till which frame should animation run.
  12971. * @param {boolean} [loop] - should the animation loop
  12972. * @param {number} [speedRatio] - the speed in which to run the animation
  12973. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12974. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12975. * @return {BABYLON.Animatable} the animatable object created for this animation
  12976. * @see BABYLON.Animatable
  12977. * @see http://doc.babylonjs.com/page.php?p=22081
  12978. */
  12979. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12980. if (speedRatio === void 0) { speedRatio = 1.0; }
  12981. this.stopAnimation(target);
  12982. if (!animatable) {
  12983. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12984. }
  12985. // Local animations
  12986. if (target.animations) {
  12987. animatable.appendAnimations(target, target.animations);
  12988. }
  12989. // Children animations
  12990. if (target.getAnimatables) {
  12991. var animatables = target.getAnimatables();
  12992. for (var index = 0; index < animatables.length; index++) {
  12993. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12994. }
  12995. }
  12996. return animatable;
  12997. };
  12998. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12999. if (speedRatio === undefined) {
  13000. speedRatio = 1.0;
  13001. }
  13002. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  13003. return animatable;
  13004. };
  13005. Scene.prototype.getAnimatableByTarget = function (target) {
  13006. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13007. if (this._activeAnimatables[index].target === target) {
  13008. return this._activeAnimatables[index];
  13009. }
  13010. }
  13011. return null;
  13012. };
  13013. /**
  13014. * Will stop the animation of the given target
  13015. * @param target - the target
  13016. * @see beginAnimation
  13017. */
  13018. Scene.prototype.stopAnimation = function (target) {
  13019. var animatable = this.getAnimatableByTarget(target);
  13020. if (animatable) {
  13021. animatable.stop();
  13022. }
  13023. };
  13024. Scene.prototype._animate = function () {
  13025. if (!this.animationsEnabled) {
  13026. return;
  13027. }
  13028. if (!this._animationStartDate) {
  13029. this._animationStartDate = BABYLON.Tools.Now;
  13030. }
  13031. // Getting time
  13032. var now = BABYLON.Tools.Now;
  13033. var delay = now - this._animationStartDate;
  13034. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13035. this._activeAnimatables[index]._animate(delay);
  13036. }
  13037. };
  13038. // Matrix
  13039. Scene.prototype.getViewMatrix = function () {
  13040. return this._viewMatrix;
  13041. };
  13042. Scene.prototype.getProjectionMatrix = function () {
  13043. return this._projectionMatrix;
  13044. };
  13045. Scene.prototype.getTransformMatrix = function () {
  13046. return this._transformMatrix;
  13047. };
  13048. Scene.prototype.setTransformMatrix = function (view, projection) {
  13049. this._viewMatrix = view;
  13050. this._projectionMatrix = projection;
  13051. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13052. };
  13053. // Methods
  13054. Scene.prototype.addMesh = function (newMesh) {
  13055. newMesh.uniqueId = this._uniqueIdCounter++;
  13056. var position = this.meshes.push(newMesh);
  13057. //notify the collision coordinator
  13058. this.collisionCoordinator.onMeshAdded(newMesh);
  13059. if (this.onNewMeshAdded) {
  13060. this.onNewMeshAdded(newMesh, position, this);
  13061. }
  13062. };
  13063. Scene.prototype.removeMesh = function (toRemove) {
  13064. var index = this.meshes.indexOf(toRemove);
  13065. if (index !== -1) {
  13066. // Remove from the scene if mesh found
  13067. this.meshes.splice(index, 1);
  13068. }
  13069. //notify the collision coordinator
  13070. this.collisionCoordinator.onMeshRemoved(toRemove);
  13071. if (this.onMeshRemoved) {
  13072. this.onMeshRemoved(toRemove);
  13073. }
  13074. return index;
  13075. };
  13076. Scene.prototype.removeLight = function (toRemove) {
  13077. var index = this.lights.indexOf(toRemove);
  13078. if (index !== -1) {
  13079. // Remove from the scene if mesh found
  13080. this.lights.splice(index, 1);
  13081. }
  13082. if (this.onLightRemoved) {
  13083. this.onLightRemoved(toRemove);
  13084. }
  13085. return index;
  13086. };
  13087. Scene.prototype.removeCamera = function (toRemove) {
  13088. var index = this.cameras.indexOf(toRemove);
  13089. if (index !== -1) {
  13090. // Remove from the scene if mesh found
  13091. this.cameras.splice(index, 1);
  13092. }
  13093. // Remove from activeCameras
  13094. var index2 = this.activeCameras.indexOf(toRemove);
  13095. if (index2 !== -1) {
  13096. // Remove from the scene if mesh found
  13097. this.activeCameras.splice(index2, 1);
  13098. }
  13099. // Reset the activeCamera
  13100. if (this.activeCamera === toRemove) {
  13101. if (this.cameras.length > 0) {
  13102. this.activeCamera = this.cameras[0];
  13103. }
  13104. else {
  13105. this.activeCamera = null;
  13106. }
  13107. }
  13108. if (this.onCameraRemoved) {
  13109. this.onCameraRemoved(toRemove);
  13110. }
  13111. return index;
  13112. };
  13113. Scene.prototype.addLight = function (newLight) {
  13114. newLight.uniqueId = this._uniqueIdCounter++;
  13115. var position = this.lights.push(newLight);
  13116. if (this.onNewLightAdded) {
  13117. this.onNewLightAdded(newLight, position, this);
  13118. }
  13119. };
  13120. Scene.prototype.addCamera = function (newCamera) {
  13121. newCamera.uniqueId = this._uniqueIdCounter++;
  13122. var position = this.cameras.push(newCamera);
  13123. if (this.onNewCameraAdded) {
  13124. this.onNewCameraAdded(newCamera, position, this);
  13125. }
  13126. };
  13127. /**
  13128. * sets the active camera of the scene using its ID
  13129. * @param {string} id - the camera's ID
  13130. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13131. * @see activeCamera
  13132. */
  13133. Scene.prototype.setActiveCameraByID = function (id) {
  13134. var camera = this.getCameraByID(id);
  13135. if (camera) {
  13136. this.activeCamera = camera;
  13137. return camera;
  13138. }
  13139. return null;
  13140. };
  13141. /**
  13142. * sets the active camera of the scene using its name
  13143. * @param {string} name - the camera's name
  13144. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13145. * @see activeCamera
  13146. */
  13147. Scene.prototype.setActiveCameraByName = function (name) {
  13148. var camera = this.getCameraByName(name);
  13149. if (camera) {
  13150. this.activeCamera = camera;
  13151. return camera;
  13152. }
  13153. return null;
  13154. };
  13155. /**
  13156. * get a material using its id
  13157. * @param {string} the material's ID
  13158. * @return {BABYLON.Material|null} the material or null if none found.
  13159. */
  13160. Scene.prototype.getMaterialByID = function (id) {
  13161. for (var index = 0; index < this.materials.length; index++) {
  13162. if (this.materials[index].id === id) {
  13163. return this.materials[index];
  13164. }
  13165. }
  13166. return null;
  13167. };
  13168. /**
  13169. * get a material using its name
  13170. * @param {string} the material's name
  13171. * @return {BABYLON.Material|null} the material or null if none found.
  13172. */
  13173. Scene.prototype.getMaterialByName = function (name) {
  13174. for (var index = 0; index < this.materials.length; index++) {
  13175. if (this.materials[index].name === name) {
  13176. return this.materials[index];
  13177. }
  13178. }
  13179. return null;
  13180. };
  13181. Scene.prototype.getLensFlareSystemByName = function (name) {
  13182. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13183. if (this.lensFlareSystems[index].name === name) {
  13184. return this.lensFlareSystems[index];
  13185. }
  13186. }
  13187. return null;
  13188. };
  13189. Scene.prototype.getCameraByID = function (id) {
  13190. for (var index = 0; index < this.cameras.length; index++) {
  13191. if (this.cameras[index].id === id) {
  13192. return this.cameras[index];
  13193. }
  13194. }
  13195. return null;
  13196. };
  13197. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13198. for (var index = 0; index < this.cameras.length; index++) {
  13199. if (this.cameras[index].uniqueId === uniqueId) {
  13200. return this.cameras[index];
  13201. }
  13202. }
  13203. return null;
  13204. };
  13205. /**
  13206. * get a camera using its name
  13207. * @param {string} the camera's name
  13208. * @return {BABYLON.Camera|null} the camera or null if none found.
  13209. */
  13210. Scene.prototype.getCameraByName = function (name) {
  13211. for (var index = 0; index < this.cameras.length; index++) {
  13212. if (this.cameras[index].name === name) {
  13213. return this.cameras[index];
  13214. }
  13215. }
  13216. return null;
  13217. };
  13218. /**
  13219. * get a light node using its name
  13220. * @param {string} the light's name
  13221. * @return {BABYLON.Light|null} the light or null if none found.
  13222. */
  13223. Scene.prototype.getLightByName = function (name) {
  13224. for (var index = 0; index < this.lights.length; index++) {
  13225. if (this.lights[index].name === name) {
  13226. return this.lights[index];
  13227. }
  13228. }
  13229. return null;
  13230. };
  13231. /**
  13232. * get a light node using its ID
  13233. * @param {string} the light's id
  13234. * @return {BABYLON.Light|null} the light or null if none found.
  13235. */
  13236. Scene.prototype.getLightByID = function (id) {
  13237. for (var index = 0; index < this.lights.length; index++) {
  13238. if (this.lights[index].id === id) {
  13239. return this.lights[index];
  13240. }
  13241. }
  13242. return null;
  13243. };
  13244. /**
  13245. * get a light node using its scene-generated unique ID
  13246. * @param {number} the light's unique id
  13247. * @return {BABYLON.Light|null} the light or null if none found.
  13248. */
  13249. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13250. for (var index = 0; index < this.lights.length; index++) {
  13251. if (this.lights[index].uniqueId === uniqueId) {
  13252. return this.lights[index];
  13253. }
  13254. }
  13255. return null;
  13256. };
  13257. /**
  13258. * get a geometry using its ID
  13259. * @param {string} the geometry's id
  13260. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13261. */
  13262. Scene.prototype.getGeometryByID = function (id) {
  13263. for (var index = 0; index < this._geometries.length; index++) {
  13264. if (this._geometries[index].id === id) {
  13265. return this._geometries[index];
  13266. }
  13267. }
  13268. return null;
  13269. };
  13270. /**
  13271. * add a new geometry to this scene.
  13272. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13273. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13274. * @return {boolean} was the geometry added or not
  13275. */
  13276. Scene.prototype.pushGeometry = function (geometry, force) {
  13277. if (!force && this.getGeometryByID(geometry.id)) {
  13278. return false;
  13279. }
  13280. this._geometries.push(geometry);
  13281. //notify the collision coordinator
  13282. this.collisionCoordinator.onGeometryAdded(geometry);
  13283. if (this.onGeometryAdded) {
  13284. this.onGeometryAdded(geometry);
  13285. }
  13286. return true;
  13287. };
  13288. /**
  13289. * Removes an existing geometry
  13290. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13291. * @return {boolean} was the geometry removed or not
  13292. */
  13293. Scene.prototype.removeGeometry = function (geometry) {
  13294. var index = this._geometries.indexOf(geometry);
  13295. if (index > -1) {
  13296. this._geometries.splice(index, 1);
  13297. //notify the collision coordinator
  13298. this.collisionCoordinator.onGeometryDeleted(geometry);
  13299. if (this.onGeometryRemoved) {
  13300. this.onGeometryRemoved(geometry);
  13301. }
  13302. return true;
  13303. }
  13304. return false;
  13305. };
  13306. Scene.prototype.getGeometries = function () {
  13307. return this._geometries;
  13308. };
  13309. /**
  13310. * Get the first added mesh found of a given ID
  13311. * @param {string} id - the id to search for
  13312. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13313. */
  13314. Scene.prototype.getMeshByID = function (id) {
  13315. for (var index = 0; index < this.meshes.length; index++) {
  13316. if (this.meshes[index].id === id) {
  13317. return this.meshes[index];
  13318. }
  13319. }
  13320. return null;
  13321. };
  13322. /**
  13323. * Get a mesh with its auto-generated unique id
  13324. * @param {number} uniqueId - the unique id to search for
  13325. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13326. */
  13327. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13328. for (var index = 0; index < this.meshes.length; index++) {
  13329. if (this.meshes[index].uniqueId === uniqueId) {
  13330. return this.meshes[index];
  13331. }
  13332. }
  13333. return null;
  13334. };
  13335. /**
  13336. * Get a the last added mesh found of a given ID
  13337. * @param {string} id - the id to search for
  13338. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13339. */
  13340. Scene.prototype.getLastMeshByID = function (id) {
  13341. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13342. if (this.meshes[index].id === id) {
  13343. return this.meshes[index];
  13344. }
  13345. }
  13346. return null;
  13347. };
  13348. /**
  13349. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13350. * @param {string} id - the id to search for
  13351. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13352. */
  13353. Scene.prototype.getLastEntryByID = function (id) {
  13354. var index;
  13355. for (index = this.meshes.length - 1; index >= 0; index--) {
  13356. if (this.meshes[index].id === id) {
  13357. return this.meshes[index];
  13358. }
  13359. }
  13360. for (index = this.cameras.length - 1; index >= 0; index--) {
  13361. if (this.cameras[index].id === id) {
  13362. return this.cameras[index];
  13363. }
  13364. }
  13365. for (index = this.lights.length - 1; index >= 0; index--) {
  13366. if (this.lights[index].id === id) {
  13367. return this.lights[index];
  13368. }
  13369. }
  13370. return null;
  13371. };
  13372. Scene.prototype.getNodeByID = function (id) {
  13373. var mesh = this.getMeshByID(id);
  13374. if (mesh) {
  13375. return mesh;
  13376. }
  13377. var light = this.getLightByID(id);
  13378. if (light) {
  13379. return light;
  13380. }
  13381. return this.getCameraByID(id);
  13382. };
  13383. Scene.prototype.getNodeByName = function (name) {
  13384. var mesh = this.getMeshByName(name);
  13385. if (mesh) {
  13386. return mesh;
  13387. }
  13388. var light = this.getLightByName(name);
  13389. if (light) {
  13390. return light;
  13391. }
  13392. return this.getCameraByName(name);
  13393. };
  13394. Scene.prototype.getMeshByName = function (name) {
  13395. for (var index = 0; index < this.meshes.length; index++) {
  13396. if (this.meshes[index].name === name) {
  13397. return this.meshes[index];
  13398. }
  13399. }
  13400. return null;
  13401. };
  13402. Scene.prototype.getSoundByName = function (name) {
  13403. var index;
  13404. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13405. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13406. return this.mainSoundTrack.soundCollection[index];
  13407. }
  13408. }
  13409. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13410. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13411. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13412. return this.soundTracks[sdIndex].soundCollection[index];
  13413. }
  13414. }
  13415. }
  13416. return null;
  13417. };
  13418. Scene.prototype.getLastSkeletonByID = function (id) {
  13419. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13420. if (this.skeletons[index].id === id) {
  13421. return this.skeletons[index];
  13422. }
  13423. }
  13424. return null;
  13425. };
  13426. Scene.prototype.getSkeletonById = function (id) {
  13427. for (var index = 0; index < this.skeletons.length; index++) {
  13428. if (this.skeletons[index].id === id) {
  13429. return this.skeletons[index];
  13430. }
  13431. }
  13432. return null;
  13433. };
  13434. Scene.prototype.getSkeletonByName = function (name) {
  13435. for (var index = 0; index < this.skeletons.length; index++) {
  13436. if (this.skeletons[index].name === name) {
  13437. return this.skeletons[index];
  13438. }
  13439. }
  13440. return null;
  13441. };
  13442. Scene.prototype.isActiveMesh = function (mesh) {
  13443. return (this._activeMeshes.indexOf(mesh) !== -1);
  13444. };
  13445. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13446. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13447. var material = subMesh.getMaterial();
  13448. if (mesh.showSubMeshesBoundingBox) {
  13449. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13450. }
  13451. if (material) {
  13452. // Render targets
  13453. if (material.getRenderTargetTextures) {
  13454. if (this._processedMaterials.indexOf(material) === -1) {
  13455. this._processedMaterials.push(material);
  13456. this._renderTargets.concat(material.getRenderTargetTextures());
  13457. }
  13458. }
  13459. // Dispatch
  13460. this._activeIndices += subMesh.indexCount;
  13461. this._renderingManager.dispatch(subMesh);
  13462. }
  13463. }
  13464. };
  13465. Scene.prototype._evaluateActiveMeshes = function () {
  13466. this.activeCamera._activeMeshes.reset();
  13467. this._activeMeshes.reset();
  13468. this._renderingManager.reset();
  13469. this._processedMaterials.reset();
  13470. this._activeParticleSystems.reset();
  13471. this._activeSkeletons.reset();
  13472. this._softwareSkinnedMeshes.reset();
  13473. this._boundingBoxRenderer.reset();
  13474. this._edgesRenderers.reset();
  13475. if (!this._frustumPlanes) {
  13476. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13477. }
  13478. else {
  13479. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13480. }
  13481. // Meshes
  13482. var meshes;
  13483. var len;
  13484. if (this._selectionOctree) {
  13485. var selection = this._selectionOctree.select(this._frustumPlanes);
  13486. meshes = selection.data;
  13487. len = selection.length;
  13488. }
  13489. else {
  13490. len = this.meshes.length;
  13491. meshes = this.meshes;
  13492. }
  13493. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13494. var mesh = meshes[meshIndex];
  13495. if (mesh.isBlocked) {
  13496. continue;
  13497. }
  13498. this._totalVertices += mesh.getTotalVertices();
  13499. if (!mesh.isReady() || !mesh.isEnabled()) {
  13500. continue;
  13501. }
  13502. mesh.computeWorldMatrix();
  13503. // Intersections
  13504. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13505. this._meshesForIntersections.pushNoDuplicate(mesh);
  13506. }
  13507. // Switch to current LOD
  13508. var meshLOD = mesh.getLOD(this.activeCamera);
  13509. if (!meshLOD) {
  13510. continue;
  13511. }
  13512. mesh._preActivate();
  13513. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13514. this._activeMeshes.push(mesh);
  13515. this.activeCamera._activeMeshes.push(mesh);
  13516. mesh._activate(this._renderId);
  13517. this._activeMesh(meshLOD);
  13518. }
  13519. }
  13520. // Particle systems
  13521. var beforeParticlesDate = BABYLON.Tools.Now;
  13522. if (this.particlesEnabled) {
  13523. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13524. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13525. var particleSystem = this.particleSystems[particleIndex];
  13526. if (!particleSystem.isStarted()) {
  13527. continue;
  13528. }
  13529. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13530. this._activeParticleSystems.push(particleSystem);
  13531. particleSystem.animate();
  13532. }
  13533. }
  13534. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13535. }
  13536. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13537. };
  13538. Scene.prototype._activeMesh = function (mesh) {
  13539. if (mesh.skeleton && this.skeletonsEnabled) {
  13540. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13541. if (!mesh.computeBonesUsingShaders) {
  13542. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13543. }
  13544. }
  13545. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13546. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13547. }
  13548. if (mesh._edgesRenderer) {
  13549. this._edgesRenderers.push(mesh._edgesRenderer);
  13550. }
  13551. if (mesh && mesh.subMeshes) {
  13552. // Submeshes Octrees
  13553. var len;
  13554. var subMeshes;
  13555. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13556. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13557. len = intersections.length;
  13558. subMeshes = intersections.data;
  13559. }
  13560. else {
  13561. subMeshes = mesh.subMeshes;
  13562. len = subMeshes.length;
  13563. }
  13564. for (var subIndex = 0; subIndex < len; subIndex++) {
  13565. var subMesh = subMeshes[subIndex];
  13566. this._evaluateSubMesh(subMesh, mesh);
  13567. }
  13568. }
  13569. };
  13570. Scene.prototype.updateTransformMatrix = function (force) {
  13571. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13572. };
  13573. Scene.prototype._renderForCamera = function (camera) {
  13574. var engine = this._engine;
  13575. this.activeCamera = camera;
  13576. if (!this.activeCamera)
  13577. throw new Error("Active camera not set");
  13578. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13579. // Viewport
  13580. engine.setViewport(this.activeCamera.viewport);
  13581. // Camera
  13582. this.resetCachedMaterial();
  13583. this._renderId++;
  13584. this.updateTransformMatrix();
  13585. if (this.beforeCameraRender) {
  13586. this.beforeCameraRender(this.activeCamera);
  13587. }
  13588. // Meshes
  13589. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13590. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13591. this._evaluateActiveMeshes();
  13592. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13593. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13594. // Skeletons
  13595. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13596. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13597. skeleton.prepare();
  13598. }
  13599. // Software skinning
  13600. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13601. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13602. mesh.applySkeleton(mesh.skeleton);
  13603. }
  13604. // Render targets
  13605. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13606. if (this.renderTargetsEnabled) {
  13607. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13608. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13609. var renderTarget = this._renderTargets.data[renderIndex];
  13610. if (renderTarget._shouldRender()) {
  13611. this._renderId++;
  13612. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13613. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13614. }
  13615. }
  13616. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13617. this._renderId++;
  13618. }
  13619. if (this._renderTargets.length > 0) {
  13620. engine.restoreDefaultFramebuffer();
  13621. }
  13622. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13623. // Prepare Frame
  13624. this.postProcessManager._prepareFrame();
  13625. var beforeRenderDate = BABYLON.Tools.Now;
  13626. // Backgrounds
  13627. var layerIndex;
  13628. var layer;
  13629. if (this.layers.length) {
  13630. engine.setDepthBuffer(false);
  13631. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13632. layer = this.layers[layerIndex];
  13633. if (layer.isBackground) {
  13634. layer.render();
  13635. }
  13636. }
  13637. engine.setDepthBuffer(true);
  13638. }
  13639. // Render
  13640. BABYLON.Tools.StartPerformanceCounter("Main render");
  13641. this._renderingManager.render(null, null, true, true);
  13642. BABYLON.Tools.EndPerformanceCounter("Main render");
  13643. // Bounding boxes
  13644. this._boundingBoxRenderer.render();
  13645. // Edges
  13646. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13647. this._edgesRenderers.data[edgesRendererIndex].render();
  13648. }
  13649. // Lens flares
  13650. if (this.lensFlaresEnabled) {
  13651. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13652. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13653. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13654. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13655. lensFlareSystem.render();
  13656. }
  13657. }
  13658. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13659. }
  13660. // Foregrounds
  13661. if (this.layers.length) {
  13662. engine.setDepthBuffer(false);
  13663. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13664. layer = this.layers[layerIndex];
  13665. if (!layer.isBackground) {
  13666. layer.render();
  13667. }
  13668. }
  13669. engine.setDepthBuffer(true);
  13670. }
  13671. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13672. // Finalize frame
  13673. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13674. // Update camera
  13675. this.activeCamera._updateFromScene();
  13676. // Reset some special arrays
  13677. this._renderTargets.reset();
  13678. if (this.afterCameraRender) {
  13679. this.afterCameraRender(this.activeCamera);
  13680. }
  13681. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13682. };
  13683. Scene.prototype._processSubCameras = function (camera) {
  13684. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13685. this._renderForCamera(camera);
  13686. return;
  13687. }
  13688. // rig cameras
  13689. for (var index = 0; index < camera._rigCameras.length; index++) {
  13690. this._renderForCamera(camera._rigCameras[index]);
  13691. }
  13692. this.activeCamera = camera;
  13693. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13694. // Update camera
  13695. this.activeCamera._updateFromScene();
  13696. };
  13697. Scene.prototype._checkIntersections = function () {
  13698. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13699. var sourceMesh = this._meshesForIntersections.data[index];
  13700. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13701. var action = sourceMesh.actionManager.actions[actionIndex];
  13702. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13703. var parameters = action.getTriggerParameter();
  13704. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13705. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13706. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13707. if (areIntersecting && currentIntersectionInProgress === -1) {
  13708. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13709. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13710. sourceMesh._intersectionsInProgress.push(otherMesh);
  13711. }
  13712. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13713. sourceMesh._intersectionsInProgress.push(otherMesh);
  13714. }
  13715. }
  13716. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13717. //They intersected, and now they don't.
  13718. //is this trigger an exit trigger? execute an event.
  13719. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13720. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13721. }
  13722. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13723. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13724. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13725. }
  13726. }
  13727. }
  13728. }
  13729. }
  13730. };
  13731. Scene.prototype.render = function () {
  13732. var startDate = BABYLON.Tools.Now;
  13733. this._particlesDuration = 0;
  13734. this._spritesDuration = 0;
  13735. this._activeParticles = 0;
  13736. this._renderDuration = 0;
  13737. this._renderTargetsDuration = 0;
  13738. this._evaluateActiveMeshesDuration = 0;
  13739. this._totalVertices = 0;
  13740. this._activeIndices = 0;
  13741. this._activeBones = 0;
  13742. this.getEngine().resetDrawCalls();
  13743. this._meshesForIntersections.reset();
  13744. this.resetCachedMaterial();
  13745. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13746. // Actions
  13747. if (this.actionManager) {
  13748. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13749. }
  13750. //Simplification Queue
  13751. if (!this.simplificationQueue.running) {
  13752. this.simplificationQueue.executeNext();
  13753. }
  13754. // Animations
  13755. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13756. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13757. this._animate();
  13758. // Physics
  13759. if (this._physicsEngine) {
  13760. BABYLON.Tools.StartPerformanceCounter("Physics");
  13761. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13762. BABYLON.Tools.EndPerformanceCounter("Physics");
  13763. }
  13764. // Before render
  13765. if (this.beforeRender) {
  13766. this.beforeRender();
  13767. }
  13768. var callbackIndex;
  13769. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13770. this._onBeforeRenderCallbacks[callbackIndex]();
  13771. }
  13772. // Customs render targets
  13773. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13774. var engine = this.getEngine();
  13775. var currentActiveCamera = this.activeCamera;
  13776. if (this.renderTargetsEnabled) {
  13777. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13778. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13779. var renderTarget = this.customRenderTargets[customIndex];
  13780. if (renderTarget._shouldRender()) {
  13781. this._renderId++;
  13782. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13783. if (!this.activeCamera)
  13784. throw new Error("Active camera not set");
  13785. // Viewport
  13786. engine.setViewport(this.activeCamera.viewport);
  13787. // Camera
  13788. this.updateTransformMatrix();
  13789. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13790. }
  13791. }
  13792. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13793. this._renderId++;
  13794. }
  13795. if (this.customRenderTargets.length > 0) {
  13796. engine.restoreDefaultFramebuffer();
  13797. }
  13798. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13799. this.activeCamera = currentActiveCamera;
  13800. // Procedural textures
  13801. if (this.proceduralTexturesEnabled) {
  13802. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13803. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13804. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13805. if (proceduralTexture._shouldRender()) {
  13806. proceduralTexture.render();
  13807. }
  13808. }
  13809. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13810. }
  13811. // Clear
  13812. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13813. // Shadows
  13814. if (this.shadowsEnabled) {
  13815. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13816. var light = this.lights[lightIndex];
  13817. var shadowGenerator = light.getShadowGenerator();
  13818. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13819. this._renderTargets.push(shadowGenerator.getShadowMap());
  13820. }
  13821. }
  13822. }
  13823. // Depth renderer
  13824. if (this._depthRenderer) {
  13825. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13826. }
  13827. // RenderPipeline
  13828. this.postProcessRenderPipelineManager.update();
  13829. // Multi-cameras?
  13830. if (this.activeCameras.length > 0) {
  13831. var currentRenderId = this._renderId;
  13832. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13833. this._renderId = currentRenderId;
  13834. this._processSubCameras(this.activeCameras[cameraIndex]);
  13835. }
  13836. }
  13837. else {
  13838. if (!this.activeCamera) {
  13839. throw new Error("No camera defined");
  13840. }
  13841. this._processSubCameras(this.activeCamera);
  13842. }
  13843. // Intersection checks
  13844. this._checkIntersections();
  13845. // Update the audio listener attached to the camera
  13846. this._updateAudioParameters();
  13847. // After render
  13848. if (this.afterRender) {
  13849. this.afterRender();
  13850. }
  13851. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13852. this._onAfterRenderCallbacks[callbackIndex]();
  13853. }
  13854. // Cleaning
  13855. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13856. this._toBeDisposed.data[index].dispose();
  13857. this._toBeDisposed[index] = null;
  13858. }
  13859. this._toBeDisposed.reset();
  13860. if (this.dumpNextRenderTargets) {
  13861. this.dumpNextRenderTargets = false;
  13862. }
  13863. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13864. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13865. };
  13866. Scene.prototype._updateAudioParameters = function () {
  13867. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13868. return;
  13869. }
  13870. var listeningCamera;
  13871. var audioEngine = BABYLON.Engine.audioEngine;
  13872. if (this.activeCameras.length > 0) {
  13873. listeningCamera = this.activeCameras[0];
  13874. }
  13875. else {
  13876. listeningCamera = this.activeCamera;
  13877. }
  13878. if (listeningCamera && audioEngine.canUseWebAudio) {
  13879. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13880. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13881. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13882. cameraDirection.normalize();
  13883. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13884. var i;
  13885. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13886. var sound = this.mainSoundTrack.soundCollection[i];
  13887. if (sound.useCustomAttenuation) {
  13888. sound.updateDistanceFromListener();
  13889. }
  13890. }
  13891. for (i = 0; i < this.soundTracks.length; i++) {
  13892. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13893. sound = this.soundTracks[i].soundCollection[j];
  13894. if (sound.useCustomAttenuation) {
  13895. sound.updateDistanceFromListener();
  13896. }
  13897. }
  13898. }
  13899. }
  13900. };
  13901. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13902. // Audio
  13903. get: function () {
  13904. return this._audioEnabled;
  13905. },
  13906. set: function (value) {
  13907. this._audioEnabled = value;
  13908. if (this._audioEnabled) {
  13909. this._enableAudio();
  13910. }
  13911. else {
  13912. this._disableAudio();
  13913. }
  13914. },
  13915. enumerable: true,
  13916. configurable: true
  13917. });
  13918. Scene.prototype._disableAudio = function () {
  13919. var i;
  13920. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13921. this.mainSoundTrack.soundCollection[i].pause();
  13922. }
  13923. for (i = 0; i < this.soundTracks.length; i++) {
  13924. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13925. this.soundTracks[i].soundCollection[j].pause();
  13926. }
  13927. }
  13928. };
  13929. Scene.prototype._enableAudio = function () {
  13930. var i;
  13931. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13932. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13933. this.mainSoundTrack.soundCollection[i].play();
  13934. }
  13935. }
  13936. for (i = 0; i < this.soundTracks.length; i++) {
  13937. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13938. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13939. this.soundTracks[i].soundCollection[j].play();
  13940. }
  13941. }
  13942. }
  13943. };
  13944. Object.defineProperty(Scene.prototype, "headphone", {
  13945. get: function () {
  13946. return this._headphone;
  13947. },
  13948. set: function (value) {
  13949. this._headphone = value;
  13950. if (this._headphone) {
  13951. this._switchAudioModeForHeadphones();
  13952. }
  13953. else {
  13954. this._switchAudioModeForNormalSpeakers();
  13955. }
  13956. },
  13957. enumerable: true,
  13958. configurable: true
  13959. });
  13960. Scene.prototype._switchAudioModeForHeadphones = function () {
  13961. this.mainSoundTrack.switchPanningModelToHRTF();
  13962. for (var i = 0; i < this.soundTracks.length; i++) {
  13963. this.soundTracks[i].switchPanningModelToHRTF();
  13964. }
  13965. };
  13966. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13967. this.mainSoundTrack.switchPanningModelToEqualPower();
  13968. for (var i = 0; i < this.soundTracks.length; i++) {
  13969. this.soundTracks[i].switchPanningModelToEqualPower();
  13970. }
  13971. };
  13972. Scene.prototype.enableDepthRenderer = function () {
  13973. if (this._depthRenderer) {
  13974. return this._depthRenderer;
  13975. }
  13976. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13977. return this._depthRenderer;
  13978. };
  13979. Scene.prototype.disableDepthRenderer = function () {
  13980. if (!this._depthRenderer) {
  13981. return;
  13982. }
  13983. this._depthRenderer.dispose();
  13984. this._depthRenderer = null;
  13985. };
  13986. Scene.prototype.dispose = function () {
  13987. this.beforeRender = null;
  13988. this.afterRender = null;
  13989. this.skeletons = [];
  13990. this._boundingBoxRenderer.dispose();
  13991. if (this._depthRenderer) {
  13992. this._depthRenderer.dispose();
  13993. }
  13994. // Debug layer
  13995. this.debugLayer.hide();
  13996. // Events
  13997. if (this.onDispose) {
  13998. this.onDispose();
  13999. }
  14000. this._onBeforeRenderCallbacks = [];
  14001. this._onAfterRenderCallbacks = [];
  14002. this.detachControl();
  14003. // Release sounds & sounds tracks
  14004. this.disposeSounds();
  14005. // Detach cameras
  14006. var canvas = this._engine.getRenderingCanvas();
  14007. var index;
  14008. for (index = 0; index < this.cameras.length; index++) {
  14009. this.cameras[index].detachControl(canvas);
  14010. }
  14011. // Release lights
  14012. while (this.lights.length) {
  14013. this.lights[0].dispose();
  14014. }
  14015. // Release meshes
  14016. while (this.meshes.length) {
  14017. this.meshes[0].dispose(true);
  14018. }
  14019. // Release cameras
  14020. while (this.cameras.length) {
  14021. this.cameras[0].dispose();
  14022. }
  14023. // Release materials
  14024. while (this.materials.length) {
  14025. this.materials[0].dispose();
  14026. }
  14027. // Release particles
  14028. while (this.particleSystems.length) {
  14029. this.particleSystems[0].dispose();
  14030. }
  14031. // Release sprites
  14032. while (this.spriteManagers.length) {
  14033. this.spriteManagers[0].dispose();
  14034. }
  14035. // Release layers
  14036. while (this.layers.length) {
  14037. this.layers[0].dispose();
  14038. }
  14039. // Release textures
  14040. while (this.textures.length) {
  14041. this.textures[0].dispose();
  14042. }
  14043. // Post-processes
  14044. this.postProcessManager.dispose();
  14045. // Physics
  14046. if (this._physicsEngine) {
  14047. this.disablePhysicsEngine();
  14048. }
  14049. // Remove from engine
  14050. index = this._engine.scenes.indexOf(this);
  14051. if (index > -1) {
  14052. this._engine.scenes.splice(index, 1);
  14053. }
  14054. this._engine.wipeCaches();
  14055. };
  14056. // Release sounds & sounds tracks
  14057. Scene.prototype.disposeSounds = function () {
  14058. this.mainSoundTrack.dispose();
  14059. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14060. this.soundTracks[scIndex].dispose();
  14061. }
  14062. };
  14063. // Octrees
  14064. Scene.prototype.getWorldExtends = function () {
  14065. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14066. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14067. for (var index = 0; index < this.meshes.length; index++) {
  14068. var mesh = this.meshes[index];
  14069. mesh.computeWorldMatrix(true);
  14070. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14071. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14072. BABYLON.Tools.CheckExtends(minBox, min, max);
  14073. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14074. }
  14075. return {
  14076. min: min,
  14077. max: max
  14078. };
  14079. };
  14080. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14081. if (maxCapacity === void 0) { maxCapacity = 64; }
  14082. if (maxDepth === void 0) { maxDepth = 2; }
  14083. if (!this._selectionOctree) {
  14084. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14085. }
  14086. var worldExtends = this.getWorldExtends();
  14087. // Update octree
  14088. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14089. return this._selectionOctree;
  14090. };
  14091. // Picking
  14092. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14093. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14094. var engine = this._engine;
  14095. if (!camera) {
  14096. if (!this.activeCamera)
  14097. throw new Error("Active camera not set");
  14098. camera = this.activeCamera;
  14099. }
  14100. var cameraViewport = camera.viewport;
  14101. var viewport = cameraViewport.toGlobal(engine);
  14102. // Moving coordinates to local viewport world
  14103. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14104. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14105. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14106. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14107. };
  14108. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14109. var engine = this._engine;
  14110. if (!camera) {
  14111. if (!this.activeCamera)
  14112. throw new Error("Active camera not set");
  14113. camera = this.activeCamera;
  14114. }
  14115. var cameraViewport = camera.viewport;
  14116. var viewport = cameraViewport.toGlobal(engine);
  14117. var identity = BABYLON.Matrix.Identity();
  14118. // Moving coordinates to local viewport world
  14119. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14120. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14121. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14122. };
  14123. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14124. var pickingInfo = null;
  14125. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14126. var mesh = this.meshes[meshIndex];
  14127. if (predicate) {
  14128. if (!predicate(mesh)) {
  14129. continue;
  14130. }
  14131. }
  14132. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14133. continue;
  14134. }
  14135. var world = mesh.getWorldMatrix();
  14136. var ray = rayFunction(world);
  14137. var result = mesh.intersects(ray, fastCheck);
  14138. if (!result || !result.hit)
  14139. continue;
  14140. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14141. continue;
  14142. pickingInfo = result;
  14143. if (fastCheck) {
  14144. break;
  14145. }
  14146. }
  14147. return pickingInfo || new BABYLON.PickingInfo();
  14148. };
  14149. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14150. var pickingInfo = null;
  14151. camera = camera || this.activeCamera;
  14152. if (this.spriteManagers.length > 0) {
  14153. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14154. var spriteManager = this.spriteManagers[spriteIndex];
  14155. if (!spriteManager.isPickable) {
  14156. continue;
  14157. }
  14158. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14159. if (!result || !result.hit)
  14160. continue;
  14161. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14162. continue;
  14163. pickingInfo = result;
  14164. if (fastCheck) {
  14165. break;
  14166. }
  14167. }
  14168. }
  14169. return pickingInfo || new BABYLON.PickingInfo();
  14170. };
  14171. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14172. var _this = this;
  14173. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14174. /// <param name="x">X position on screen</param>
  14175. /// <param name="y">Y position on screen</param>
  14176. /// <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>
  14177. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14178. /// <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>
  14179. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14180. };
  14181. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14182. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14183. /// <param name="x">X position on screen</param>
  14184. /// <param name="y">Y position on screen</param>
  14185. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  14186. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14187. /// <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>
  14188. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14189. };
  14190. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14191. var _this = this;
  14192. return this._internalPick(function (world) {
  14193. if (!_this._pickWithRayInverseMatrix) {
  14194. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14195. }
  14196. world.invertToRef(_this._pickWithRayInverseMatrix);
  14197. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14198. }, predicate, fastCheck);
  14199. };
  14200. Scene.prototype.setPointerOverMesh = function (mesh) {
  14201. if (this._pointerOverMesh === mesh) {
  14202. return;
  14203. }
  14204. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14205. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14206. }
  14207. this._pointerOverMesh = mesh;
  14208. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14209. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14210. }
  14211. };
  14212. Scene.prototype.getPointerOverMesh = function () {
  14213. return this._pointerOverMesh;
  14214. };
  14215. // Physics
  14216. Scene.prototype.getPhysicsEngine = function () {
  14217. return this._physicsEngine;
  14218. };
  14219. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14220. if (this._physicsEngine) {
  14221. return true;
  14222. }
  14223. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14224. if (!this._physicsEngine.isSupported()) {
  14225. this._physicsEngine = null;
  14226. return false;
  14227. }
  14228. this._physicsEngine._initialize(gravity);
  14229. return true;
  14230. };
  14231. Scene.prototype.disablePhysicsEngine = function () {
  14232. if (!this._physicsEngine) {
  14233. return;
  14234. }
  14235. this._physicsEngine.dispose();
  14236. this._physicsEngine = undefined;
  14237. };
  14238. Scene.prototype.isPhysicsEnabled = function () {
  14239. return this._physicsEngine !== undefined;
  14240. };
  14241. Scene.prototype.setGravity = function (gravity) {
  14242. if (!this._physicsEngine) {
  14243. return;
  14244. }
  14245. this._physicsEngine._setGravity(gravity);
  14246. };
  14247. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14248. if (parts.parts) {
  14249. options = parts;
  14250. parts = parts.parts;
  14251. }
  14252. if (!this._physicsEngine) {
  14253. return null;
  14254. }
  14255. for (var index = 0; index < parts.length; index++) {
  14256. var mesh = parts[index].mesh;
  14257. mesh._physicImpostor = parts[index].impostor;
  14258. mesh._physicsMass = options.mass / parts.length;
  14259. mesh._physicsFriction = options.friction;
  14260. mesh._physicRestitution = options.restitution;
  14261. }
  14262. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14263. };
  14264. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14265. for (var index = 0; index < compound.parts.length; index++) {
  14266. var mesh = compound.parts[index].mesh;
  14267. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14268. this._physicsEngine._unregisterMesh(mesh);
  14269. }
  14270. };
  14271. // Misc.
  14272. Scene.prototype.createDefaultCameraOrLight = function () {
  14273. // Light
  14274. if (this.lights.length === 0) {
  14275. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14276. }
  14277. // Camera
  14278. if (!this.activeCamera) {
  14279. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14280. // Compute position
  14281. var worldExtends = this.getWorldExtends();
  14282. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14283. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14284. camera.setTarget(worldCenter);
  14285. this.activeCamera = camera;
  14286. }
  14287. };
  14288. // Tags
  14289. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14290. if (tagsQuery === undefined) {
  14291. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14292. return list;
  14293. }
  14294. var listByTags = [];
  14295. forEach = forEach || (function (item) { return; });
  14296. for (var i in list) {
  14297. var item = list[i];
  14298. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14299. listByTags.push(item);
  14300. forEach(item);
  14301. }
  14302. }
  14303. return listByTags;
  14304. };
  14305. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14306. return this._getByTags(this.meshes, tagsQuery, forEach);
  14307. };
  14308. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14309. return this._getByTags(this.cameras, tagsQuery, forEach);
  14310. };
  14311. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14312. return this._getByTags(this.lights, tagsQuery, forEach);
  14313. };
  14314. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14315. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14316. };
  14317. // Statics
  14318. Scene._FOGMODE_NONE = 0;
  14319. Scene._FOGMODE_EXP = 1;
  14320. Scene._FOGMODE_EXP2 = 2;
  14321. Scene._FOGMODE_LINEAR = 3;
  14322. Scene.MinDeltaTime = 1.0;
  14323. Scene.MaxDeltaTime = 1000.0;
  14324. return Scene;
  14325. })();
  14326. BABYLON.Scene = Scene;
  14327. })(BABYLON || (BABYLON = {}));
  14328. var BABYLON;
  14329. (function (BABYLON) {
  14330. var VertexBuffer = (function () {
  14331. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14332. if (engine instanceof BABYLON.Mesh) {
  14333. this._engine = engine.getScene().getEngine();
  14334. }
  14335. else {
  14336. this._engine = engine;
  14337. }
  14338. this._updatable = updatable;
  14339. this._data = data;
  14340. if (!postponeInternalCreation) {
  14341. this.create();
  14342. }
  14343. this._kind = kind;
  14344. if (stride) {
  14345. this._strideSize = stride;
  14346. return;
  14347. }
  14348. // Deduce stride from kind
  14349. switch (kind) {
  14350. case VertexBuffer.PositionKind:
  14351. this._strideSize = 3;
  14352. break;
  14353. case VertexBuffer.NormalKind:
  14354. this._strideSize = 3;
  14355. break;
  14356. case VertexBuffer.UVKind:
  14357. case VertexBuffer.UV2Kind:
  14358. case VertexBuffer.UV3Kind:
  14359. case VertexBuffer.UV4Kind:
  14360. case VertexBuffer.UV5Kind:
  14361. case VertexBuffer.UV6Kind:
  14362. this._strideSize = 2;
  14363. break;
  14364. case VertexBuffer.ColorKind:
  14365. this._strideSize = 4;
  14366. break;
  14367. case VertexBuffer.MatricesIndicesKind:
  14368. this._strideSize = 4;
  14369. break;
  14370. case VertexBuffer.MatricesWeightsKind:
  14371. this._strideSize = 4;
  14372. break;
  14373. }
  14374. }
  14375. // Properties
  14376. VertexBuffer.prototype.isUpdatable = function () {
  14377. return this._updatable;
  14378. };
  14379. VertexBuffer.prototype.getData = function () {
  14380. return this._data;
  14381. };
  14382. VertexBuffer.prototype.getBuffer = function () {
  14383. return this._buffer;
  14384. };
  14385. VertexBuffer.prototype.getStrideSize = function () {
  14386. return this._strideSize;
  14387. };
  14388. // Methods
  14389. VertexBuffer.prototype.create = function (data) {
  14390. if (!data && this._buffer) {
  14391. return; // nothing to do
  14392. }
  14393. data = data || this._data;
  14394. if (!this._buffer) {
  14395. if (this._updatable) {
  14396. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14397. }
  14398. else {
  14399. this._buffer = this._engine.createVertexBuffer(data);
  14400. }
  14401. }
  14402. if (this._updatable) {
  14403. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14404. this._data = data;
  14405. }
  14406. };
  14407. VertexBuffer.prototype.update = function (data) {
  14408. this.create(data);
  14409. };
  14410. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14411. if (!this._buffer) {
  14412. return;
  14413. }
  14414. if (this._updatable) {
  14415. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14416. this._data = null;
  14417. }
  14418. };
  14419. VertexBuffer.prototype.dispose = function () {
  14420. if (!this._buffer) {
  14421. return;
  14422. }
  14423. if (this._engine._releaseBuffer(this._buffer)) {
  14424. this._buffer = null;
  14425. }
  14426. };
  14427. Object.defineProperty(VertexBuffer, "PositionKind", {
  14428. get: function () {
  14429. return VertexBuffer._PositionKind;
  14430. },
  14431. enumerable: true,
  14432. configurable: true
  14433. });
  14434. Object.defineProperty(VertexBuffer, "NormalKind", {
  14435. get: function () {
  14436. return VertexBuffer._NormalKind;
  14437. },
  14438. enumerable: true,
  14439. configurable: true
  14440. });
  14441. Object.defineProperty(VertexBuffer, "UVKind", {
  14442. get: function () {
  14443. return VertexBuffer._UVKind;
  14444. },
  14445. enumerable: true,
  14446. configurable: true
  14447. });
  14448. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14449. get: function () {
  14450. return VertexBuffer._UV2Kind;
  14451. },
  14452. enumerable: true,
  14453. configurable: true
  14454. });
  14455. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14456. get: function () {
  14457. return VertexBuffer._UV3Kind;
  14458. },
  14459. enumerable: true,
  14460. configurable: true
  14461. });
  14462. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14463. get: function () {
  14464. return VertexBuffer._UV4Kind;
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14470. get: function () {
  14471. return VertexBuffer._UV5Kind;
  14472. },
  14473. enumerable: true,
  14474. configurable: true
  14475. });
  14476. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14477. get: function () {
  14478. return VertexBuffer._UV6Kind;
  14479. },
  14480. enumerable: true,
  14481. configurable: true
  14482. });
  14483. Object.defineProperty(VertexBuffer, "ColorKind", {
  14484. get: function () {
  14485. return VertexBuffer._ColorKind;
  14486. },
  14487. enumerable: true,
  14488. configurable: true
  14489. });
  14490. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14491. get: function () {
  14492. return VertexBuffer._MatricesIndicesKind;
  14493. },
  14494. enumerable: true,
  14495. configurable: true
  14496. });
  14497. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14498. get: function () {
  14499. return VertexBuffer._MatricesWeightsKind;
  14500. },
  14501. enumerable: true,
  14502. configurable: true
  14503. });
  14504. // Enums
  14505. VertexBuffer._PositionKind = "position";
  14506. VertexBuffer._NormalKind = "normal";
  14507. VertexBuffer._UVKind = "uv";
  14508. VertexBuffer._UV2Kind = "uv2";
  14509. VertexBuffer._UV3Kind = "uv3";
  14510. VertexBuffer._UV4Kind = "uv4";
  14511. VertexBuffer._UV5Kind = "uv5";
  14512. VertexBuffer._UV6Kind = "uv6";
  14513. VertexBuffer._ColorKind = "color";
  14514. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14515. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14516. return VertexBuffer;
  14517. })();
  14518. BABYLON.VertexBuffer = VertexBuffer;
  14519. })(BABYLON || (BABYLON = {}));
  14520. var BABYLON;
  14521. (function (BABYLON) {
  14522. /**
  14523. * Creates an instance based on a source mesh.
  14524. */
  14525. var InstancedMesh = (function (_super) {
  14526. __extends(InstancedMesh, _super);
  14527. function InstancedMesh(name, source) {
  14528. _super.call(this, name, source.getScene());
  14529. source.instances.push(this);
  14530. this._sourceMesh = source;
  14531. this.position.copyFrom(source.position);
  14532. this.rotation.copyFrom(source.rotation);
  14533. this.scaling.copyFrom(source.scaling);
  14534. if (source.rotationQuaternion) {
  14535. this.rotationQuaternion = source.rotationQuaternion.clone();
  14536. }
  14537. this.infiniteDistance = source.infiniteDistance;
  14538. this.setPivotMatrix(source.getPivotMatrix());
  14539. this.refreshBoundingInfo();
  14540. this._syncSubMeshes();
  14541. }
  14542. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14543. // Methods
  14544. get: function () {
  14545. return this._sourceMesh.receiveShadows;
  14546. },
  14547. enumerable: true,
  14548. configurable: true
  14549. });
  14550. Object.defineProperty(InstancedMesh.prototype, "material", {
  14551. get: function () {
  14552. return this._sourceMesh.material;
  14553. },
  14554. enumerable: true,
  14555. configurable: true
  14556. });
  14557. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14558. get: function () {
  14559. return this._sourceMesh.visibility;
  14560. },
  14561. enumerable: true,
  14562. configurable: true
  14563. });
  14564. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14565. get: function () {
  14566. return this._sourceMesh.skeleton;
  14567. },
  14568. enumerable: true,
  14569. configurable: true
  14570. });
  14571. InstancedMesh.prototype.getTotalVertices = function () {
  14572. return this._sourceMesh.getTotalVertices();
  14573. };
  14574. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14575. get: function () {
  14576. return this._sourceMesh;
  14577. },
  14578. enumerable: true,
  14579. configurable: true
  14580. });
  14581. InstancedMesh.prototype.getVerticesData = function (kind) {
  14582. return this._sourceMesh.getVerticesData(kind);
  14583. };
  14584. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14585. return this._sourceMesh.isVerticesDataPresent(kind);
  14586. };
  14587. InstancedMesh.prototype.getIndices = function () {
  14588. return this._sourceMesh.getIndices();
  14589. };
  14590. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14591. get: function () {
  14592. return this._sourceMesh._positions;
  14593. },
  14594. enumerable: true,
  14595. configurable: true
  14596. });
  14597. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14598. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14599. if (data) {
  14600. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14601. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14602. }
  14603. this._updateBoundingInfo();
  14604. };
  14605. InstancedMesh.prototype._preActivate = function () {
  14606. if (this._currentLOD) {
  14607. this._currentLOD._preActivate();
  14608. }
  14609. };
  14610. InstancedMesh.prototype._activate = function (renderId) {
  14611. if (this._currentLOD) {
  14612. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14613. }
  14614. };
  14615. InstancedMesh.prototype.getLOD = function (camera) {
  14616. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14617. if (this._currentLOD === this.sourceMesh) {
  14618. return this;
  14619. }
  14620. return this._currentLOD;
  14621. };
  14622. InstancedMesh.prototype._syncSubMeshes = function () {
  14623. this.releaseSubMeshes();
  14624. if (this._sourceMesh.subMeshes) {
  14625. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14626. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14627. }
  14628. }
  14629. };
  14630. InstancedMesh.prototype._generatePointsArray = function () {
  14631. return this._sourceMesh._generatePointsArray();
  14632. };
  14633. // Clone
  14634. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14635. var result = this._sourceMesh.createInstance(name);
  14636. // Deep copy
  14637. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14638. // Bounding info
  14639. this.refreshBoundingInfo();
  14640. // Parent
  14641. if (newParent) {
  14642. result.parent = newParent;
  14643. }
  14644. if (!doNotCloneChildren) {
  14645. // Children
  14646. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14647. var mesh = this.getScene().meshes[index];
  14648. if (mesh.parent === this) {
  14649. mesh.clone(mesh.name, result);
  14650. }
  14651. }
  14652. }
  14653. result.computeWorldMatrix(true);
  14654. return result;
  14655. };
  14656. // Dispoe
  14657. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14658. // Remove from mesh
  14659. var index = this._sourceMesh.instances.indexOf(this);
  14660. this._sourceMesh.instances.splice(index, 1);
  14661. _super.prototype.dispose.call(this, doNotRecurse);
  14662. };
  14663. return InstancedMesh;
  14664. })(BABYLON.AbstractMesh);
  14665. BABYLON.InstancedMesh = InstancedMesh;
  14666. })(BABYLON || (BABYLON = {}));
  14667. var BABYLON;
  14668. (function (BABYLON) {
  14669. var _InstancesBatch = (function () {
  14670. function _InstancesBatch() {
  14671. this.mustReturn = false;
  14672. this.visibleInstances = new Array();
  14673. this.renderSelf = new Array();
  14674. }
  14675. return _InstancesBatch;
  14676. })();
  14677. BABYLON._InstancesBatch = _InstancesBatch;
  14678. var Mesh = (function (_super) {
  14679. __extends(Mesh, _super);
  14680. /**
  14681. * @constructor
  14682. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14683. * @param {Scene} scene - The scene to add this mesh to.
  14684. * @param {Node} parent - The parent of this mesh, if it has one
  14685. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14686. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14687. * When false, achieved by calling a clone(), also passing False.
  14688. * This will make creation of children, recursive.
  14689. */
  14690. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14691. if (parent === void 0) { parent = null; }
  14692. _super.call(this, name, scene);
  14693. // Members
  14694. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14695. this.instances = new Array();
  14696. this._LODLevels = new Array();
  14697. this._onBeforeRenderCallbacks = new Array();
  14698. this._onAfterRenderCallbacks = new Array();
  14699. this._visibleInstances = {};
  14700. this._renderIdForInstances = new Array();
  14701. this._batchCache = new _InstancesBatch();
  14702. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14703. this._sideOrientation = Mesh._DEFAULTSIDE;
  14704. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14705. if (source) {
  14706. // Geometry
  14707. if (source._geometry) {
  14708. source._geometry.applyToMesh(this);
  14709. }
  14710. // Deep copy
  14711. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14712. this.id = name + "." + source.id;
  14713. // Material
  14714. this.material = source.material;
  14715. var index;
  14716. if (!doNotCloneChildren) {
  14717. // Children
  14718. for (index = 0; index < scene.meshes.length; index++) {
  14719. var mesh = scene.meshes[index];
  14720. if (mesh.parent === source) {
  14721. // doNotCloneChildren is always going to be False
  14722. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14723. }
  14724. }
  14725. }
  14726. // Particles
  14727. for (index = 0; index < scene.particleSystems.length; index++) {
  14728. var system = scene.particleSystems[index];
  14729. if (system.emitter === source) {
  14730. system.clone(system.name, this);
  14731. }
  14732. }
  14733. this.computeWorldMatrix(true);
  14734. }
  14735. // Parent
  14736. if (parent !== null) {
  14737. this.parent = parent;
  14738. }
  14739. }
  14740. Object.defineProperty(Mesh, "FRONTSIDE", {
  14741. get: function () {
  14742. return Mesh._FRONTSIDE;
  14743. },
  14744. enumerable: true,
  14745. configurable: true
  14746. });
  14747. Object.defineProperty(Mesh, "BACKSIDE", {
  14748. get: function () {
  14749. return Mesh._BACKSIDE;
  14750. },
  14751. enumerable: true,
  14752. configurable: true
  14753. });
  14754. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14755. get: function () {
  14756. return Mesh._DOUBLESIDE;
  14757. },
  14758. enumerable: true,
  14759. configurable: true
  14760. });
  14761. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14762. get: function () {
  14763. return Mesh._DEFAULTSIDE;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Object.defineProperty(Mesh, "NO_CAP", {
  14769. get: function () {
  14770. return Mesh._NO_CAP;
  14771. },
  14772. enumerable: true,
  14773. configurable: true
  14774. });
  14775. Object.defineProperty(Mesh, "CAP_START", {
  14776. get: function () {
  14777. return Mesh._CAP_START;
  14778. },
  14779. enumerable: true,
  14780. configurable: true
  14781. });
  14782. Object.defineProperty(Mesh, "CAP_END", {
  14783. get: function () {
  14784. return Mesh._CAP_END;
  14785. },
  14786. enumerable: true,
  14787. configurable: true
  14788. });
  14789. Object.defineProperty(Mesh, "CAP_ALL", {
  14790. get: function () {
  14791. return Mesh._CAP_ALL;
  14792. },
  14793. enumerable: true,
  14794. configurable: true
  14795. });
  14796. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14797. // Methods
  14798. get: function () {
  14799. return this._LODLevels.length > 0;
  14800. },
  14801. enumerable: true,
  14802. configurable: true
  14803. });
  14804. Mesh.prototype._sortLODLevels = function () {
  14805. this._LODLevels.sort(function (a, b) {
  14806. if (a.distance < b.distance) {
  14807. return 1;
  14808. }
  14809. if (a.distance > b.distance) {
  14810. return -1;
  14811. }
  14812. return 0;
  14813. });
  14814. };
  14815. /**
  14816. * Add a mesh as LOD level triggered at the given distance.
  14817. * @param {number} distance - the distance from the center of the object to show this level
  14818. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14819. * @return {BABYLON.Mesh} this mesh (for chaining)
  14820. */
  14821. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14822. if (mesh && mesh._masterMesh) {
  14823. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14824. return this;
  14825. }
  14826. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14827. this._LODLevels.push(level);
  14828. if (mesh) {
  14829. mesh._masterMesh = this;
  14830. }
  14831. this._sortLODLevels();
  14832. return this;
  14833. };
  14834. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14835. for (var index = 0; index < this._LODLevels.length; index++) {
  14836. var level = this._LODLevels[index];
  14837. if (level.distance === distance) {
  14838. return level.mesh;
  14839. }
  14840. }
  14841. return null;
  14842. };
  14843. /**
  14844. * Remove a mesh from the LOD array
  14845. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14846. * @return {BABYLON.Mesh} this mesh (for chaining)
  14847. */
  14848. Mesh.prototype.removeLODLevel = function (mesh) {
  14849. for (var index = 0; index < this._LODLevels.length; index++) {
  14850. if (this._LODLevels[index].mesh === mesh) {
  14851. this._LODLevels.splice(index, 1);
  14852. if (mesh) {
  14853. mesh._masterMesh = null;
  14854. }
  14855. }
  14856. }
  14857. this._sortLODLevels();
  14858. return this;
  14859. };
  14860. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14861. if (!this._LODLevels || this._LODLevels.length === 0) {
  14862. return this;
  14863. }
  14864. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14865. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14866. if (this.onLODLevelSelection) {
  14867. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14868. }
  14869. return this;
  14870. }
  14871. for (var index = 0; index < this._LODLevels.length; index++) {
  14872. var level = this._LODLevels[index];
  14873. if (level.distance < distanceToCamera) {
  14874. if (level.mesh) {
  14875. level.mesh._preActivate();
  14876. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14877. }
  14878. if (this.onLODLevelSelection) {
  14879. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14880. }
  14881. return level.mesh;
  14882. }
  14883. }
  14884. if (this.onLODLevelSelection) {
  14885. this.onLODLevelSelection(distanceToCamera, this, this);
  14886. }
  14887. return this;
  14888. };
  14889. Object.defineProperty(Mesh.prototype, "geometry", {
  14890. get: function () {
  14891. return this._geometry;
  14892. },
  14893. enumerable: true,
  14894. configurable: true
  14895. });
  14896. Mesh.prototype.getTotalVertices = function () {
  14897. if (!this._geometry) {
  14898. return 0;
  14899. }
  14900. return this._geometry.getTotalVertices();
  14901. };
  14902. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14903. if (!this._geometry) {
  14904. return null;
  14905. }
  14906. return this._geometry.getVerticesData(kind, copyWhenShared);
  14907. };
  14908. Mesh.prototype.getVertexBuffer = function (kind) {
  14909. if (!this._geometry) {
  14910. return undefined;
  14911. }
  14912. return this._geometry.getVertexBuffer(kind);
  14913. };
  14914. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14915. if (!this._geometry) {
  14916. if (this._delayInfo) {
  14917. return this._delayInfo.indexOf(kind) !== -1;
  14918. }
  14919. return false;
  14920. }
  14921. return this._geometry.isVerticesDataPresent(kind);
  14922. };
  14923. Mesh.prototype.getVerticesDataKinds = function () {
  14924. if (!this._geometry) {
  14925. var result = [];
  14926. if (this._delayInfo) {
  14927. for (var kind in this._delayInfo) {
  14928. result.push(kind);
  14929. }
  14930. }
  14931. return result;
  14932. }
  14933. return this._geometry.getVerticesDataKinds();
  14934. };
  14935. Mesh.prototype.getTotalIndices = function () {
  14936. if (!this._geometry) {
  14937. return 0;
  14938. }
  14939. return this._geometry.getTotalIndices();
  14940. };
  14941. Mesh.prototype.getIndices = function (copyWhenShared) {
  14942. if (!this._geometry) {
  14943. return [];
  14944. }
  14945. return this._geometry.getIndices(copyWhenShared);
  14946. };
  14947. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14948. get: function () {
  14949. return this._masterMesh !== null && this._masterMesh !== undefined;
  14950. },
  14951. enumerable: true,
  14952. configurable: true
  14953. });
  14954. Mesh.prototype.isReady = function () {
  14955. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14956. return false;
  14957. }
  14958. return _super.prototype.isReady.call(this);
  14959. };
  14960. Mesh.prototype.isDisposed = function () {
  14961. return this._isDisposed;
  14962. };
  14963. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14964. get: function () {
  14965. return this._sideOrientation;
  14966. },
  14967. set: function (sideO) {
  14968. this._sideOrientation = sideO;
  14969. },
  14970. enumerable: true,
  14971. configurable: true
  14972. });
  14973. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14974. get: function () {
  14975. return this._areNormalsFrozen;
  14976. },
  14977. enumerable: true,
  14978. configurable: true
  14979. });
  14980. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14981. Mesh.prototype.freezeNormals = function () {
  14982. this._areNormalsFrozen = true;
  14983. };
  14984. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14985. Mesh.prototype.unfreezeNormals = function () {
  14986. this._areNormalsFrozen = false;
  14987. };
  14988. // Methods
  14989. Mesh.prototype._preActivate = function () {
  14990. var sceneRenderId = this.getScene().getRenderId();
  14991. if (this._preActivateId === sceneRenderId) {
  14992. return;
  14993. }
  14994. this._preActivateId = sceneRenderId;
  14995. this._visibleInstances = null;
  14996. };
  14997. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14998. if (!this._visibleInstances) {
  14999. this._visibleInstances = {};
  15000. this._visibleInstances.defaultRenderId = renderId;
  15001. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15002. }
  15003. if (!this._visibleInstances[renderId]) {
  15004. this._visibleInstances[renderId] = new Array();
  15005. }
  15006. this._visibleInstances[renderId].push(instance);
  15007. };
  15008. Mesh.prototype.refreshBoundingInfo = function () {
  15009. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15010. if (data) {
  15011. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15012. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15013. }
  15014. if (this.subMeshes) {
  15015. for (var index = 0; index < this.subMeshes.length; index++) {
  15016. this.subMeshes[index].refreshBoundingInfo();
  15017. }
  15018. }
  15019. this._updateBoundingInfo();
  15020. };
  15021. Mesh.prototype._createGlobalSubMesh = function () {
  15022. var totalVertices = this.getTotalVertices();
  15023. if (!totalVertices || !this.getIndices()) {
  15024. return null;
  15025. }
  15026. this.releaseSubMeshes();
  15027. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15028. };
  15029. Mesh.prototype.subdivide = function (count) {
  15030. if (count < 1) {
  15031. return;
  15032. }
  15033. var totalIndices = this.getTotalIndices();
  15034. var subdivisionSize = (totalIndices / count) | 0;
  15035. var offset = 0;
  15036. // Ensure that subdivisionSize is a multiple of 3
  15037. while (subdivisionSize % 3 !== 0) {
  15038. subdivisionSize++;
  15039. }
  15040. this.releaseSubMeshes();
  15041. for (var index = 0; index < count; index++) {
  15042. if (offset >= totalIndices) {
  15043. break;
  15044. }
  15045. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15046. offset += subdivisionSize;
  15047. }
  15048. this.synchronizeInstances();
  15049. };
  15050. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15051. if (kind instanceof Array) {
  15052. var temp = data;
  15053. data = kind;
  15054. kind = temp;
  15055. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  15056. }
  15057. if (!this._geometry) {
  15058. var vertexData = new BABYLON.VertexData();
  15059. vertexData.set(data, kind);
  15060. var scene = this.getScene();
  15061. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15062. }
  15063. else {
  15064. this._geometry.setVerticesData(kind, data, updatable, stride);
  15065. }
  15066. };
  15067. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15068. if (!this._geometry) {
  15069. return;
  15070. }
  15071. if (!makeItUnique) {
  15072. this._geometry.updateVerticesData(kind, data, updateExtends);
  15073. }
  15074. else {
  15075. this.makeGeometryUnique();
  15076. this.updateVerticesData(kind, data, updateExtends, false);
  15077. }
  15078. };
  15079. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15080. if (!this._geometry) {
  15081. return;
  15082. }
  15083. if (!makeItUnique) {
  15084. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15085. }
  15086. else {
  15087. this.makeGeometryUnique();
  15088. this.updateVerticesDataDirectly(kind, data, offset, false);
  15089. }
  15090. };
  15091. // Mesh positions update function :
  15092. // updates the mesh positions according to the positionFunction returned values.
  15093. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15094. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15095. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15096. if (computeNormals === void 0) { computeNormals = true; }
  15097. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15098. positionFunction(positions);
  15099. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15100. if (computeNormals) {
  15101. var indices = this.getIndices();
  15102. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15103. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15104. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15105. }
  15106. };
  15107. Mesh.prototype.makeGeometryUnique = function () {
  15108. if (!this._geometry) {
  15109. return;
  15110. }
  15111. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15112. geometry.applyToMesh(this);
  15113. };
  15114. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15115. if (!this._geometry) {
  15116. var vertexData = new BABYLON.VertexData();
  15117. vertexData.indices = indices;
  15118. var scene = this.getScene();
  15119. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15120. }
  15121. else {
  15122. this._geometry.setIndices(indices, totalVertices);
  15123. }
  15124. };
  15125. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15126. var engine = this.getScene().getEngine();
  15127. // Wireframe
  15128. var indexToBind;
  15129. switch (fillMode) {
  15130. case BABYLON.Material.PointFillMode:
  15131. indexToBind = null;
  15132. break;
  15133. case BABYLON.Material.WireFrameFillMode:
  15134. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15135. break;
  15136. default:
  15137. case BABYLON.Material.TriangleFillMode:
  15138. indexToBind = this._geometry.getIndexBuffer();
  15139. break;
  15140. }
  15141. // VBOs
  15142. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15143. };
  15144. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15145. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15146. return;
  15147. }
  15148. var engine = this.getScene().getEngine();
  15149. // Draw order
  15150. switch (fillMode) {
  15151. case BABYLON.Material.PointFillMode:
  15152. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15153. break;
  15154. case BABYLON.Material.WireFrameFillMode:
  15155. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15156. break;
  15157. default:
  15158. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15159. }
  15160. };
  15161. Mesh.prototype.registerBeforeRender = function (func) {
  15162. this._onBeforeRenderCallbacks.push(func);
  15163. };
  15164. Mesh.prototype.unregisterBeforeRender = function (func) {
  15165. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15166. if (index > -1) {
  15167. this._onBeforeRenderCallbacks.splice(index, 1);
  15168. }
  15169. };
  15170. Mesh.prototype.registerAfterRender = function (func) {
  15171. this._onAfterRenderCallbacks.push(func);
  15172. };
  15173. Mesh.prototype.unregisterAfterRender = function (func) {
  15174. var index = this._onAfterRenderCallbacks.indexOf(func);
  15175. if (index > -1) {
  15176. this._onAfterRenderCallbacks.splice(index, 1);
  15177. }
  15178. };
  15179. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15180. var scene = this.getScene();
  15181. this._batchCache.mustReturn = false;
  15182. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15183. this._batchCache.visibleInstances[subMeshId] = null;
  15184. if (this._visibleInstances) {
  15185. var currentRenderId = scene.getRenderId();
  15186. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15187. var selfRenderId = this._renderId;
  15188. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15189. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15190. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15191. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15192. }
  15193. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15194. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15195. this._batchCache.mustReturn = true;
  15196. return this._batchCache;
  15197. }
  15198. if (currentRenderId !== selfRenderId) {
  15199. this._batchCache.renderSelf[subMeshId] = false;
  15200. }
  15201. }
  15202. this._renderIdForInstances[subMeshId] = currentRenderId;
  15203. }
  15204. return this._batchCache;
  15205. };
  15206. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15207. var visibleInstances = batch.visibleInstances[subMesh._id];
  15208. var matricesCount = visibleInstances.length + 1;
  15209. var bufferSize = matricesCount * 16 * 4;
  15210. while (this._instancesBufferSize < bufferSize) {
  15211. this._instancesBufferSize *= 2;
  15212. }
  15213. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15214. if (this._worldMatricesInstancesBuffer) {
  15215. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15216. }
  15217. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15218. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15219. }
  15220. var offset = 0;
  15221. var instancesCount = 0;
  15222. var world = this.getWorldMatrix();
  15223. if (batch.renderSelf[subMesh._id]) {
  15224. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15225. offset += 16;
  15226. instancesCount++;
  15227. }
  15228. if (visibleInstances) {
  15229. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15230. var instance = visibleInstances[instanceIndex];
  15231. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15232. offset += 16;
  15233. instancesCount++;
  15234. }
  15235. }
  15236. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15237. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15238. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15239. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15240. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15241. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15242. this._draw(subMesh, fillMode, instancesCount);
  15243. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15244. };
  15245. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15246. var scene = this.getScene();
  15247. var engine = scene.getEngine();
  15248. if (hardwareInstancedRendering) {
  15249. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15250. }
  15251. else {
  15252. if (batch.renderSelf[subMesh._id]) {
  15253. // Draw
  15254. if (onBeforeDraw) {
  15255. onBeforeDraw(false, this.getWorldMatrix());
  15256. }
  15257. this._draw(subMesh, fillMode);
  15258. }
  15259. if (batch.visibleInstances[subMesh._id]) {
  15260. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15261. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15262. // World
  15263. var world = instance.getWorldMatrix();
  15264. if (onBeforeDraw) {
  15265. onBeforeDraw(true, world);
  15266. }
  15267. // Draw
  15268. this._draw(subMesh, fillMode);
  15269. }
  15270. }
  15271. }
  15272. };
  15273. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15274. var scene = this.getScene();
  15275. // Managing instances
  15276. var batch = this._getInstancesRenderList(subMesh._id);
  15277. if (batch.mustReturn) {
  15278. return;
  15279. }
  15280. // Checking geometry state
  15281. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15282. return;
  15283. }
  15284. var callbackIndex;
  15285. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15286. this._onBeforeRenderCallbacks[callbackIndex](this);
  15287. }
  15288. var engine = scene.getEngine();
  15289. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15290. // Material
  15291. var effectiveMaterial = subMesh.getMaterial();
  15292. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15293. return;
  15294. }
  15295. // Outline - step 1
  15296. var savedDepthWrite = engine.getDepthWrite();
  15297. if (this.renderOutline) {
  15298. engine.setDepthWrite(false);
  15299. scene.getOutlineRenderer().render(subMesh, batch);
  15300. engine.setDepthWrite(savedDepthWrite);
  15301. }
  15302. effectiveMaterial._preBind();
  15303. var effect = effectiveMaterial.getEffect();
  15304. // Bind
  15305. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15306. this._bind(subMesh, effect, fillMode);
  15307. var world = this.getWorldMatrix();
  15308. effectiveMaterial.bind(world, this);
  15309. // Alpha mode
  15310. if (enableAlphaMode) {
  15311. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15312. }
  15313. // Draw
  15314. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15315. if (isInstance) {
  15316. effectiveMaterial.bindOnlyWorldMatrix(world);
  15317. }
  15318. });
  15319. // Unbind
  15320. effectiveMaterial.unbind();
  15321. // Outline - step 2
  15322. if (this.renderOutline && savedDepthWrite) {
  15323. engine.setDepthWrite(true);
  15324. engine.setColorWrite(false);
  15325. scene.getOutlineRenderer().render(subMesh, batch);
  15326. engine.setColorWrite(true);
  15327. }
  15328. // Overlay
  15329. if (this.renderOverlay) {
  15330. var currentMode = engine.getAlphaMode();
  15331. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15332. scene.getOutlineRenderer().render(subMesh, batch, true);
  15333. engine.setAlphaMode(currentMode);
  15334. }
  15335. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15336. this._onAfterRenderCallbacks[callbackIndex](this);
  15337. }
  15338. };
  15339. Mesh.prototype.getEmittedParticleSystems = function () {
  15340. var results = new Array();
  15341. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15342. var particleSystem = this.getScene().particleSystems[index];
  15343. if (particleSystem.emitter === this) {
  15344. results.push(particleSystem);
  15345. }
  15346. }
  15347. return results;
  15348. };
  15349. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15350. var results = new Array();
  15351. var descendants = this.getDescendants();
  15352. descendants.push(this);
  15353. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15354. var particleSystem = this.getScene().particleSystems[index];
  15355. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15356. results.push(particleSystem);
  15357. }
  15358. }
  15359. return results;
  15360. };
  15361. Mesh.prototype.getChildren = function () {
  15362. var results = [];
  15363. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15364. var mesh = this.getScene().meshes[index];
  15365. if (mesh.parent === this) {
  15366. results.push(mesh);
  15367. }
  15368. }
  15369. return results;
  15370. };
  15371. Mesh.prototype._checkDelayState = function () {
  15372. var _this = this;
  15373. var that = this;
  15374. var scene = this.getScene();
  15375. if (this._geometry) {
  15376. this._geometry.load(scene);
  15377. }
  15378. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15379. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15380. scene._addPendingData(that);
  15381. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15382. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15383. if (data instanceof ArrayBuffer) {
  15384. _this._delayLoadingFunction(data, _this);
  15385. }
  15386. else {
  15387. _this._delayLoadingFunction(JSON.parse(data), _this);
  15388. }
  15389. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15390. scene._removePendingData(_this);
  15391. }, function () { }, scene.database, getBinaryData);
  15392. }
  15393. };
  15394. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15395. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15396. return false;
  15397. }
  15398. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15399. return false;
  15400. }
  15401. this._checkDelayState();
  15402. return true;
  15403. };
  15404. Mesh.prototype.setMaterialByID = function (id) {
  15405. var materials = this.getScene().materials;
  15406. var index;
  15407. for (index = 0; index < materials.length; index++) {
  15408. if (materials[index].id === id) {
  15409. this.material = materials[index];
  15410. return;
  15411. }
  15412. }
  15413. // Multi
  15414. var multiMaterials = this.getScene().multiMaterials;
  15415. for (index = 0; index < multiMaterials.length; index++) {
  15416. if (multiMaterials[index].id === id) {
  15417. this.material = multiMaterials[index];
  15418. return;
  15419. }
  15420. }
  15421. };
  15422. Mesh.prototype.getAnimatables = function () {
  15423. var results = [];
  15424. if (this.material) {
  15425. results.push(this.material);
  15426. }
  15427. if (this.skeleton) {
  15428. results.push(this.skeleton);
  15429. }
  15430. return results;
  15431. };
  15432. // Geometry
  15433. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15434. // Position
  15435. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15436. return;
  15437. }
  15438. this._resetPointsArrayCache();
  15439. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15440. var temp = [];
  15441. var index;
  15442. for (index = 0; index < data.length; index += 3) {
  15443. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15444. }
  15445. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15446. // Normals
  15447. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15448. return;
  15449. }
  15450. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15451. temp = [];
  15452. for (index = 0; index < data.length; index += 3) {
  15453. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15454. }
  15455. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15456. // flip faces?
  15457. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15458. this.flipFaces();
  15459. }
  15460. };
  15461. // Will apply current transform to mesh and reset world matrix
  15462. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15463. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15464. this.scaling.copyFromFloats(1, 1, 1);
  15465. this.position.copyFromFloats(0, 0, 0);
  15466. this.rotation.copyFromFloats(0, 0, 0);
  15467. //only if quaternion is already set
  15468. if (this.rotationQuaternion) {
  15469. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15470. }
  15471. this._worldMatrix = BABYLON.Matrix.Identity();
  15472. };
  15473. // Cache
  15474. Mesh.prototype._resetPointsArrayCache = function () {
  15475. this._positions = null;
  15476. };
  15477. Mesh.prototype._generatePointsArray = function () {
  15478. if (this._positions)
  15479. return true;
  15480. this._positions = [];
  15481. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15482. if (!data) {
  15483. return false;
  15484. }
  15485. for (var index = 0; index < data.length; index += 3) {
  15486. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15487. }
  15488. return true;
  15489. };
  15490. // Clone
  15491. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15492. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15493. };
  15494. // Dispose
  15495. Mesh.prototype.dispose = function (doNotRecurse) {
  15496. if (this._geometry) {
  15497. this._geometry.releaseForMesh(this, true);
  15498. }
  15499. // Instances
  15500. if (this._worldMatricesInstancesBuffer) {
  15501. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15502. this._worldMatricesInstancesBuffer = null;
  15503. }
  15504. while (this.instances.length) {
  15505. this.instances[0].dispose();
  15506. }
  15507. _super.prototype.dispose.call(this, doNotRecurse);
  15508. };
  15509. // Geometric tools
  15510. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15511. var _this = this;
  15512. var scene = this.getScene();
  15513. var onload = function (img) {
  15514. // Getting height map data
  15515. var canvas = document.createElement("canvas");
  15516. var context = canvas.getContext("2d");
  15517. var heightMapWidth = img.width;
  15518. var heightMapHeight = img.height;
  15519. canvas.width = heightMapWidth;
  15520. canvas.height = heightMapHeight;
  15521. context.drawImage(img, 0, 0);
  15522. // Create VertexData from map data
  15523. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15524. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15525. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15526. //execute success callback, if set
  15527. if (onSuccess) {
  15528. onSuccess(_this);
  15529. }
  15530. };
  15531. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15532. };
  15533. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15534. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15535. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15536. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15537. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15538. return;
  15539. }
  15540. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15541. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15542. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15543. var position = BABYLON.Vector3.Zero();
  15544. var normal = BABYLON.Vector3.Zero();
  15545. var uv = BABYLON.Vector2.Zero();
  15546. for (var index = 0; index < positions.length; index += 3) {
  15547. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15548. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15549. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15550. // Compute height
  15551. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15552. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15553. var pos = (u + v * heightMapWidth) * 4;
  15554. var r = buffer[pos] / 255.0;
  15555. var g = buffer[pos + 1] / 255.0;
  15556. var b = buffer[pos + 2] / 255.0;
  15557. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15558. normal.normalize();
  15559. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15560. position = position.add(normal);
  15561. position.toArray(positions, index);
  15562. }
  15563. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15564. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15565. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15566. };
  15567. Mesh.prototype.convertToFlatShadedMesh = function () {
  15568. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15569. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15570. var kinds = this.getVerticesDataKinds();
  15571. var vbs = [];
  15572. var data = [];
  15573. var newdata = [];
  15574. var updatableNormals = false;
  15575. var kindIndex;
  15576. var kind;
  15577. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15578. kind = kinds[kindIndex];
  15579. var vertexBuffer = this.getVertexBuffer(kind);
  15580. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15581. updatableNormals = vertexBuffer.isUpdatable();
  15582. kinds.splice(kindIndex, 1);
  15583. kindIndex--;
  15584. continue;
  15585. }
  15586. vbs[kind] = vertexBuffer;
  15587. data[kind] = vbs[kind].getData();
  15588. newdata[kind] = [];
  15589. }
  15590. // Save previous submeshes
  15591. var previousSubmeshes = this.subMeshes.slice(0);
  15592. var indices = this.getIndices();
  15593. var totalIndices = this.getTotalIndices();
  15594. // Generating unique vertices per face
  15595. var index;
  15596. for (index = 0; index < totalIndices; index++) {
  15597. var vertexIndex = indices[index];
  15598. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15599. kind = kinds[kindIndex];
  15600. var stride = vbs[kind].getStrideSize();
  15601. for (var offset = 0; offset < stride; offset++) {
  15602. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15603. }
  15604. }
  15605. }
  15606. // Updating faces & normal
  15607. var normals = [];
  15608. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15609. for (index = 0; index < totalIndices; index += 3) {
  15610. indices[index] = index;
  15611. indices[index + 1] = index + 1;
  15612. indices[index + 2] = index + 2;
  15613. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15614. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15615. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15616. var p1p2 = p1.subtract(p2);
  15617. var p3p2 = p3.subtract(p2);
  15618. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15619. // Store same normals for every vertex
  15620. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15621. normals.push(normal.x);
  15622. normals.push(normal.y);
  15623. normals.push(normal.z);
  15624. }
  15625. }
  15626. this.setIndices(indices);
  15627. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15628. // Updating vertex buffers
  15629. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15630. kind = kinds[kindIndex];
  15631. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15632. }
  15633. // Updating submeshes
  15634. this.releaseSubMeshes();
  15635. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15636. var previousOne = previousSubmeshes[submeshIndex];
  15637. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15638. }
  15639. this.synchronizeInstances();
  15640. };
  15641. // will inverse faces orientations, and invert normals too if specified
  15642. Mesh.prototype.flipFaces = function (flipNormals) {
  15643. if (flipNormals === void 0) { flipNormals = false; }
  15644. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15645. var i;
  15646. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15647. for (i = 0; i < vertex_data.normals.length; i++) {
  15648. vertex_data.normals[i] *= -1;
  15649. }
  15650. }
  15651. var temp;
  15652. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15653. // reassign indices
  15654. temp = vertex_data.indices[i + 1];
  15655. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15656. vertex_data.indices[i + 2] = temp;
  15657. }
  15658. vertex_data.applyToMesh(this);
  15659. };
  15660. // Instances
  15661. Mesh.prototype.createInstance = function (name) {
  15662. return new BABYLON.InstancedMesh(name, this);
  15663. };
  15664. Mesh.prototype.synchronizeInstances = function () {
  15665. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15666. var instance = this.instances[instanceIndex];
  15667. instance._syncSubMeshes();
  15668. }
  15669. };
  15670. /**
  15671. * Simplify the mesh according to the given array of settings.
  15672. * Function will return immediately and will simplify async.
  15673. * @param settings a collection of simplification settings.
  15674. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15675. * @param type the type of simplification to run.
  15676. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15677. */
  15678. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15679. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15680. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15681. this.getScene().simplificationQueue.addTask({
  15682. settings: settings,
  15683. parallelProcessing: parallelProcessing,
  15684. mesh: this,
  15685. simplificationType: simplificationType,
  15686. successCallback: successCallback
  15687. });
  15688. };
  15689. /**
  15690. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15691. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15692. * This should be used together with the simplification to avoid disappearing triangles.
  15693. * @param successCallback an optional success callback to be called after the optimization finished.
  15694. */
  15695. Mesh.prototype.optimizeIndices = function (successCallback) {
  15696. var _this = this;
  15697. var indices = this.getIndices();
  15698. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15699. var vectorPositions = [];
  15700. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15701. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15702. }
  15703. var dupes = [];
  15704. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15705. var realPos = vectorPositions.length - 1 - iteration;
  15706. var testedPosition = vectorPositions[realPos];
  15707. for (var j = 0; j < realPos; ++j) {
  15708. var againstPosition = vectorPositions[j];
  15709. if (testedPosition.equals(againstPosition)) {
  15710. dupes[realPos] = j;
  15711. break;
  15712. }
  15713. }
  15714. }, function () {
  15715. for (var i = 0; i < indices.length; ++i) {
  15716. indices[i] = dupes[indices[i]] || indices[i];
  15717. }
  15718. //indices are now reordered
  15719. var originalSubMeshes = _this.subMeshes.slice(0);
  15720. _this.setIndices(indices);
  15721. _this.subMeshes = originalSubMeshes;
  15722. if (successCallback) {
  15723. successCallback(_this);
  15724. }
  15725. });
  15726. };
  15727. Mesh.CreateRibbon = function (name, options, closeArrayOrScene, closePath, offset, scene, updatable, sideOrientation, instance) {
  15728. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15729. if (instance === void 0) { instance = null; }
  15730. var pathArray;
  15731. var closeArray;
  15732. if (Array.isArray(options)) {
  15733. pathArray = options;
  15734. closeArray = closeArrayOrScene;
  15735. if (!instance) {
  15736. options = {
  15737. pathArray: pathArray,
  15738. closeArray: closeArray,
  15739. closePath: closePath,
  15740. offset: offset,
  15741. updatable: updatable,
  15742. sideOrientation: sideOrientation
  15743. };
  15744. }
  15745. }
  15746. else {
  15747. scene = closeArrayOrScene;
  15748. pathArray = options.pathArray;
  15749. closeArray = options.closeArray;
  15750. closePath = options.closePath;
  15751. offset = options.offset;
  15752. sideOrientation = options.sideOrientation;
  15753. instance = options.instance;
  15754. updatable = options.updatable;
  15755. }
  15756. if (instance) {
  15757. // positionFunction : ribbon case
  15758. // only pathArray and sideOrientation parameters are taken into account for positions update
  15759. var positionFunction = function (positions) {
  15760. var minlg = pathArray[0].length;
  15761. var i = 0;
  15762. var ns = (instance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15763. for (var si = 1; si <= ns; si++) {
  15764. for (var p = 0; p < pathArray.length; p++) {
  15765. var path = pathArray[p];
  15766. var l = path.length;
  15767. minlg = (minlg < l) ? minlg : l;
  15768. var j = 0;
  15769. while (j < minlg) {
  15770. positions[i] = path[j].x;
  15771. positions[i + 1] = path[j].y;
  15772. positions[i + 2] = path[j].z;
  15773. j++;
  15774. i += 3;
  15775. }
  15776. if (instance._closePath) {
  15777. positions[i] = path[0].x;
  15778. positions[i + 1] = path[0].y;
  15779. positions[i + 2] = path[0].z;
  15780. i += 3;
  15781. }
  15782. }
  15783. }
  15784. };
  15785. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15786. positionFunction(positions);
  15787. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15788. if (!(instance.areNormalsFrozen)) {
  15789. var indices = instance.getIndices();
  15790. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15791. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15792. if (instance._closePath) {
  15793. var indexFirst = 0;
  15794. var indexLast = 0;
  15795. for (var p = 0; p < pathArray.length; p++) {
  15796. indexFirst = instance._idx[p] * 3;
  15797. if (p + 1 < pathArray.length) {
  15798. indexLast = (instance._idx[p + 1] - 1) * 3;
  15799. }
  15800. else {
  15801. indexLast = normals.length - 3;
  15802. }
  15803. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15804. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15805. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15806. normals[indexLast] = normals[indexFirst];
  15807. normals[indexLast + 1] = normals[indexFirst + 1];
  15808. normals[indexLast + 2] = normals[indexFirst + 2];
  15809. }
  15810. }
  15811. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15812. }
  15813. return instance;
  15814. }
  15815. else {
  15816. var ribbon = new Mesh(name, scene);
  15817. ribbon.sideOrientation = sideOrientation;
  15818. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15819. if (closePath) {
  15820. ribbon._idx = vertexData._idx;
  15821. }
  15822. ribbon._closePath = closePath;
  15823. ribbon._closeArray = closeArray;
  15824. vertexData.applyToMesh(ribbon, updatable);
  15825. return ribbon;
  15826. }
  15827. };
  15828. Mesh.CreateDisc = function (name, options, tessellationOrScene, scene, updatable, sideOrientation) {
  15829. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15830. if (tessellationOrScene instanceof BABYLON.Scene) {
  15831. scene = tessellationOrScene;
  15832. }
  15833. else {
  15834. var radius = options;
  15835. options = {
  15836. radius: radius,
  15837. tessellation: tessellationOrScene,
  15838. sideOrientation: sideOrientation
  15839. };
  15840. }
  15841. var disc = new Mesh(name, scene);
  15842. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15843. vertexData.applyToMesh(disc, updatable || options.updatable);
  15844. return disc;
  15845. };
  15846. Mesh.CreateBox = function (name, options, scene, updatable, sideOrientation) {
  15847. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15848. // Check parameters
  15849. updatable = updatable || options.updatable;
  15850. if (typeof options === 'number') {
  15851. var size = options;
  15852. options = {
  15853. size: size,
  15854. sideOrientation: sideOrientation
  15855. };
  15856. }
  15857. var box = new Mesh(name, scene);
  15858. var vertexData = BABYLON.VertexData.CreateBox(options);
  15859. vertexData.applyToMesh(box, updatable);
  15860. return box;
  15861. };
  15862. Mesh.CreateSphere = function (name, options, diameterOrScene, scene, updatable, sideOrientation) {
  15863. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15864. if (diameterOrScene instanceof BABYLON.Scene) {
  15865. scene = diameterOrScene;
  15866. updatable = options.updatable;
  15867. }
  15868. else {
  15869. var segments = options;
  15870. options = {
  15871. segments: segments,
  15872. diameterX: diameterOrScene,
  15873. diameterY: diameterOrScene,
  15874. diameterZ: diameterOrScene,
  15875. sideOrientation: sideOrientation
  15876. };
  15877. }
  15878. var sphere = new Mesh(name, scene);
  15879. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15880. vertexData.applyToMesh(sphere, updatable);
  15881. return sphere;
  15882. };
  15883. Mesh.CreateCylinder = function (name, options, diameterTopOrScene, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15884. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15885. if (diameterTopOrScene instanceof BABYLON.Scene) {
  15886. scene = diameterTopOrScene;
  15887. updatable = options.updatable;
  15888. }
  15889. else {
  15890. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15891. if (scene !== undefined) {
  15892. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15893. updatable = scene;
  15894. }
  15895. scene = subdivisions;
  15896. subdivisions = 1;
  15897. }
  15898. var height = options;
  15899. options = {
  15900. height: height,
  15901. diameterTop: diameterTopOrScene,
  15902. diameterBottom: diameterBottom,
  15903. tessellation: tessellation,
  15904. subdivisions: subdivisions,
  15905. sideOrientation: sideOrientation
  15906. };
  15907. }
  15908. var cylinder = new Mesh(name, scene);
  15909. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15910. vertexData.applyToMesh(cylinder, updatable);
  15911. return cylinder;
  15912. };
  15913. Mesh.CreateTorus = function (name, options, thicknessOrScene, tessellation, scene, updatable, sideOrientation) {
  15914. if (thicknessOrScene instanceof BABYLON.Scene) {
  15915. scene = thicknessOrScene;
  15916. updatable = options.updatable;
  15917. }
  15918. else {
  15919. var diameter = options;
  15920. options = {
  15921. diameter: diameter,
  15922. thickness: thicknessOrScene,
  15923. tessellation: tessellation,
  15924. sideOrientation: sideOrientation
  15925. };
  15926. }
  15927. var torus = new Mesh(name, scene);
  15928. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15929. vertexData.applyToMesh(torus, updatable);
  15930. return torus;
  15931. };
  15932. Mesh.CreateTorusKnot = function (name, options, tubeOrScene, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15933. if (tubeOrScene instanceof BABYLON.Scene) {
  15934. scene = tubeOrScene;
  15935. updatable = options.updatable;
  15936. }
  15937. else {
  15938. var radius = options;
  15939. options = {
  15940. radius: radius,
  15941. tube: tubeOrScene,
  15942. radialSegments: radialSegments,
  15943. tubularSegments: tubularSegments,
  15944. p: p,
  15945. q: q,
  15946. sideOrientation: sideOrientation
  15947. };
  15948. }
  15949. var torusKnot = new Mesh(name, scene);
  15950. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15951. vertexData.applyToMesh(torusKnot, updatable);
  15952. return torusKnot;
  15953. };
  15954. Mesh.CreateLines = function (name, options, scene, updatable, instance) {
  15955. var points;
  15956. if (Array.isArray(options)) {
  15957. points = options;
  15958. if (!instance) {
  15959. options = {
  15960. points: points
  15961. };
  15962. }
  15963. }
  15964. else {
  15965. instance = options.instance;
  15966. points = options.points;
  15967. }
  15968. if (instance) {
  15969. var positionFunction = function (positions) {
  15970. var i = 0;
  15971. for (var p = 0; p < points.length; p++) {
  15972. positions[i] = points[p].x;
  15973. positions[i + 1] = points[p].y;
  15974. positions[i + 2] = points[p].z;
  15975. i += 3;
  15976. }
  15977. };
  15978. instance.updateMeshPositions(positionFunction, false);
  15979. return instance;
  15980. }
  15981. // lines creation
  15982. var lines = new BABYLON.LinesMesh(name, scene);
  15983. var vertexData = BABYLON.VertexData.CreateLines(options);
  15984. vertexData.applyToMesh(lines, updatable || options.updatable);
  15985. return lines;
  15986. };
  15987. Mesh.CreateDashedLines = function (name, options, dashSizeOrScene, gapSize, dashNb, scene, updatable, instance) {
  15988. var points;
  15989. var dashSize;
  15990. if (Array.isArray(options)) {
  15991. points = options;
  15992. dashSize = dashSizeOrScene;
  15993. if (!instance) {
  15994. options = {
  15995. points: points,
  15996. dashSize: dashSize,
  15997. gapSize: gapSize,
  15998. dashNb: dashNb
  15999. };
  16000. }
  16001. }
  16002. else {
  16003. scene = dashSizeOrScene,
  16004. points = options.points;
  16005. instance = options.instance;
  16006. gapSize = options.gapSize;
  16007. dashNb = options.dashNb;
  16008. dashSize = options.dashSize;
  16009. }
  16010. if (instance) {
  16011. var positionFunction = function (positions) {
  16012. var curvect = BABYLON.Vector3.Zero();
  16013. var nbSeg = positions.length / 6;
  16014. var lg = 0;
  16015. var nb = 0;
  16016. var shft = 0;
  16017. var dashshft = 0;
  16018. var curshft = 0;
  16019. var p = 0;
  16020. var i = 0;
  16021. var j = 0;
  16022. for (i = 0; i < points.length - 1; i++) {
  16023. points[i + 1].subtractToRef(points[i], curvect);
  16024. lg += curvect.length();
  16025. }
  16026. shft = lg / nbSeg;
  16027. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16028. for (i = 0; i < points.length - 1; i++) {
  16029. points[i + 1].subtractToRef(points[i], curvect);
  16030. nb = Math.floor(curvect.length() / shft);
  16031. curvect.normalize();
  16032. j = 0;
  16033. while (j < nb && p < positions.length) {
  16034. curshft = shft * j;
  16035. positions[p] = points[i].x + curshft * curvect.x;
  16036. positions[p + 1] = points[i].y + curshft * curvect.y;
  16037. positions[p + 2] = points[i].z + curshft * curvect.z;
  16038. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16039. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16040. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16041. p += 6;
  16042. j++;
  16043. }
  16044. }
  16045. while (p < positions.length) {
  16046. positions[p] = points[i].x;
  16047. positions[p + 1] = points[i].y;
  16048. positions[p + 2] = points[i].z;
  16049. p += 3;
  16050. }
  16051. };
  16052. instance.updateMeshPositions(positionFunction, false);
  16053. return instance;
  16054. }
  16055. // dashed lines creation
  16056. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16057. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16058. vertexData.applyToMesh(dashedLines, updatable || options.updatable);
  16059. dashedLines.dashSize = dashSize;
  16060. dashedLines.gapSize = gapSize;
  16061. return dashedLines;
  16062. };
  16063. Mesh.ExtrudeShape = function (name, options, pathOrScene, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16064. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16065. if (instance === void 0) { instance = null; }
  16066. var path;
  16067. var shape;
  16068. if (Array.isArray(options)) {
  16069. shape = options;
  16070. path = pathOrScene;
  16071. scale = scale || 1;
  16072. rotation = rotation || 0;
  16073. cap = (cap === 0) ? 0 : cap || Mesh.NO_CAP;
  16074. }
  16075. else {
  16076. scene = pathOrScene;
  16077. path = options.path;
  16078. shape = options.shape;
  16079. scale = options.scale || 1;
  16080. rotation = options.rotation || 0;
  16081. cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  16082. updatable = options.updatable;
  16083. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  16084. instance = options.instance;
  16085. }
  16086. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16087. return extruded;
  16088. };
  16089. Mesh.ExtrudeShapeCustom = function (name, options, pathOrScene, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16090. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16091. if (instance === void 0) { instance = null; }
  16092. var path;
  16093. var shape;
  16094. if (Array.isArray(options)) {
  16095. shape = options;
  16096. path = pathOrScene;
  16097. ribbonCloseArray = ribbonCloseArray || false;
  16098. ribbonClosePath = ribbonClosePath || false;
  16099. cap = (cap === 0) ? 0 : cap || Mesh.NO_CAP;
  16100. }
  16101. else {
  16102. scene = pathOrScene;
  16103. path = options.path;
  16104. shape = options.shape;
  16105. scaleFunction = options.scaleFunction || (function (i, distance) { return 1; });
  16106. rotationFunction = options.rotationFunction || (function (i, distance) { return 0; });
  16107. ribbonCloseArray = options.ribbonCloseArray || false;
  16108. ribbonClosePath = options.ribbonClosePath || false;
  16109. cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  16110. updatable = options.updatable;
  16111. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  16112. instance = options.instance;
  16113. }
  16114. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16115. return extrudedCustom;
  16116. };
  16117. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16118. // extrusion geometry
  16119. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16120. var tangents = path3D.getTangents();
  16121. var normals = path3D.getNormals();
  16122. var binormals = path3D.getBinormals();
  16123. var distances = path3D.getDistances();
  16124. var angle = 0;
  16125. var returnScale = function (i, distance) { return scale; };
  16126. var returnRotation = function (i, distance) { return rotation; };
  16127. var rotate = custom ? rotateFunction : returnRotation;
  16128. var scl = custom ? scaleFunction : returnScale;
  16129. var index = (cap === Mesh.NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  16130. var rotationMatrix = BABYLON.Matrix.Zero();
  16131. for (var i = 0; i < curve.length; i++) {
  16132. var shapePath = new Array();
  16133. var angleStep = rotate(i, distances[i]);
  16134. var scaleRatio = scl(i, distances[i]);
  16135. for (var p = 0; p < shape.length; p++) {
  16136. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16137. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16138. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16139. shapePath.push(rotated);
  16140. }
  16141. shapePaths[index] = shapePath;
  16142. angle += angleStep;
  16143. index++;
  16144. }
  16145. // cap
  16146. var capPath = function (shapePath) {
  16147. var pointCap = Array();
  16148. var barycenter = BABYLON.Vector3.Zero();
  16149. var i;
  16150. for (i = 0; i < shapePath.length; i++) {
  16151. barycenter.addInPlace(shapePath[i]);
  16152. }
  16153. barycenter.scaleInPlace(1 / shapePath.length);
  16154. for (i = 0; i < shapePath.length; i++) {
  16155. pointCap.push(barycenter);
  16156. }
  16157. return pointCap;
  16158. };
  16159. switch (cap) {
  16160. case Mesh.NO_CAP:
  16161. break;
  16162. case Mesh.CAP_START:
  16163. shapePaths[0] = capPath(shapePaths[2]);
  16164. shapePaths[1] = shapePaths[2].slice(0);
  16165. break;
  16166. case Mesh.CAP_END:
  16167. shapePaths[index] = shapePaths[index - 1];
  16168. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16169. break;
  16170. case Mesh.CAP_ALL:
  16171. shapePaths[0] = capPath(shapePaths[2]);
  16172. shapePaths[1] = shapePaths[2].slice(0);
  16173. shapePaths[index] = shapePaths[index - 1];
  16174. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16175. break;
  16176. default:
  16177. break;
  16178. }
  16179. return shapePaths;
  16180. };
  16181. var path3D;
  16182. var pathArray;
  16183. if (instance) {
  16184. path3D = (instance.path3D).update(curve);
  16185. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16186. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16187. return instance;
  16188. }
  16189. // extruded shape creation
  16190. path3D = new BABYLON.Path3D(curve);
  16191. var newShapePaths = new Array();
  16192. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16193. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16194. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16195. extrudedGeneric.pathArray = pathArray;
  16196. extrudedGeneric.path3D = path3D;
  16197. extrudedGeneric.cap = cap;
  16198. return extrudedGeneric;
  16199. };
  16200. Mesh.CreateLathe = function (name, options, radiusOrScene, tessellation, scene, updatable, sideOrientation) {
  16201. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16202. var shape;
  16203. var radius;
  16204. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  16205. var closed = (options.closed === undefined) ? true : options.closed;
  16206. if (Array.isArray(options)) {
  16207. shape = options;
  16208. radius = radiusOrScene || 1;
  16209. tessellation = tessellation || 64;
  16210. }
  16211. else {
  16212. scene = radiusOrScene;
  16213. shape = options.shape;
  16214. radius = options.radius || 1;
  16215. tessellation = options.tessellation || 64;
  16216. updatable = options.updatable;
  16217. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  16218. }
  16219. var pi2 = Math.PI * 2;
  16220. var shapeLathe = new Array();
  16221. // first rotatable point
  16222. var i = 0;
  16223. while (shape[i].x === 0) {
  16224. i++;
  16225. }
  16226. var pt = shape[i];
  16227. for (i = 0; i < shape.length; i++) {
  16228. shapeLathe.push(shape[i].subtract(pt));
  16229. }
  16230. // circle path
  16231. var step = pi2 / tessellation * arc;
  16232. var rotated;
  16233. var path = new Array();
  16234. ;
  16235. for (i = 0; i <= tessellation; i++) {
  16236. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  16237. path.push(rotated);
  16238. }
  16239. if (closed) {
  16240. path.push(path[0]);
  16241. }
  16242. // extrusion
  16243. var scaleFunction = function () { return 1; };
  16244. var rotateFunction = function () { return 0; };
  16245. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  16246. return lathe;
  16247. };
  16248. Mesh.CreatePlane = function (name, options, scene, updatable, sideOrientation) {
  16249. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16250. if (typeof options === 'number') {
  16251. var size = options;
  16252. options = {
  16253. size: size,
  16254. width: size,
  16255. height: size,
  16256. sideOrientation: sideOrientation
  16257. };
  16258. }
  16259. var plane = new Mesh(name, scene);
  16260. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16261. vertexData.applyToMesh(plane, updatable || options.updatable);
  16262. return plane;
  16263. };
  16264. Mesh.CreateGround = function (name, options, heightOrScene, subdivisions, scene, updatable) {
  16265. if (heightOrScene instanceof BABYLON.Scene) {
  16266. scene = heightOrScene;
  16267. updatable = options.updatable;
  16268. }
  16269. else {
  16270. var width = options;
  16271. options = {
  16272. width: width,
  16273. height: heightOrScene,
  16274. subdivisions: subdivisions
  16275. };
  16276. }
  16277. var ground = new BABYLON.GroundMesh(name, scene);
  16278. ground._setReady(false);
  16279. ground._subdivisions = options.subdivisions || 1;
  16280. var vertexData = BABYLON.VertexData.CreateGround(options);
  16281. vertexData.applyToMesh(ground, updatable || options.updatable);
  16282. ground._setReady(true);
  16283. return ground;
  16284. };
  16285. Mesh.CreateTiledGround = function (name, options, zminOrScene, xmax, zmax, subdivisions, precision, scene, updatable) {
  16286. var xmin;
  16287. var zmin;
  16288. if (typeof options === 'number') {
  16289. xmin = options || -1;
  16290. zmin = zminOrScene || -1;
  16291. xmax = xmax || 1;
  16292. zmax = zmax || 1;
  16293. subdivisions = subdivisions || { w: 6, h: 6 };
  16294. precision = precision || { w: 2, h: 2 };
  16295. }
  16296. else {
  16297. scene = zminOrScene;
  16298. xmin = options.xmin || -1;
  16299. zmin = options.zmin || -1;
  16300. xmax = options.xmax || 1;
  16301. zmax = options.zmax || 1;
  16302. subdivisions = options.subdivisions || { w: 6, h: 6 };
  16303. precision = options.precision || { w: 2, h: 2 };
  16304. }
  16305. var tiledGround = new Mesh(name, scene);
  16306. var vertexData = BABYLON.VertexData.CreateTiledGround({ xmin: xmin, zmin: zmin, xmax: xmax, zmax: zmax, subdivisions: subdivisions, precision: precision });
  16307. vertexData.applyToMesh(tiledGround, updatable);
  16308. return tiledGround;
  16309. };
  16310. Mesh.CreateGroundFromHeightMap = function (name, url, widthOrOptions, heightorScene, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16311. var width;
  16312. var height;
  16313. if (typeof widthOrOptions === "number") {
  16314. width = widthOrOptions;
  16315. height = heightorScene;
  16316. }
  16317. else {
  16318. width = widthOrOptions.width || 10;
  16319. height = widthOrOptions.height || 10;
  16320. subdivisions = widthOrOptions.subdivisions || 1;
  16321. minHeight = widthOrOptions.minHeight;
  16322. maxHeight = widthOrOptions.maxHeight || 10;
  16323. updatable = widthOrOptions.updatable;
  16324. onReady = widthOrOptions.onReady;
  16325. scene = heightorScene;
  16326. }
  16327. var ground = new BABYLON.GroundMesh(name, scene);
  16328. ground._subdivisions = subdivisions;
  16329. ground._setReady(false);
  16330. var onload = function (img) {
  16331. // Getting height map data
  16332. var canvas = document.createElement("canvas");
  16333. var context = canvas.getContext("2d");
  16334. var bufferWidth = img.width;
  16335. var bufferHeight = img.height;
  16336. canvas.width = bufferWidth;
  16337. canvas.height = bufferHeight;
  16338. context.drawImage(img, 0, 0);
  16339. // Create VertexData from map data
  16340. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16341. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16342. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16343. width: width, height: height,
  16344. subdivisions: subdivisions,
  16345. minHeight: minHeight, maxHeight: maxHeight,
  16346. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16347. });
  16348. vertexData.applyToMesh(ground, updatable);
  16349. ground._setReady(true);
  16350. //execute ready callback, if set
  16351. if (onReady) {
  16352. onReady(ground);
  16353. }
  16354. };
  16355. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16356. return ground;
  16357. };
  16358. Mesh.CreateTube = function (name, options, radiusOrScene, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16359. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16360. if (instance === void 0) { instance = null; }
  16361. var path;
  16362. var radius;
  16363. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  16364. ;
  16365. if (Array.isArray(options)) {
  16366. path = options;
  16367. radius = radiusOrScene;
  16368. }
  16369. else {
  16370. scene = radiusOrScene;
  16371. path = options.path;
  16372. radius = options.radius || 1;
  16373. tessellation = options.tessellation || 64;
  16374. radiusFunction = options.radiusFunction;
  16375. cap = options.cap || Mesh.NO_CAP,
  16376. updatable = options.updatable;
  16377. sideOrientation = options.sideOrientation || Mesh.DEFAULTSIDE,
  16378. instance = options.instance;
  16379. }
  16380. // tube geometry
  16381. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16382. var tangents = path3D.getTangents();
  16383. var normals = path3D.getNormals();
  16384. var distances = path3D.getDistances();
  16385. var pi2 = Math.PI * 2;
  16386. var step = pi2 / tessellation * arc;
  16387. var returnRadius = function (i, distance) { return radius; };
  16388. var radiusFunctionFinal = radiusFunction || returnRadius;
  16389. var circlePath;
  16390. var rad;
  16391. var normal;
  16392. var rotated;
  16393. var rotationMatrix = BABYLON.Matrix.Zero();
  16394. var index = (cap === Mesh._NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  16395. for (var i = 0; i < path.length; i++) {
  16396. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16397. circlePath = Array(); // current circle array
  16398. normal = normals[i]; // current normal
  16399. for (var t = 0; t < tessellation; t++) {
  16400. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16401. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16402. circlePath.push(rotated);
  16403. }
  16404. circlePaths[index] = circlePath;
  16405. index++;
  16406. }
  16407. // cap
  16408. var capPath = function (nbPoints, pathIndex) {
  16409. var pointCap = Array();
  16410. for (var i = 0; i < nbPoints; i++) {
  16411. pointCap.push(path[pathIndex]);
  16412. }
  16413. return pointCap;
  16414. };
  16415. switch (cap) {
  16416. case Mesh.NO_CAP:
  16417. break;
  16418. case Mesh.CAP_START:
  16419. circlePaths[0] = capPath(tessellation, 0);
  16420. circlePaths[1] = circlePaths[2].slice(0);
  16421. break;
  16422. case Mesh.CAP_END:
  16423. circlePaths[index] = circlePaths[index - 1].slice(0);
  16424. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16425. break;
  16426. case Mesh.CAP_ALL:
  16427. circlePaths[0] = capPath(tessellation, 0);
  16428. circlePaths[1] = circlePaths[2].slice(0);
  16429. circlePaths[index] = circlePaths[index - 1].slice(0);
  16430. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16431. break;
  16432. default:
  16433. break;
  16434. }
  16435. return circlePaths;
  16436. };
  16437. var path3D;
  16438. var pathArray;
  16439. if (instance) {
  16440. arc = arc || instance.arc;
  16441. path3D = (instance.path3D).update(path);
  16442. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16443. instance = Mesh.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16444. instance.path3D = path3D;
  16445. instance.pathArray = pathArray;
  16446. instance.arc = arc;
  16447. return instance;
  16448. }
  16449. // tube creation
  16450. path3D = new BABYLON.Path3D(path);
  16451. var newPathArray = new Array();
  16452. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16453. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, arc);
  16454. var tube = Mesh.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16455. tube.pathArray = pathArray;
  16456. tube.path3D = path3D;
  16457. tube.tessellation = tessellation;
  16458. tube.cap = cap;
  16459. tube.arc = arc;
  16460. return tube;
  16461. };
  16462. Mesh.CreateDecal = function (name, sourceMesh, positionOrOptions, normal, size, angle) {
  16463. if (angle === void 0) { angle = 0; }
  16464. var indices = sourceMesh.getIndices();
  16465. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16466. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16467. var position;
  16468. if (positionOrOptions instanceof BABYLON.Vector3) {
  16469. position = positionOrOptions;
  16470. }
  16471. else {
  16472. position = positionOrOptions.position || BABYLON.Vector3.Zero();
  16473. normal = positionOrOptions.normal || BABYLON.Vector3.Up();
  16474. size = positionOrOptions.size || new BABYLON.Vector3(1, 1, 1);
  16475. angle = positionOrOptions.angle;
  16476. }
  16477. // Getting correct rotation
  16478. if (!normal) {
  16479. var target = new BABYLON.Vector3(0, 0, 1);
  16480. var camera = sourceMesh.getScene().activeCamera;
  16481. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16482. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16483. }
  16484. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16485. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16486. var pitch = Math.atan2(normal.y, len);
  16487. // Matrix
  16488. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16489. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16490. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16491. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16492. var vertexData = new BABYLON.VertexData();
  16493. vertexData.indices = [];
  16494. vertexData.positions = [];
  16495. vertexData.normals = [];
  16496. vertexData.uvs = [];
  16497. var currentVertexDataIndex = 0;
  16498. var extractDecalVector3 = function (indexId) {
  16499. var vertexId = indices[indexId];
  16500. var result = new BABYLON.PositionNormalVertex();
  16501. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16502. // Send vector to decal local world
  16503. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16504. // Get normal
  16505. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16506. return result;
  16507. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16508. var clip = function (vertices, axis) {
  16509. if (vertices.length === 0) {
  16510. return vertices;
  16511. }
  16512. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16513. var clipVertices = function (v0, v1) {
  16514. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16515. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16516. };
  16517. var result = new Array();
  16518. for (var index = 0; index < vertices.length; index += 3) {
  16519. var v1Out;
  16520. var v2Out;
  16521. var v3Out;
  16522. var total = 0;
  16523. var nV1, nV2, nV3, nV4;
  16524. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16525. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16526. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16527. v1Out = d1 > 0;
  16528. v2Out = d2 > 0;
  16529. v3Out = d3 > 0;
  16530. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16531. switch (total) {
  16532. case 0:
  16533. result.push(vertices[index]);
  16534. result.push(vertices[index + 1]);
  16535. result.push(vertices[index + 2]);
  16536. break;
  16537. case 1:
  16538. if (v1Out) {
  16539. nV1 = vertices[index + 1];
  16540. nV2 = vertices[index + 2];
  16541. nV3 = clipVertices(vertices[index], nV1);
  16542. nV4 = clipVertices(vertices[index], nV2);
  16543. }
  16544. if (v2Out) {
  16545. nV1 = vertices[index];
  16546. nV2 = vertices[index + 2];
  16547. nV3 = clipVertices(vertices[index + 1], nV1);
  16548. nV4 = clipVertices(vertices[index + 1], nV2);
  16549. result.push(nV3);
  16550. result.push(nV2.clone());
  16551. result.push(nV1.clone());
  16552. result.push(nV2.clone());
  16553. result.push(nV3.clone());
  16554. result.push(nV4);
  16555. break;
  16556. }
  16557. if (v3Out) {
  16558. nV1 = vertices[index];
  16559. nV2 = vertices[index + 1];
  16560. nV3 = clipVertices(vertices[index + 2], nV1);
  16561. nV4 = clipVertices(vertices[index + 2], nV2);
  16562. }
  16563. result.push(nV1.clone());
  16564. result.push(nV2.clone());
  16565. result.push(nV3);
  16566. result.push(nV4);
  16567. result.push(nV3.clone());
  16568. result.push(nV2.clone());
  16569. break;
  16570. case 2:
  16571. if (!v1Out) {
  16572. nV1 = vertices[index].clone();
  16573. nV2 = clipVertices(nV1, vertices[index + 1]);
  16574. nV3 = clipVertices(nV1, vertices[index + 2]);
  16575. result.push(nV1);
  16576. result.push(nV2);
  16577. result.push(nV3);
  16578. }
  16579. if (!v2Out) {
  16580. nV1 = vertices[index + 1].clone();
  16581. nV2 = clipVertices(nV1, vertices[index + 2]);
  16582. nV3 = clipVertices(nV1, vertices[index]);
  16583. result.push(nV1);
  16584. result.push(nV2);
  16585. result.push(nV3);
  16586. }
  16587. if (!v3Out) {
  16588. nV1 = vertices[index + 2].clone();
  16589. nV2 = clipVertices(nV1, vertices[index]);
  16590. nV3 = clipVertices(nV1, vertices[index + 1]);
  16591. result.push(nV1);
  16592. result.push(nV2);
  16593. result.push(nV3);
  16594. }
  16595. break;
  16596. case 3:
  16597. break;
  16598. }
  16599. }
  16600. return result;
  16601. };
  16602. for (var index = 0; index < indices.length; index += 3) {
  16603. var faceVertices = new Array();
  16604. faceVertices.push(extractDecalVector3(index));
  16605. faceVertices.push(extractDecalVector3(index + 1));
  16606. faceVertices.push(extractDecalVector3(index + 2));
  16607. // Clip
  16608. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16609. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16610. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16611. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16612. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16613. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16614. if (faceVertices.length === 0) {
  16615. continue;
  16616. }
  16617. // Add UVs and get back to world
  16618. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16619. var vertex = faceVertices[vIndex];
  16620. vertexData.indices.push(currentVertexDataIndex);
  16621. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16622. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16623. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16624. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16625. currentVertexDataIndex++;
  16626. }
  16627. }
  16628. // Return mesh
  16629. var decal = new Mesh(name, sourceMesh.getScene());
  16630. vertexData.applyToMesh(decal);
  16631. decal.position = position.clone();
  16632. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16633. return decal;
  16634. };
  16635. // Skeletons
  16636. /**
  16637. * Update the vertex buffers by applying transformation from the bones
  16638. * @param {skeleton} skeleton to apply
  16639. */
  16640. Mesh.prototype.applySkeleton = function (skeleton) {
  16641. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16642. return this;
  16643. }
  16644. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16645. return this;
  16646. }
  16647. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16648. return this;
  16649. }
  16650. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16651. return this;
  16652. }
  16653. var source;
  16654. if (!this._sourcePositions) {
  16655. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16656. this._sourcePositions = new Float32Array(source);
  16657. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16658. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16659. }
  16660. }
  16661. if (!this._sourceNormals) {
  16662. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16663. this._sourceNormals = new Float32Array(source);
  16664. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16665. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16666. }
  16667. }
  16668. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16669. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16670. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16671. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16672. var skeletonMatrices = skeleton.getTransformMatrices();
  16673. var tempVector3 = BABYLON.Vector3.Zero();
  16674. var finalMatrix = new BABYLON.Matrix();
  16675. var tempMatrix = new BABYLON.Matrix();
  16676. for (var index = 0; index < positionsData.length; index += 3) {
  16677. var index4 = (index / 3) * 4;
  16678. var matricesWeight0 = matricesWeightsData[index4];
  16679. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16680. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16681. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16682. if (matricesWeight0 > 0) {
  16683. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16684. finalMatrix.addToSelf(tempMatrix);
  16685. }
  16686. if (matricesWeight1 > 0) {
  16687. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16688. finalMatrix.addToSelf(tempMatrix);
  16689. }
  16690. if (matricesWeight2 > 0) {
  16691. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16692. finalMatrix.addToSelf(tempMatrix);
  16693. }
  16694. if (matricesWeight3 > 0) {
  16695. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16696. finalMatrix.addToSelf(tempMatrix);
  16697. }
  16698. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16699. tempVector3.toArray(positionsData, index);
  16700. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16701. tempVector3.toArray(normalsData, index);
  16702. finalMatrix.reset();
  16703. }
  16704. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16705. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16706. return this;
  16707. };
  16708. // Tools
  16709. Mesh.MinMax = function (meshes) {
  16710. var minVector = null;
  16711. var maxVector = null;
  16712. for (var i in meshes) {
  16713. var mesh = meshes[i];
  16714. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16715. if (!minVector) {
  16716. minVector = boundingBox.minimumWorld;
  16717. maxVector = boundingBox.maximumWorld;
  16718. continue;
  16719. }
  16720. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16721. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16722. }
  16723. return {
  16724. min: minVector,
  16725. max: maxVector
  16726. };
  16727. };
  16728. Mesh.Center = function (meshesOrMinMaxVector) {
  16729. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16730. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16731. };
  16732. /**
  16733. * Merge the array of meshes into a single mesh for performance reasons.
  16734. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16735. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16736. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16737. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16738. */
  16739. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16740. if (disposeSource === void 0) { disposeSource = true; }
  16741. var index;
  16742. if (!allow32BitsIndices) {
  16743. var totalVertices = 0;
  16744. // Counting vertices
  16745. for (index = 0; index < meshes.length; index++) {
  16746. if (meshes[index]) {
  16747. totalVertices += meshes[index].getTotalVertices();
  16748. if (totalVertices > 65536) {
  16749. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16750. return null;
  16751. }
  16752. }
  16753. }
  16754. }
  16755. // Merge
  16756. var vertexData;
  16757. var otherVertexData;
  16758. var source;
  16759. for (index = 0; index < meshes.length; index++) {
  16760. if (meshes[index]) {
  16761. meshes[index].computeWorldMatrix(true);
  16762. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16763. otherVertexData.transform(meshes[index].getWorldMatrix());
  16764. if (vertexData) {
  16765. vertexData.merge(otherVertexData);
  16766. }
  16767. else {
  16768. vertexData = otherVertexData;
  16769. source = meshes[index];
  16770. }
  16771. }
  16772. }
  16773. if (!meshSubclass) {
  16774. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16775. }
  16776. vertexData.applyToMesh(meshSubclass);
  16777. // Setting properties
  16778. meshSubclass.material = source.material;
  16779. meshSubclass.checkCollisions = source.checkCollisions;
  16780. // Cleaning
  16781. if (disposeSource) {
  16782. for (index = 0; index < meshes.length; index++) {
  16783. if (meshes[index]) {
  16784. meshes[index].dispose();
  16785. }
  16786. }
  16787. }
  16788. return meshSubclass;
  16789. };
  16790. // Consts
  16791. Mesh._FRONTSIDE = 0;
  16792. Mesh._BACKSIDE = 1;
  16793. Mesh._DOUBLESIDE = 2;
  16794. Mesh._DEFAULTSIDE = 0;
  16795. Mesh._NO_CAP = 0;
  16796. Mesh._CAP_START = 1;
  16797. Mesh._CAP_END = 2;
  16798. Mesh._CAP_ALL = 3;
  16799. return Mesh;
  16800. })(BABYLON.AbstractMesh);
  16801. BABYLON.Mesh = Mesh;
  16802. })(BABYLON || (BABYLON = {}));
  16803. var BABYLON;
  16804. (function (BABYLON) {
  16805. var SubMesh = (function () {
  16806. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16807. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16808. this.materialIndex = materialIndex;
  16809. this.verticesStart = verticesStart;
  16810. this.verticesCount = verticesCount;
  16811. this.indexStart = indexStart;
  16812. this.indexCount = indexCount;
  16813. this._renderId = 0;
  16814. this._mesh = mesh;
  16815. this._renderingMesh = renderingMesh || mesh;
  16816. mesh.subMeshes.push(this);
  16817. this._trianglePlanes = [];
  16818. this._id = mesh.subMeshes.length - 1;
  16819. if (createBoundingBox) {
  16820. this.refreshBoundingInfo();
  16821. mesh.computeWorldMatrix(true);
  16822. }
  16823. }
  16824. SubMesh.prototype.getBoundingInfo = function () {
  16825. return this._boundingInfo;
  16826. };
  16827. SubMesh.prototype.getMesh = function () {
  16828. return this._mesh;
  16829. };
  16830. SubMesh.prototype.getRenderingMesh = function () {
  16831. return this._renderingMesh;
  16832. };
  16833. SubMesh.prototype.getMaterial = function () {
  16834. var rootMaterial = this._renderingMesh.material;
  16835. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16836. var multiMaterial = rootMaterial;
  16837. return multiMaterial.getSubMaterial(this.materialIndex);
  16838. }
  16839. if (!rootMaterial) {
  16840. return this._mesh.getScene().defaultMaterial;
  16841. }
  16842. return rootMaterial;
  16843. };
  16844. // Methods
  16845. SubMesh.prototype.refreshBoundingInfo = function () {
  16846. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16847. if (!data) {
  16848. this._boundingInfo = this._mesh._boundingInfo;
  16849. return;
  16850. }
  16851. var indices = this._renderingMesh.getIndices();
  16852. var extend;
  16853. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16854. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16855. }
  16856. else {
  16857. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16858. }
  16859. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16860. };
  16861. SubMesh.prototype._checkCollision = function (collider) {
  16862. return this._boundingInfo._checkCollision(collider);
  16863. };
  16864. SubMesh.prototype.updateBoundingInfo = function (world) {
  16865. if (!this._boundingInfo) {
  16866. this.refreshBoundingInfo();
  16867. }
  16868. this._boundingInfo._update(world);
  16869. };
  16870. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16871. return this._boundingInfo.isInFrustum(frustumPlanes);
  16872. };
  16873. SubMesh.prototype.render = function (enableAlphaMode) {
  16874. this._renderingMesh.render(this, enableAlphaMode);
  16875. };
  16876. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16877. if (!this._linesIndexBuffer) {
  16878. var linesIndices = [];
  16879. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16880. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16881. }
  16882. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16883. this.linesIndexCount = linesIndices.length;
  16884. }
  16885. return this._linesIndexBuffer;
  16886. };
  16887. SubMesh.prototype.canIntersects = function (ray) {
  16888. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16889. };
  16890. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16891. var intersectInfo = null;
  16892. // Triangles test
  16893. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16894. var p0 = positions[indices[index]];
  16895. var p1 = positions[indices[index + 1]];
  16896. var p2 = positions[indices[index + 2]];
  16897. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16898. if (currentIntersectInfo) {
  16899. if (currentIntersectInfo.distance < 0) {
  16900. continue;
  16901. }
  16902. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16903. intersectInfo = currentIntersectInfo;
  16904. intersectInfo.faceId = index / 3;
  16905. if (fastCheck) {
  16906. break;
  16907. }
  16908. }
  16909. }
  16910. }
  16911. return intersectInfo;
  16912. };
  16913. // Clone
  16914. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16915. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16916. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16917. return result;
  16918. };
  16919. // Dispose
  16920. SubMesh.prototype.dispose = function () {
  16921. if (this._linesIndexBuffer) {
  16922. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16923. this._linesIndexBuffer = null;
  16924. }
  16925. // Remove from mesh
  16926. var index = this._mesh.subMeshes.indexOf(this);
  16927. this._mesh.subMeshes.splice(index, 1);
  16928. };
  16929. // Statics
  16930. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16931. var minVertexIndex = Number.MAX_VALUE;
  16932. var maxVertexIndex = -Number.MAX_VALUE;
  16933. renderingMesh = renderingMesh || mesh;
  16934. var indices = renderingMesh.getIndices();
  16935. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16936. var vertexIndex = indices[index];
  16937. if (vertexIndex < minVertexIndex)
  16938. minVertexIndex = vertexIndex;
  16939. if (vertexIndex > maxVertexIndex)
  16940. maxVertexIndex = vertexIndex;
  16941. }
  16942. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16943. };
  16944. return SubMesh;
  16945. })();
  16946. BABYLON.SubMesh = SubMesh;
  16947. })(BABYLON || (BABYLON = {}));
  16948. var BABYLON;
  16949. (function (BABYLON) {
  16950. var BaseTexture = (function () {
  16951. function BaseTexture(scene) {
  16952. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16953. this.hasAlpha = false;
  16954. this.getAlphaFromRGB = false;
  16955. this.level = 1;
  16956. this.isCube = false;
  16957. this.isRenderTarget = false;
  16958. this.animations = new Array();
  16959. this.coordinatesIndex = 0;
  16960. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16961. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16962. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16963. this.anisotropicFilteringLevel = 4;
  16964. this._scene = scene;
  16965. this._scene.textures.push(this);
  16966. }
  16967. BaseTexture.prototype.getScene = function () {
  16968. return this._scene;
  16969. };
  16970. BaseTexture.prototype.getTextureMatrix = function () {
  16971. return null;
  16972. };
  16973. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16974. return null;
  16975. };
  16976. BaseTexture.prototype.getInternalTexture = function () {
  16977. return this._texture;
  16978. };
  16979. BaseTexture.prototype.isReady = function () {
  16980. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16981. return true;
  16982. }
  16983. if (this._texture) {
  16984. return this._texture.isReady;
  16985. }
  16986. return false;
  16987. };
  16988. BaseTexture.prototype.getSize = function () {
  16989. if (this._texture._width) {
  16990. return { width: this._texture._width, height: this._texture._height };
  16991. }
  16992. if (this._texture._size) {
  16993. return { width: this._texture._size, height: this._texture._size };
  16994. }
  16995. return { width: 0, height: 0 };
  16996. };
  16997. BaseTexture.prototype.getBaseSize = function () {
  16998. if (!this.isReady())
  16999. return { width: 0, height: 0 };
  17000. if (this._texture._size) {
  17001. return { width: this._texture._size, height: this._texture._size };
  17002. }
  17003. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17004. };
  17005. BaseTexture.prototype.scale = function (ratio) {
  17006. };
  17007. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17008. get: function () {
  17009. return false;
  17010. },
  17011. enumerable: true,
  17012. configurable: true
  17013. });
  17014. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17015. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17016. for (var index = 0; index < texturesCache.length; index++) {
  17017. var texturesCacheEntry = texturesCache[index];
  17018. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17019. texturesCache.splice(index, 1);
  17020. return;
  17021. }
  17022. }
  17023. };
  17024. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17025. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17026. for (var index = 0; index < texturesCache.length; index++) {
  17027. var texturesCacheEntry = texturesCache[index];
  17028. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17029. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17030. texturesCacheEntry.references++;
  17031. return texturesCacheEntry;
  17032. }
  17033. }
  17034. }
  17035. return null;
  17036. };
  17037. BaseTexture.prototype.delayLoad = function () {
  17038. };
  17039. BaseTexture.prototype.clone = function () {
  17040. return null;
  17041. };
  17042. BaseTexture.prototype.releaseInternalTexture = function () {
  17043. if (this._texture) {
  17044. this._scene.getEngine().releaseInternalTexture(this._texture);
  17045. delete this._texture;
  17046. }
  17047. };
  17048. BaseTexture.prototype.dispose = function () {
  17049. // Remove from scene
  17050. var index = this._scene.textures.indexOf(this);
  17051. if (index >= 0) {
  17052. this._scene.textures.splice(index, 1);
  17053. }
  17054. if (this._texture === undefined) {
  17055. return;
  17056. }
  17057. // Callback
  17058. if (this.onDispose) {
  17059. this.onDispose();
  17060. }
  17061. };
  17062. return BaseTexture;
  17063. })();
  17064. BABYLON.BaseTexture = BaseTexture;
  17065. })(BABYLON || (BABYLON = {}));
  17066. var BABYLON;
  17067. (function (BABYLON) {
  17068. var Texture = (function (_super) {
  17069. __extends(Texture, _super);
  17070. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17071. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17072. if (onLoad === void 0) { onLoad = null; }
  17073. if (onError === void 0) { onError = null; }
  17074. if (buffer === void 0) { buffer = null; }
  17075. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17076. _super.call(this, scene);
  17077. this.uOffset = 0;
  17078. this.vOffset = 0;
  17079. this.uScale = 1.0;
  17080. this.vScale = 1.0;
  17081. this.uAng = 0;
  17082. this.vAng = 0;
  17083. this.wAng = 0;
  17084. this.name = url;
  17085. this.url = url;
  17086. this._noMipmap = noMipmap;
  17087. this._invertY = invertY;
  17088. this._samplingMode = samplingMode;
  17089. this._buffer = buffer;
  17090. this._deleteBuffer = deleteBuffer;
  17091. if (!url) {
  17092. return;
  17093. }
  17094. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17095. if (!this._texture) {
  17096. if (!scene.useDelayedTextureLoading) {
  17097. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17098. if (deleteBuffer) {
  17099. delete this._buffer;
  17100. }
  17101. }
  17102. else {
  17103. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17104. }
  17105. }
  17106. else {
  17107. BABYLON.Tools.SetImmediate(function () {
  17108. if (onLoad) {
  17109. onLoad();
  17110. }
  17111. });
  17112. }
  17113. }
  17114. Texture.prototype.delayLoad = function () {
  17115. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17116. return;
  17117. }
  17118. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17119. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17120. if (!this._texture) {
  17121. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17122. if (this._deleteBuffer) {
  17123. delete this._buffer;
  17124. }
  17125. }
  17126. };
  17127. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17128. if (!this._texture) {
  17129. return;
  17130. }
  17131. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17132. };
  17133. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17134. x *= this.uScale;
  17135. y *= this.vScale;
  17136. x -= 0.5 * this.uScale;
  17137. y -= 0.5 * this.vScale;
  17138. z -= 0.5;
  17139. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17140. t.x += 0.5 * this.uScale + this.uOffset;
  17141. t.y += 0.5 * this.vScale + this.vOffset;
  17142. t.z += 0.5;
  17143. };
  17144. Texture.prototype.getTextureMatrix = function () {
  17145. if (this.uOffset === this._cachedUOffset &&
  17146. this.vOffset === this._cachedVOffset &&
  17147. this.uScale === this._cachedUScale &&
  17148. this.vScale === this._cachedVScale &&
  17149. this.uAng === this._cachedUAng &&
  17150. this.vAng === this._cachedVAng &&
  17151. this.wAng === this._cachedWAng) {
  17152. return this._cachedTextureMatrix;
  17153. }
  17154. this._cachedUOffset = this.uOffset;
  17155. this._cachedVOffset = this.vOffset;
  17156. this._cachedUScale = this.uScale;
  17157. this._cachedVScale = this.vScale;
  17158. this._cachedUAng = this.uAng;
  17159. this._cachedVAng = this.vAng;
  17160. this._cachedWAng = this.wAng;
  17161. if (!this._cachedTextureMatrix) {
  17162. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17163. this._rowGenerationMatrix = new BABYLON.Matrix();
  17164. this._t0 = BABYLON.Vector3.Zero();
  17165. this._t1 = BABYLON.Vector3.Zero();
  17166. this._t2 = BABYLON.Vector3.Zero();
  17167. }
  17168. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17169. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17170. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17171. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17172. this._t1.subtractInPlace(this._t0);
  17173. this._t2.subtractInPlace(this._t0);
  17174. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17175. this._cachedTextureMatrix.m[0] = this._t1.x;
  17176. this._cachedTextureMatrix.m[1] = this._t1.y;
  17177. this._cachedTextureMatrix.m[2] = this._t1.z;
  17178. this._cachedTextureMatrix.m[4] = this._t2.x;
  17179. this._cachedTextureMatrix.m[5] = this._t2.y;
  17180. this._cachedTextureMatrix.m[6] = this._t2.z;
  17181. this._cachedTextureMatrix.m[8] = this._t0.x;
  17182. this._cachedTextureMatrix.m[9] = this._t0.y;
  17183. this._cachedTextureMatrix.m[10] = this._t0.z;
  17184. return this._cachedTextureMatrix;
  17185. };
  17186. Texture.prototype.getReflectionTextureMatrix = function () {
  17187. if (this.uOffset === this._cachedUOffset &&
  17188. this.vOffset === this._cachedVOffset &&
  17189. this.uScale === this._cachedUScale &&
  17190. this.vScale === this._cachedVScale &&
  17191. this.coordinatesMode === this._cachedCoordinatesMode) {
  17192. return this._cachedTextureMatrix;
  17193. }
  17194. if (!this._cachedTextureMatrix) {
  17195. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17196. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17197. }
  17198. this._cachedCoordinatesMode = this.coordinatesMode;
  17199. switch (this.coordinatesMode) {
  17200. case Texture.SPHERICAL_MODE:
  17201. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17202. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  17203. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  17204. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  17205. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  17206. break;
  17207. case Texture.PLANAR_MODE:
  17208. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17209. this._cachedTextureMatrix[0] = this.uScale;
  17210. this._cachedTextureMatrix[5] = this.vScale;
  17211. this._cachedTextureMatrix[12] = this.uOffset;
  17212. this._cachedTextureMatrix[13] = this.vOffset;
  17213. break;
  17214. case Texture.PROJECTION_MODE:
  17215. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17216. this._projectionModeMatrix.m[0] = 0.5;
  17217. this._projectionModeMatrix.m[5] = -0.5;
  17218. this._projectionModeMatrix.m[10] = 0.0;
  17219. this._projectionModeMatrix.m[12] = 0.5;
  17220. this._projectionModeMatrix.m[13] = 0.5;
  17221. this._projectionModeMatrix.m[14] = 1.0;
  17222. this._projectionModeMatrix.m[15] = 1.0;
  17223. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17224. break;
  17225. default:
  17226. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17227. break;
  17228. }
  17229. return this._cachedTextureMatrix;
  17230. };
  17231. Texture.prototype.clone = function () {
  17232. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17233. // Base texture
  17234. newTexture.hasAlpha = this.hasAlpha;
  17235. newTexture.level = this.level;
  17236. newTexture.wrapU = this.wrapU;
  17237. newTexture.wrapV = this.wrapV;
  17238. newTexture.coordinatesIndex = this.coordinatesIndex;
  17239. newTexture.coordinatesMode = this.coordinatesMode;
  17240. // Texture
  17241. newTexture.uOffset = this.uOffset;
  17242. newTexture.vOffset = this.vOffset;
  17243. newTexture.uScale = this.uScale;
  17244. newTexture.vScale = this.vScale;
  17245. newTexture.uAng = this.uAng;
  17246. newTexture.vAng = this.vAng;
  17247. newTexture.wAng = this.wAng;
  17248. return newTexture;
  17249. };
  17250. // Statics
  17251. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17252. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17253. if (onLoad === void 0) { onLoad = null; }
  17254. if (onError === void 0) { onError = null; }
  17255. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17256. };
  17257. // Constants
  17258. Texture.NEAREST_SAMPLINGMODE = 1;
  17259. Texture.BILINEAR_SAMPLINGMODE = 2;
  17260. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17261. Texture.EXPLICIT_MODE = 0;
  17262. Texture.SPHERICAL_MODE = 1;
  17263. Texture.PLANAR_MODE = 2;
  17264. Texture.CUBIC_MODE = 3;
  17265. Texture.PROJECTION_MODE = 4;
  17266. Texture.SKYBOX_MODE = 5;
  17267. Texture.INVCUBIC_MODE = 6;
  17268. Texture.CLAMP_ADDRESSMODE = 0;
  17269. Texture.WRAP_ADDRESSMODE = 1;
  17270. Texture.MIRROR_ADDRESSMODE = 2;
  17271. return Texture;
  17272. })(BABYLON.BaseTexture);
  17273. BABYLON.Texture = Texture;
  17274. })(BABYLON || (BABYLON = {}));
  17275. var BABYLON;
  17276. (function (BABYLON) {
  17277. var CubeTexture = (function (_super) {
  17278. __extends(CubeTexture, _super);
  17279. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17280. _super.call(this, scene);
  17281. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17282. this.name = rootUrl;
  17283. this.url = rootUrl;
  17284. this._noMipmap = noMipmap;
  17285. this.hasAlpha = false;
  17286. if (!rootUrl) {
  17287. return;
  17288. }
  17289. this._texture = this._getFromCache(rootUrl, noMipmap);
  17290. if (!extensions) {
  17291. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17292. }
  17293. this._extensions = extensions;
  17294. if (!this._texture) {
  17295. if (!scene.useDelayedTextureLoading) {
  17296. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17297. }
  17298. else {
  17299. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17300. }
  17301. }
  17302. this.isCube = true;
  17303. this._textureMatrix = BABYLON.Matrix.Identity();
  17304. }
  17305. CubeTexture.prototype.clone = function () {
  17306. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17307. // Base texture
  17308. newTexture.level = this.level;
  17309. newTexture.wrapU = this.wrapU;
  17310. newTexture.wrapV = this.wrapV;
  17311. newTexture.coordinatesIndex = this.coordinatesIndex;
  17312. newTexture.coordinatesMode = this.coordinatesMode;
  17313. return newTexture;
  17314. };
  17315. // Methods
  17316. CubeTexture.prototype.delayLoad = function () {
  17317. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17318. return;
  17319. }
  17320. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17321. this._texture = this._getFromCache(this.url, this._noMipmap);
  17322. if (!this._texture) {
  17323. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17324. }
  17325. };
  17326. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17327. return this._textureMatrix;
  17328. };
  17329. return CubeTexture;
  17330. })(BABYLON.BaseTexture);
  17331. BABYLON.CubeTexture = CubeTexture;
  17332. })(BABYLON || (BABYLON = {}));
  17333. var BABYLON;
  17334. (function (BABYLON) {
  17335. var RenderTargetTexture = (function (_super) {
  17336. __extends(RenderTargetTexture, _super);
  17337. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17338. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17339. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17340. if (isCube === void 0) { isCube = false; }
  17341. _super.call(this, null, scene, !generateMipMaps);
  17342. this.isCube = isCube;
  17343. this.renderList = new Array();
  17344. this.renderParticles = true;
  17345. this.renderSprites = false;
  17346. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17347. this._currentRefreshId = -1;
  17348. this._refreshRate = 1;
  17349. this.name = name;
  17350. this.isRenderTarget = true;
  17351. this._size = size;
  17352. this._generateMipMaps = generateMipMaps;
  17353. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17354. if (isCube) {
  17355. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17356. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17357. this._textureMatrix = BABYLON.Matrix.Identity();
  17358. }
  17359. else {
  17360. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17361. }
  17362. // Rendering groups
  17363. this._renderingManager = new BABYLON.RenderingManager(scene);
  17364. }
  17365. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONCE", {
  17366. get: function () {
  17367. return RenderTargetTexture._REFRESHRATE_RENDERONCE;
  17368. },
  17369. enumerable: true,
  17370. configurable: true
  17371. });
  17372. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONEVERYFRAME", {
  17373. get: function () {
  17374. return RenderTargetTexture._REFRESHRATE_RENDERONEVERYFRAME;
  17375. },
  17376. enumerable: true,
  17377. configurable: true
  17378. });
  17379. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONEVERYTWOFRAME", {
  17380. get: function () {
  17381. return RenderTargetTexture._REFRESHRATE_RENDERONEVERYTWOFRAME;
  17382. },
  17383. enumerable: true,
  17384. configurable: true
  17385. });
  17386. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17387. this._currentRefreshId = -1;
  17388. };
  17389. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17390. get: function () {
  17391. return this._refreshRate;
  17392. },
  17393. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17394. set: function (value) {
  17395. this._refreshRate = value;
  17396. this.resetRefreshCounter();
  17397. },
  17398. enumerable: true,
  17399. configurable: true
  17400. });
  17401. RenderTargetTexture.prototype._shouldRender = function () {
  17402. if (this._currentRefreshId === -1) {
  17403. this._currentRefreshId = 1;
  17404. return true;
  17405. }
  17406. if (this.refreshRate === this._currentRefreshId) {
  17407. this._currentRefreshId = 1;
  17408. return true;
  17409. }
  17410. this._currentRefreshId++;
  17411. return false;
  17412. };
  17413. RenderTargetTexture.prototype.isReady = function () {
  17414. if (!this.getScene().renderTargetsEnabled) {
  17415. return false;
  17416. }
  17417. return _super.prototype.isReady.call(this);
  17418. };
  17419. RenderTargetTexture.prototype.getRenderSize = function () {
  17420. return this._size;
  17421. };
  17422. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17423. get: function () {
  17424. return true;
  17425. },
  17426. enumerable: true,
  17427. configurable: true
  17428. });
  17429. RenderTargetTexture.prototype.scale = function (ratio) {
  17430. var newSize = this._size * ratio;
  17431. this.resize(newSize, this._generateMipMaps);
  17432. };
  17433. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17434. if (this.isCube) {
  17435. return this._textureMatrix;
  17436. }
  17437. return _super.prototype.getReflectionTextureMatrix.call(this);
  17438. };
  17439. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17440. this.releaseInternalTexture();
  17441. if (this.isCube) {
  17442. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17443. }
  17444. else {
  17445. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17446. }
  17447. };
  17448. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17449. var scene = this.getScene();
  17450. if (this._waitingRenderList) {
  17451. this.renderList = [];
  17452. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17453. var id = this._waitingRenderList[index];
  17454. this.renderList.push(scene.getMeshByID(id));
  17455. }
  17456. delete this._waitingRenderList;
  17457. }
  17458. if (this.renderList && this.renderList.length === 0) {
  17459. return;
  17460. }
  17461. // Prepare renderingManager
  17462. this._renderingManager.reset();
  17463. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17464. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17465. var mesh = currentRenderList[meshIndex];
  17466. if (mesh) {
  17467. if (!mesh.isReady()) {
  17468. // Reset _currentRefreshId
  17469. this.resetRefreshCounter();
  17470. continue;
  17471. }
  17472. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17473. mesh._activate(scene.getRenderId());
  17474. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17475. var subMesh = mesh.subMeshes[subIndex];
  17476. scene._activeIndices += subMesh.indexCount;
  17477. this._renderingManager.dispatch(subMesh);
  17478. }
  17479. }
  17480. }
  17481. }
  17482. if (this.isCube) {
  17483. for (var face = 0; face < 6; face++) {
  17484. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17485. }
  17486. }
  17487. else {
  17488. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17489. }
  17490. if (this.onAfterUnbind) {
  17491. this.onAfterUnbind();
  17492. }
  17493. scene.resetCachedMaterial();
  17494. };
  17495. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17496. var scene = this.getScene();
  17497. var engine = scene.getEngine();
  17498. // Bind
  17499. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17500. if (this.isCube) {
  17501. engine.bindFramebuffer(this._texture, faceIndex);
  17502. }
  17503. else {
  17504. engine.bindFramebuffer(this._texture);
  17505. }
  17506. }
  17507. if (this.onBeforeRender) {
  17508. this.onBeforeRender(faceIndex);
  17509. }
  17510. // Clear
  17511. if (this.onClear) {
  17512. this.onClear(engine);
  17513. }
  17514. else {
  17515. engine.clear(scene.clearColor, true, true);
  17516. }
  17517. if (!this._doNotChangeAspectRatio) {
  17518. scene.updateTransformMatrix(true);
  17519. }
  17520. // Render
  17521. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17522. if (useCameraPostProcess) {
  17523. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17524. }
  17525. if (!this._doNotChangeAspectRatio) {
  17526. scene.updateTransformMatrix(true);
  17527. }
  17528. if (this.onAfterRender) {
  17529. this.onAfterRender(faceIndex);
  17530. }
  17531. // Dump ?
  17532. if (dumpForDebug) {
  17533. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17534. }
  17535. // Unbind
  17536. if (!this.isCube || faceIndex === 5) {
  17537. if (this.isCube) {
  17538. if (faceIndex === 5) {
  17539. engine.generateMipMapsForCubemap(this._texture);
  17540. }
  17541. }
  17542. engine.unBindFramebuffer(this._texture, true);
  17543. }
  17544. };
  17545. RenderTargetTexture.prototype.clone = function () {
  17546. var textureSize = this.getSize();
  17547. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17548. // Base texture
  17549. newTexture.hasAlpha = this.hasAlpha;
  17550. newTexture.level = this.level;
  17551. // RenderTarget Texture
  17552. newTexture.coordinatesMode = this.coordinatesMode;
  17553. newTexture.renderList = this.renderList.slice(0);
  17554. return newTexture;
  17555. };
  17556. RenderTargetTexture._REFRESHRATE_RENDERONCE = 0;
  17557. RenderTargetTexture._REFRESHRATE_RENDERONEVERYFRAME = 1;
  17558. RenderTargetTexture._REFRESHRATE_RENDERONEVERYTWOFRAME = 2;
  17559. return RenderTargetTexture;
  17560. })(BABYLON.Texture);
  17561. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17562. })(BABYLON || (BABYLON = {}));
  17563. var BABYLON;
  17564. (function (BABYLON) {
  17565. var ProceduralTexture = (function (_super) {
  17566. __extends(ProceduralTexture, _super);
  17567. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17568. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17569. _super.call(this, null, scene, !generateMipMaps);
  17570. this.isEnabled = true;
  17571. this._currentRefreshId = -1;
  17572. this._refreshRate = 1;
  17573. this._vertexDeclaration = [2];
  17574. this._vertexStrideSize = 2 * 4;
  17575. this._uniforms = new Array();
  17576. this._samplers = new Array();
  17577. this._textures = new Array();
  17578. this._floats = new Array();
  17579. this._floatsArrays = {};
  17580. this._colors3 = new Array();
  17581. this._colors4 = new Array();
  17582. this._vectors2 = new Array();
  17583. this._vectors3 = new Array();
  17584. this._matrices = new Array();
  17585. this._fallbackTextureUsed = false;
  17586. scene._proceduralTextures.push(this);
  17587. this.name = name;
  17588. this.isRenderTarget = true;
  17589. this._size = size;
  17590. this._generateMipMaps = generateMipMaps;
  17591. this.setFragment(fragment);
  17592. this._fallbackTexture = fallbackTexture;
  17593. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17594. // VBO
  17595. var vertices = [];
  17596. vertices.push(1, 1);
  17597. vertices.push(-1, 1);
  17598. vertices.push(-1, -1);
  17599. vertices.push(1, -1);
  17600. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17601. // Indices
  17602. var indices = [];
  17603. indices.push(0);
  17604. indices.push(1);
  17605. indices.push(2);
  17606. indices.push(0);
  17607. indices.push(2);
  17608. indices.push(3);
  17609. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17610. }
  17611. ProceduralTexture.prototype.reset = function () {
  17612. if (this._effect === undefined) {
  17613. return;
  17614. }
  17615. var engine = this.getScene().getEngine();
  17616. engine._releaseEffect(this._effect);
  17617. };
  17618. ProceduralTexture.prototype.isReady = function () {
  17619. var _this = this;
  17620. var engine = this.getScene().getEngine();
  17621. var shaders;
  17622. if (!this._fragment) {
  17623. return false;
  17624. }
  17625. if (this._fallbackTextureUsed) {
  17626. return true;
  17627. }
  17628. if (this._fragment.fragmentElement !== undefined) {
  17629. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17630. }
  17631. else {
  17632. shaders = { vertex: "procedural", fragment: this._fragment };
  17633. }
  17634. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17635. _this.releaseInternalTexture();
  17636. if (_this._fallbackTexture) {
  17637. _this._texture = _this._fallbackTexture._texture;
  17638. _this._texture.references++;
  17639. }
  17640. _this._fallbackTextureUsed = true;
  17641. });
  17642. return this._effect.isReady();
  17643. };
  17644. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17645. this._currentRefreshId = -1;
  17646. };
  17647. ProceduralTexture.prototype.setFragment = function (fragment) {
  17648. this._fragment = fragment;
  17649. };
  17650. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17651. get: function () {
  17652. return this._refreshRate;
  17653. },
  17654. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17655. set: function (value) {
  17656. this._refreshRate = value;
  17657. this.resetRefreshCounter();
  17658. },
  17659. enumerable: true,
  17660. configurable: true
  17661. });
  17662. ProceduralTexture.prototype._shouldRender = function () {
  17663. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17664. return false;
  17665. }
  17666. if (this._fallbackTextureUsed) {
  17667. return false;
  17668. }
  17669. if (this._currentRefreshId === -1) {
  17670. this._currentRefreshId = 1;
  17671. return true;
  17672. }
  17673. if (this.refreshRate === this._currentRefreshId) {
  17674. this._currentRefreshId = 1;
  17675. return true;
  17676. }
  17677. this._currentRefreshId++;
  17678. return false;
  17679. };
  17680. ProceduralTexture.prototype.getRenderSize = function () {
  17681. return this._size;
  17682. };
  17683. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17684. if (this._fallbackTextureUsed) {
  17685. return;
  17686. }
  17687. this.releaseInternalTexture();
  17688. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17689. };
  17690. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17691. if (this._uniforms.indexOf(uniformName) === -1) {
  17692. this._uniforms.push(uniformName);
  17693. }
  17694. };
  17695. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17696. if (this._samplers.indexOf(name) === -1) {
  17697. this._samplers.push(name);
  17698. }
  17699. this._textures[name] = texture;
  17700. return this;
  17701. };
  17702. ProceduralTexture.prototype.setFloat = function (name, value) {
  17703. this._checkUniform(name);
  17704. this._floats[name] = value;
  17705. return this;
  17706. };
  17707. ProceduralTexture.prototype.setFloats = function (name, value) {
  17708. this._checkUniform(name);
  17709. this._floatsArrays[name] = value;
  17710. return this;
  17711. };
  17712. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17713. this._checkUniform(name);
  17714. this._colors3[name] = value;
  17715. return this;
  17716. };
  17717. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17718. this._checkUniform(name);
  17719. this._colors4[name] = value;
  17720. return this;
  17721. };
  17722. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17723. this._checkUniform(name);
  17724. this._vectors2[name] = value;
  17725. return this;
  17726. };
  17727. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17728. this._checkUniform(name);
  17729. this._vectors3[name] = value;
  17730. return this;
  17731. };
  17732. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17733. this._checkUniform(name);
  17734. this._matrices[name] = value;
  17735. return this;
  17736. };
  17737. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17738. var scene = this.getScene();
  17739. var engine = scene.getEngine();
  17740. engine.bindFramebuffer(this._texture);
  17741. // Clear
  17742. engine.clear(scene.clearColor, true, true);
  17743. // Render
  17744. engine.enableEffect(this._effect);
  17745. engine.setState(false);
  17746. // Texture
  17747. for (var name in this._textures) {
  17748. this._effect.setTexture(name, this._textures[name]);
  17749. }
  17750. // Float
  17751. for (name in this._floats) {
  17752. this._effect.setFloat(name, this._floats[name]);
  17753. }
  17754. // Floats
  17755. for (name in this._floatsArrays) {
  17756. this._effect.setArray(name, this._floatsArrays[name]);
  17757. }
  17758. // Color3
  17759. for (name in this._colors3) {
  17760. this._effect.setColor3(name, this._colors3[name]);
  17761. }
  17762. // Color4
  17763. for (name in this._colors4) {
  17764. var color = this._colors4[name];
  17765. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17766. }
  17767. // Vector2
  17768. for (name in this._vectors2) {
  17769. this._effect.setVector2(name, this._vectors2[name]);
  17770. }
  17771. // Vector3
  17772. for (name in this._vectors3) {
  17773. this._effect.setVector3(name, this._vectors3[name]);
  17774. }
  17775. // Matrix
  17776. for (name in this._matrices) {
  17777. this._effect.setMatrix(name, this._matrices[name]);
  17778. }
  17779. // VBOs
  17780. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17781. // Draw order
  17782. engine.draw(true, 0, 6);
  17783. // Unbind
  17784. engine.unBindFramebuffer(this._texture);
  17785. };
  17786. ProceduralTexture.prototype.clone = function () {
  17787. var textureSize = this.getSize();
  17788. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17789. // Base texture
  17790. newTexture.hasAlpha = this.hasAlpha;
  17791. newTexture.level = this.level;
  17792. // RenderTarget Texture
  17793. newTexture.coordinatesMode = this.coordinatesMode;
  17794. return newTexture;
  17795. };
  17796. ProceduralTexture.prototype.dispose = function () {
  17797. var index = this.getScene()._proceduralTextures.indexOf(this);
  17798. if (index >= 0) {
  17799. this.getScene()._proceduralTextures.splice(index, 1);
  17800. }
  17801. _super.prototype.dispose.call(this);
  17802. };
  17803. return ProceduralTexture;
  17804. })(BABYLON.Texture);
  17805. BABYLON.ProceduralTexture = ProceduralTexture;
  17806. })(BABYLON || (BABYLON = {}));
  17807. var BABYLON;
  17808. (function (BABYLON) {
  17809. var MirrorTexture = (function (_super) {
  17810. __extends(MirrorTexture, _super);
  17811. function MirrorTexture(name, size, scene, generateMipMaps) {
  17812. var _this = this;
  17813. _super.call(this, name, size, scene, generateMipMaps, true);
  17814. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17815. this._transformMatrix = BABYLON.Matrix.Zero();
  17816. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17817. this.onBeforeRender = function () {
  17818. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17819. _this._savedViewMatrix = scene.getViewMatrix();
  17820. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17821. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17822. scene.clipPlane = _this.mirrorPlane;
  17823. scene.getEngine().cullBackFaces = false;
  17824. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17825. };
  17826. this.onAfterRender = function () {
  17827. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17828. scene.getEngine().cullBackFaces = true;
  17829. scene._mirroredCameraPosition = null;
  17830. delete scene.clipPlane;
  17831. };
  17832. }
  17833. MirrorTexture.prototype.clone = function () {
  17834. var textureSize = this.getSize();
  17835. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17836. // Base texture
  17837. newTexture.hasAlpha = this.hasAlpha;
  17838. newTexture.level = this.level;
  17839. // Mirror Texture
  17840. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17841. newTexture.renderList = this.renderList.slice(0);
  17842. return newTexture;
  17843. };
  17844. return MirrorTexture;
  17845. })(BABYLON.RenderTargetTexture);
  17846. BABYLON.MirrorTexture = MirrorTexture;
  17847. })(BABYLON || (BABYLON = {}));
  17848. var BABYLON;
  17849. (function (BABYLON) {
  17850. var DynamicTexture = (function (_super) {
  17851. __extends(DynamicTexture, _super);
  17852. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17854. _super.call(this, null, scene, !generateMipMaps);
  17855. this.name = name;
  17856. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17857. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17858. this._generateMipMaps = generateMipMaps;
  17859. if (options.getContext) {
  17860. this._canvas = options;
  17861. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17862. }
  17863. else {
  17864. this._canvas = document.createElement("canvas");
  17865. if (options.width) {
  17866. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17867. }
  17868. else {
  17869. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17870. }
  17871. }
  17872. var textureSize = this.getSize();
  17873. this._canvas.width = textureSize.width;
  17874. this._canvas.height = textureSize.height;
  17875. this._context = this._canvas.getContext("2d");
  17876. }
  17877. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17878. get: function () {
  17879. return true;
  17880. },
  17881. enumerable: true,
  17882. configurable: true
  17883. });
  17884. DynamicTexture.prototype.scale = function (ratio) {
  17885. var textureSize = this.getSize();
  17886. textureSize.width *= ratio;
  17887. textureSize.height *= ratio;
  17888. this._canvas.width = textureSize.width;
  17889. this._canvas.height = textureSize.height;
  17890. this.releaseInternalTexture();
  17891. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17892. };
  17893. DynamicTexture.prototype.getContext = function () {
  17894. return this._context;
  17895. };
  17896. DynamicTexture.prototype.clear = function () {
  17897. var size = this.getSize();
  17898. this._context.fillRect(0, 0, size.width, size.height);
  17899. };
  17900. DynamicTexture.prototype.update = function (invertY) {
  17901. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17902. };
  17903. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17904. if (update === void 0) { update = true; }
  17905. var size = this.getSize();
  17906. if (clearColor) {
  17907. this._context.fillStyle = clearColor;
  17908. this._context.fillRect(0, 0, size.width, size.height);
  17909. }
  17910. this._context.font = font;
  17911. if (x === null) {
  17912. var textSize = this._context.measureText(text);
  17913. x = (size.width - textSize.width) / 2;
  17914. }
  17915. this._context.fillStyle = color;
  17916. this._context.fillText(text, x, y);
  17917. if (update) {
  17918. this.update(invertY);
  17919. }
  17920. };
  17921. DynamicTexture.prototype.clone = function () {
  17922. var textureSize = this.getSize();
  17923. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17924. // Base texture
  17925. newTexture.hasAlpha = this.hasAlpha;
  17926. newTexture.level = this.level;
  17927. // Dynamic Texture
  17928. newTexture.wrapU = this.wrapU;
  17929. newTexture.wrapV = this.wrapV;
  17930. return newTexture;
  17931. };
  17932. return DynamicTexture;
  17933. })(BABYLON.Texture);
  17934. BABYLON.DynamicTexture = DynamicTexture;
  17935. })(BABYLON || (BABYLON = {}));
  17936. var BABYLON;
  17937. (function (BABYLON) {
  17938. var VideoTexture = (function (_super) {
  17939. __extends(VideoTexture, _super);
  17940. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17941. var _this = this;
  17942. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17943. if (invertY === void 0) { invertY = false; }
  17944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17945. _super.call(this, null, scene, !generateMipMaps, invertY);
  17946. this._autoLaunch = true;
  17947. this.name = name;
  17948. this.video = document.createElement("video");
  17949. this.video.autoplay = false;
  17950. this.video.loop = true;
  17951. this.video.addEventListener("canplaythrough", function () {
  17952. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17953. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17954. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17955. }
  17956. else {
  17957. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17958. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17959. generateMipMaps = false;
  17960. }
  17961. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17962. _this._texture.isReady = true;
  17963. });
  17964. urls.forEach(function (url) {
  17965. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17966. var source = document.createElement("source");
  17967. source.src = url;
  17968. _this.video.appendChild(source);
  17969. });
  17970. this._lastUpdate = BABYLON.Tools.Now;
  17971. }
  17972. VideoTexture.prototype.update = function () {
  17973. if (this._autoLaunch) {
  17974. this._autoLaunch = false;
  17975. this.video.play();
  17976. }
  17977. var now = BABYLON.Tools.Now;
  17978. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17979. return false;
  17980. }
  17981. this._lastUpdate = now;
  17982. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17983. return true;
  17984. };
  17985. return VideoTexture;
  17986. })(BABYLON.Texture);
  17987. BABYLON.VideoTexture = VideoTexture;
  17988. })(BABYLON || (BABYLON = {}));
  17989. var BABYLON;
  17990. (function (BABYLON) {
  17991. var CustomProceduralTexture = (function (_super) {
  17992. __extends(CustomProceduralTexture, _super);
  17993. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17994. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17995. this._animate = true;
  17996. this._time = 0;
  17997. this._texturePath = texturePath;
  17998. //Try to load json
  17999. this.loadJson(texturePath);
  18000. this.refreshRate = 1;
  18001. }
  18002. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18003. var _this = this;
  18004. var that = this;
  18005. function noConfigFile() {
  18006. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18007. try {
  18008. that.setFragment(that._texturePath);
  18009. }
  18010. catch (ex) {
  18011. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18012. }
  18013. }
  18014. var configFileUrl = jsonUrl + "/config.json";
  18015. var xhr = new XMLHttpRequest();
  18016. xhr.open("GET", configFileUrl, true);
  18017. xhr.addEventListener("load", function () {
  18018. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18019. try {
  18020. _this._config = JSON.parse(xhr.response);
  18021. _this.updateShaderUniforms();
  18022. _this.updateTextures();
  18023. _this.setFragment(_this._texturePath + "/custom");
  18024. _this._animate = _this._config.animate;
  18025. _this.refreshRate = _this._config.refreshrate;
  18026. }
  18027. catch (ex) {
  18028. noConfigFile();
  18029. }
  18030. }
  18031. else {
  18032. noConfigFile();
  18033. }
  18034. }, false);
  18035. xhr.addEventListener("error", function () {
  18036. noConfigFile();
  18037. }, false);
  18038. try {
  18039. xhr.send();
  18040. }
  18041. catch (ex) {
  18042. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18043. }
  18044. };
  18045. CustomProceduralTexture.prototype.isReady = function () {
  18046. if (!_super.prototype.isReady.call(this)) {
  18047. return false;
  18048. }
  18049. for (var name in this._textures) {
  18050. var texture = this._textures[name];
  18051. if (!texture.isReady()) {
  18052. return false;
  18053. }
  18054. }
  18055. return true;
  18056. };
  18057. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18058. if (this._animate) {
  18059. this._time += this.getScene().getAnimationRatio() * 0.03;
  18060. this.updateShaderUniforms();
  18061. }
  18062. _super.prototype.render.call(this, useCameraPostProcess);
  18063. };
  18064. CustomProceduralTexture.prototype.updateTextures = function () {
  18065. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18066. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18067. }
  18068. };
  18069. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18070. if (this._config) {
  18071. for (var j = 0; j < this._config.uniforms.length; j++) {
  18072. var uniform = this._config.uniforms[j];
  18073. switch (uniform.type) {
  18074. case "float":
  18075. this.setFloat(uniform.name, uniform.value);
  18076. break;
  18077. case "color3":
  18078. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18079. break;
  18080. case "color4":
  18081. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18082. break;
  18083. case "vector2":
  18084. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18085. break;
  18086. case "vector3":
  18087. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18088. break;
  18089. }
  18090. }
  18091. }
  18092. this.setFloat("time", this._time);
  18093. };
  18094. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18095. get: function () {
  18096. return this._animate;
  18097. },
  18098. set: function (value) {
  18099. this._animate = value;
  18100. },
  18101. enumerable: true,
  18102. configurable: true
  18103. });
  18104. return CustomProceduralTexture;
  18105. })(BABYLON.ProceduralTexture);
  18106. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18107. })(BABYLON || (BABYLON = {}));
  18108. var BABYLON;
  18109. (function (BABYLON) {
  18110. var WoodProceduralTexture = (function (_super) {
  18111. __extends(WoodProceduralTexture, _super);
  18112. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18113. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  18114. this._ampScale = 100.0;
  18115. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  18116. this.updateShaderUniforms();
  18117. this.refreshRate = 0;
  18118. }
  18119. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  18120. this.setFloat("ampScale", this._ampScale);
  18121. this.setColor3("woodColor", this._woodColor);
  18122. };
  18123. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  18124. get: function () {
  18125. return this._ampScale;
  18126. },
  18127. set: function (value) {
  18128. this._ampScale = value;
  18129. this.updateShaderUniforms();
  18130. },
  18131. enumerable: true,
  18132. configurable: true
  18133. });
  18134. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  18135. get: function () {
  18136. return this._woodColor;
  18137. },
  18138. set: function (value) {
  18139. this._woodColor = value;
  18140. this.updateShaderUniforms();
  18141. },
  18142. enumerable: true,
  18143. configurable: true
  18144. });
  18145. return WoodProceduralTexture;
  18146. })(BABYLON.ProceduralTexture);
  18147. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  18148. var FireProceduralTexture = (function (_super) {
  18149. __extends(FireProceduralTexture, _super);
  18150. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18151. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  18152. this._time = 0.0;
  18153. this._speed = new BABYLON.Vector2(0.5, 0.3);
  18154. this._autoGenerateTime = true;
  18155. this._alphaThreshold = 0.5;
  18156. this._fireColors = FireProceduralTexture.RedFireColors;
  18157. this.updateShaderUniforms();
  18158. this.refreshRate = 1;
  18159. }
  18160. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  18161. this.setFloat("time", this._time);
  18162. this.setVector2("speed", this._speed);
  18163. this.setColor3("c1", this._fireColors[0]);
  18164. this.setColor3("c2", this._fireColors[1]);
  18165. this.setColor3("c3", this._fireColors[2]);
  18166. this.setColor3("c4", this._fireColors[3]);
  18167. this.setColor3("c5", this._fireColors[4]);
  18168. this.setColor3("c6", this._fireColors[5]);
  18169. this.setFloat("alphaThreshold", this._alphaThreshold);
  18170. };
  18171. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18172. if (this._autoGenerateTime) {
  18173. this._time += this.getScene().getAnimationRatio() * 0.03;
  18174. this.updateShaderUniforms();
  18175. }
  18176. _super.prototype.render.call(this, useCameraPostProcess);
  18177. };
  18178. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  18179. get: function () {
  18180. return [
  18181. new BABYLON.Color3(0.5, 0.0, 1.0),
  18182. new BABYLON.Color3(0.9, 0.0, 1.0),
  18183. new BABYLON.Color3(0.2, 0.0, 1.0),
  18184. new BABYLON.Color3(1.0, 0.9, 1.0),
  18185. new BABYLON.Color3(0.1, 0.1, 1.0),
  18186. new BABYLON.Color3(0.9, 0.9, 1.0)
  18187. ];
  18188. },
  18189. enumerable: true,
  18190. configurable: true
  18191. });
  18192. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  18193. get: function () {
  18194. return [
  18195. new BABYLON.Color3(0.5, 1.0, 0.0),
  18196. new BABYLON.Color3(0.5, 1.0, 0.0),
  18197. new BABYLON.Color3(0.3, 0.4, 0.0),
  18198. new BABYLON.Color3(0.5, 1.0, 0.0),
  18199. new BABYLON.Color3(0.2, 0.0, 0.0),
  18200. new BABYLON.Color3(0.5, 1.0, 0.0)
  18201. ];
  18202. },
  18203. enumerable: true,
  18204. configurable: true
  18205. });
  18206. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  18207. get: function () {
  18208. return [
  18209. new BABYLON.Color3(0.5, 0.0, 0.1),
  18210. new BABYLON.Color3(0.9, 0.0, 0.0),
  18211. new BABYLON.Color3(0.2, 0.0, 0.0),
  18212. new BABYLON.Color3(1.0, 0.9, 0.0),
  18213. new BABYLON.Color3(0.1, 0.1, 0.1),
  18214. new BABYLON.Color3(0.9, 0.9, 0.9)
  18215. ];
  18216. },
  18217. enumerable: true,
  18218. configurable: true
  18219. });
  18220. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  18221. get: function () {
  18222. return [
  18223. new BABYLON.Color3(0.1, 0.0, 0.5),
  18224. new BABYLON.Color3(0.0, 0.0, 0.5),
  18225. new BABYLON.Color3(0.1, 0.0, 0.2),
  18226. new BABYLON.Color3(0.0, 0.0, 1.0),
  18227. new BABYLON.Color3(0.1, 0.2, 0.3),
  18228. new BABYLON.Color3(0.0, 0.2, 0.9)
  18229. ];
  18230. },
  18231. enumerable: true,
  18232. configurable: true
  18233. });
  18234. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  18235. get: function () {
  18236. return this._fireColors;
  18237. },
  18238. set: function (value) {
  18239. this._fireColors = value;
  18240. this.updateShaderUniforms();
  18241. },
  18242. enumerable: true,
  18243. configurable: true
  18244. });
  18245. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  18246. get: function () {
  18247. return this._time;
  18248. },
  18249. set: function (value) {
  18250. this._time = value;
  18251. this.updateShaderUniforms();
  18252. },
  18253. enumerable: true,
  18254. configurable: true
  18255. });
  18256. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  18257. get: function () {
  18258. return this._speed;
  18259. },
  18260. set: function (value) {
  18261. this._speed = value;
  18262. this.updateShaderUniforms();
  18263. },
  18264. enumerable: true,
  18265. configurable: true
  18266. });
  18267. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  18268. get: function () {
  18269. return this._alphaThreshold;
  18270. },
  18271. set: function (value) {
  18272. this._alphaThreshold = value;
  18273. this.updateShaderUniforms();
  18274. },
  18275. enumerable: true,
  18276. configurable: true
  18277. });
  18278. return FireProceduralTexture;
  18279. })(BABYLON.ProceduralTexture);
  18280. BABYLON.FireProceduralTexture = FireProceduralTexture;
  18281. var CloudProceduralTexture = (function (_super) {
  18282. __extends(CloudProceduralTexture, _super);
  18283. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18284. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  18285. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  18286. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  18287. this.updateShaderUniforms();
  18288. this.refreshRate = 0;
  18289. }
  18290. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  18291. this.setColor4("skyColor", this._skyColor);
  18292. this.setColor4("cloudColor", this._cloudColor);
  18293. };
  18294. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  18295. get: function () {
  18296. return this._skyColor;
  18297. },
  18298. set: function (value) {
  18299. this._skyColor = value;
  18300. this.updateShaderUniforms();
  18301. },
  18302. enumerable: true,
  18303. configurable: true
  18304. });
  18305. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  18306. get: function () {
  18307. return this._cloudColor;
  18308. },
  18309. set: function (value) {
  18310. this._cloudColor = value;
  18311. this.updateShaderUniforms();
  18312. },
  18313. enumerable: true,
  18314. configurable: true
  18315. });
  18316. return CloudProceduralTexture;
  18317. })(BABYLON.ProceduralTexture);
  18318. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  18319. var GrassProceduralTexture = (function (_super) {
  18320. __extends(GrassProceduralTexture, _super);
  18321. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18322. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  18323. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  18324. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  18325. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  18326. this._groundColor = new BABYLON.Color3(1, 1, 1);
  18327. this._grassColors = [
  18328. new BABYLON.Color3(0.29, 0.38, 0.02),
  18329. new BABYLON.Color3(0.36, 0.49, 0.09),
  18330. new BABYLON.Color3(0.51, 0.6, 0.28)
  18331. ];
  18332. this.updateShaderUniforms();
  18333. this.refreshRate = 0;
  18334. }
  18335. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  18336. this.setColor3("herb1Color", this._grassColors[0]);
  18337. this.setColor3("herb2Color", this._grassColors[1]);
  18338. this.setColor3("herb3Color", this._grassColors[2]);
  18339. this.setColor3("groundColor", this._groundColor);
  18340. };
  18341. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  18342. get: function () {
  18343. return this._grassColors;
  18344. },
  18345. set: function (value) {
  18346. this._grassColors = value;
  18347. this.updateShaderUniforms();
  18348. },
  18349. enumerable: true,
  18350. configurable: true
  18351. });
  18352. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  18353. get: function () {
  18354. return this._groundColor;
  18355. },
  18356. set: function (value) {
  18357. this.groundColor = value;
  18358. this.updateShaderUniforms();
  18359. },
  18360. enumerable: true,
  18361. configurable: true
  18362. });
  18363. return GrassProceduralTexture;
  18364. })(BABYLON.ProceduralTexture);
  18365. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  18366. var RoadProceduralTexture = (function (_super) {
  18367. __extends(RoadProceduralTexture, _super);
  18368. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18369. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  18370. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  18371. this.updateShaderUniforms();
  18372. this.refreshRate = 0;
  18373. }
  18374. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  18375. this.setColor3("roadColor", this._roadColor);
  18376. };
  18377. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  18378. get: function () {
  18379. return this._roadColor;
  18380. },
  18381. set: function (value) {
  18382. this._roadColor = value;
  18383. this.updateShaderUniforms();
  18384. },
  18385. enumerable: true,
  18386. configurable: true
  18387. });
  18388. return RoadProceduralTexture;
  18389. })(BABYLON.ProceduralTexture);
  18390. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  18391. var BrickProceduralTexture = (function (_super) {
  18392. __extends(BrickProceduralTexture, _super);
  18393. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18394. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  18395. this._numberOfBricksHeight = 15;
  18396. this._numberOfBricksWidth = 5;
  18397. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  18398. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  18399. this.updateShaderUniforms();
  18400. this.refreshRate = 0;
  18401. }
  18402. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  18403. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  18404. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  18405. this.setColor3("brickColor", this._brickColor);
  18406. this.setColor3("jointColor", this._jointColor);
  18407. };
  18408. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  18409. get: function () {
  18410. return this._numberOfBricksHeight;
  18411. },
  18412. set: function (value) {
  18413. this._numberOfBricksHeight = value;
  18414. this.updateShaderUniforms();
  18415. },
  18416. enumerable: true,
  18417. configurable: true
  18418. });
  18419. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  18420. get: function () {
  18421. return this._numberOfBricksWidth;
  18422. },
  18423. set: function (value) {
  18424. this._numberOfBricksWidth = value;
  18425. this.updateShaderUniforms();
  18426. },
  18427. enumerable: true,
  18428. configurable: true
  18429. });
  18430. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  18431. get: function () {
  18432. return this._jointColor;
  18433. },
  18434. set: function (value) {
  18435. this._jointColor = value;
  18436. this.updateShaderUniforms();
  18437. },
  18438. enumerable: true,
  18439. configurable: true
  18440. });
  18441. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  18442. get: function () {
  18443. return this._brickColor;
  18444. },
  18445. set: function (value) {
  18446. this._brickColor = value;
  18447. this.updateShaderUniforms();
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. return BrickProceduralTexture;
  18453. })(BABYLON.ProceduralTexture);
  18454. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  18455. var MarbleProceduralTexture = (function (_super) {
  18456. __extends(MarbleProceduralTexture, _super);
  18457. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18458. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  18459. this._numberOfTilesHeight = 3;
  18460. this._numberOfTilesWidth = 3;
  18461. this._amplitude = 9.0;
  18462. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  18463. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  18464. this.updateShaderUniforms();
  18465. this.refreshRate = 0;
  18466. }
  18467. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  18468. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  18469. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  18470. this.setFloat("amplitude", this._amplitude);
  18471. this.setColor3("marbleColor", this._marbleColor);
  18472. this.setColor3("jointColor", this._jointColor);
  18473. };
  18474. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  18475. get: function () {
  18476. return this._numberOfTilesHeight;
  18477. },
  18478. set: function (value) {
  18479. this._numberOfTilesHeight = value;
  18480. this.updateShaderUniforms();
  18481. },
  18482. enumerable: true,
  18483. configurable: true
  18484. });
  18485. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  18486. get: function () {
  18487. return this._numberOfTilesWidth;
  18488. },
  18489. set: function (value) {
  18490. this._numberOfTilesWidth = value;
  18491. this.updateShaderUniforms();
  18492. },
  18493. enumerable: true,
  18494. configurable: true
  18495. });
  18496. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  18497. get: function () {
  18498. return this._jointColor;
  18499. },
  18500. set: function (value) {
  18501. this._jointColor = value;
  18502. this.updateShaderUniforms();
  18503. },
  18504. enumerable: true,
  18505. configurable: true
  18506. });
  18507. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  18508. get: function () {
  18509. return this._marbleColor;
  18510. },
  18511. set: function (value) {
  18512. this._marbleColor = value;
  18513. this.updateShaderUniforms();
  18514. },
  18515. enumerable: true,
  18516. configurable: true
  18517. });
  18518. return MarbleProceduralTexture;
  18519. })(BABYLON.ProceduralTexture);
  18520. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  18521. })(BABYLON || (BABYLON = {}));
  18522. var BABYLON;
  18523. (function (BABYLON) {
  18524. var EffectFallbacks = (function () {
  18525. function EffectFallbacks() {
  18526. this._defines = {};
  18527. this._currentRank = 32;
  18528. this._maxRank = -1;
  18529. }
  18530. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18531. if (!this._defines[rank]) {
  18532. if (rank < this._currentRank) {
  18533. this._currentRank = rank;
  18534. }
  18535. if (rank > this._maxRank) {
  18536. this._maxRank = rank;
  18537. }
  18538. this._defines[rank] = new Array();
  18539. }
  18540. this._defines[rank].push(define);
  18541. };
  18542. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18543. get: function () {
  18544. return this._currentRank <= this._maxRank;
  18545. },
  18546. enumerable: true,
  18547. configurable: true
  18548. });
  18549. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18550. var currentFallbacks = this._defines[this._currentRank];
  18551. for (var index = 0; index < currentFallbacks.length; index++) {
  18552. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18553. }
  18554. this._currentRank++;
  18555. return currentDefines;
  18556. };
  18557. return EffectFallbacks;
  18558. })();
  18559. BABYLON.EffectFallbacks = EffectFallbacks;
  18560. var Effect = (function () {
  18561. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18562. var _this = this;
  18563. this._isReady = false;
  18564. this._compilationError = "";
  18565. this._valueCache = [];
  18566. this._engine = engine;
  18567. this.name = baseName;
  18568. this.defines = defines;
  18569. this._uniformsNames = uniformsNames.concat(samplers);
  18570. this._samplers = samplers;
  18571. this._attributesNames = attributesNames;
  18572. this.onError = onError;
  18573. this.onCompiled = onCompiled;
  18574. var vertexSource;
  18575. var fragmentSource;
  18576. if (baseName.vertexElement) {
  18577. vertexSource = document.getElementById(baseName.vertexElement);
  18578. if (!vertexSource) {
  18579. vertexSource = baseName.vertexElement;
  18580. }
  18581. }
  18582. else {
  18583. vertexSource = baseName.vertex || baseName;
  18584. }
  18585. if (baseName.fragmentElement) {
  18586. fragmentSource = document.getElementById(baseName.fragmentElement);
  18587. if (!fragmentSource) {
  18588. fragmentSource = baseName.fragmentElement;
  18589. }
  18590. }
  18591. else {
  18592. fragmentSource = baseName.fragment || baseName;
  18593. }
  18594. this._loadVertexShader(vertexSource, function (vertexCode) {
  18595. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18596. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18597. });
  18598. });
  18599. }
  18600. // Properties
  18601. Effect.prototype.isReady = function () {
  18602. return this._isReady;
  18603. };
  18604. Effect.prototype.getProgram = function () {
  18605. return this._program;
  18606. };
  18607. Effect.prototype.getAttributesNames = function () {
  18608. return this._attributesNames;
  18609. };
  18610. Effect.prototype.getAttributeLocation = function (index) {
  18611. return this._attributes[index];
  18612. };
  18613. Effect.prototype.getAttributeLocationByName = function (name) {
  18614. var index = this._attributesNames.indexOf(name);
  18615. return this._attributes[index];
  18616. };
  18617. Effect.prototype.getAttributesCount = function () {
  18618. return this._attributes.length;
  18619. };
  18620. Effect.prototype.getUniformIndex = function (uniformName) {
  18621. return this._uniformsNames.indexOf(uniformName);
  18622. };
  18623. Effect.prototype.getUniform = function (uniformName) {
  18624. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18625. };
  18626. Effect.prototype.getSamplers = function () {
  18627. return this._samplers;
  18628. };
  18629. Effect.prototype.getCompilationError = function () {
  18630. return this._compilationError;
  18631. };
  18632. // Methods
  18633. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18634. // DOM element ?
  18635. if (vertex instanceof HTMLElement) {
  18636. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18637. callback(vertexCode);
  18638. return;
  18639. }
  18640. // Is in local store ?
  18641. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18642. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18643. return;
  18644. }
  18645. var vertexShaderUrl;
  18646. if (vertex[0] === "." || vertex[0] === "/") {
  18647. vertexShaderUrl = vertex;
  18648. }
  18649. else {
  18650. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18651. }
  18652. // Vertex shader
  18653. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18654. };
  18655. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18656. // DOM element ?
  18657. if (fragment instanceof HTMLElement) {
  18658. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18659. callback(fragmentCode);
  18660. return;
  18661. }
  18662. // Is in local store ?
  18663. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18664. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18665. return;
  18666. }
  18667. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18668. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18669. return;
  18670. }
  18671. var fragmentShaderUrl;
  18672. if (fragment[0] === "." || fragment[0] === "/") {
  18673. fragmentShaderUrl = fragment;
  18674. }
  18675. else {
  18676. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18677. }
  18678. // Fragment shader
  18679. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18680. };
  18681. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18682. try {
  18683. var engine = this._engine;
  18684. if (!engine.getCaps().highPrecisionShaderSupported) {
  18685. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18686. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18687. }
  18688. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18689. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18690. this._attributes = engine.getAttributes(this._program, attributesNames);
  18691. for (var index = 0; index < this._samplers.length; index++) {
  18692. var sampler = this.getUniform(this._samplers[index]);
  18693. if (sampler == null) {
  18694. this._samplers.splice(index, 1);
  18695. index--;
  18696. }
  18697. }
  18698. engine.bindSamplers(this);
  18699. this._isReady = true;
  18700. if (this.onCompiled) {
  18701. this.onCompiled(this);
  18702. }
  18703. }
  18704. catch (e) {
  18705. // Is it a problem with precision?
  18706. if (e.message.indexOf("highp") !== -1) {
  18707. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18708. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18709. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18710. return;
  18711. }
  18712. // Let's go through fallbacks then
  18713. if (fallbacks && fallbacks.isMoreFallbacks) {
  18714. defines = fallbacks.reduce(defines);
  18715. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18716. }
  18717. else {
  18718. BABYLON.Tools.Error("Unable to compile effect: ");
  18719. if (this.name.vertexElement) {
  18720. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18721. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18722. }
  18723. else if (this.name.vertex) {
  18724. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18725. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18726. }
  18727. else {
  18728. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18729. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18730. }
  18731. BABYLON.Tools.Error("Defines: " + defines);
  18732. BABYLON.Tools.Error("Error: " + e.message);
  18733. this._compilationError = e.message;
  18734. if (this.onError) {
  18735. this.onError(this, this._compilationError);
  18736. }
  18737. }
  18738. }
  18739. };
  18740. Effect.prototype._bindTexture = function (channel, texture) {
  18741. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18742. };
  18743. Effect.prototype.setTexture = function (channel, texture) {
  18744. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18745. };
  18746. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18747. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18748. };
  18749. //public _cacheMatrix(uniformName, matrix) {
  18750. // if (!this._valueCache[uniformName]) {
  18751. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18752. // }
  18753. // for (var index = 0; index < 16; index++) {
  18754. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18755. // }
  18756. //};
  18757. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18758. if (!this._valueCache[uniformName]) {
  18759. this._valueCache[uniformName] = [x, y];
  18760. return;
  18761. }
  18762. this._valueCache[uniformName][0] = x;
  18763. this._valueCache[uniformName][1] = y;
  18764. };
  18765. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18766. if (!this._valueCache[uniformName]) {
  18767. this._valueCache[uniformName] = [x, y, z];
  18768. return;
  18769. }
  18770. this._valueCache[uniformName][0] = x;
  18771. this._valueCache[uniformName][1] = y;
  18772. this._valueCache[uniformName][2] = z;
  18773. };
  18774. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18775. if (!this._valueCache[uniformName]) {
  18776. this._valueCache[uniformName] = [x, y, z, w];
  18777. return;
  18778. }
  18779. this._valueCache[uniformName][0] = x;
  18780. this._valueCache[uniformName][1] = y;
  18781. this._valueCache[uniformName][2] = z;
  18782. this._valueCache[uniformName][3] = w;
  18783. };
  18784. Effect.prototype.setArray = function (uniformName, array) {
  18785. this._engine.setArray(this.getUniform(uniformName), array);
  18786. return this;
  18787. };
  18788. Effect.prototype.setArray2 = function (uniformName, array) {
  18789. this._engine.setArray2(this.getUniform(uniformName), array);
  18790. return this;
  18791. };
  18792. Effect.prototype.setArray3 = function (uniformName, array) {
  18793. this._engine.setArray3(this.getUniform(uniformName), array);
  18794. return this;
  18795. };
  18796. Effect.prototype.setArray4 = function (uniformName, array) {
  18797. this._engine.setArray4(this.getUniform(uniformName), array);
  18798. return this;
  18799. };
  18800. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18801. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18802. return this;
  18803. };
  18804. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18805. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18806. // return;
  18807. //this._cacheMatrix(uniformName, matrix);
  18808. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18809. return this;
  18810. };
  18811. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18812. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18813. return this;
  18814. };
  18815. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18816. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18817. return this;
  18818. };
  18819. Effect.prototype.setFloat = function (uniformName, value) {
  18820. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18821. return this;
  18822. this._valueCache[uniformName] = value;
  18823. this._engine.setFloat(this.getUniform(uniformName), value);
  18824. return this;
  18825. };
  18826. Effect.prototype.setBool = function (uniformName, bool) {
  18827. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18828. return this;
  18829. this._valueCache[uniformName] = bool;
  18830. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18831. return this;
  18832. };
  18833. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18834. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18835. return this;
  18836. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18837. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18838. return this;
  18839. };
  18840. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18841. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18842. return this;
  18843. this._cacheFloat2(uniformName, x, y);
  18844. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18845. return this;
  18846. };
  18847. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18848. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18849. return this;
  18850. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18851. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18852. return this;
  18853. };
  18854. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18855. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18856. return this;
  18857. this._cacheFloat3(uniformName, x, y, z);
  18858. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18859. return this;
  18860. };
  18861. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18862. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
  18863. return this;
  18864. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18865. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18866. return this;
  18867. };
  18868. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18869. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18870. return this;
  18871. this._cacheFloat4(uniformName, x, y, z, w);
  18872. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18873. return this;
  18874. };
  18875. Effect.prototype.setColor3 = function (uniformName, color3) {
  18876. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18877. return this;
  18878. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18879. this._engine.setColor3(this.getUniform(uniformName), color3);
  18880. return this;
  18881. };
  18882. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18883. 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)
  18884. return this;
  18885. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18886. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18887. return this;
  18888. };
  18889. // Statics
  18890. Effect.ShadersStore = {};
  18891. return Effect;
  18892. })();
  18893. BABYLON.Effect = Effect;
  18894. })(BABYLON || (BABYLON = {}));
  18895. var BABYLON;
  18896. (function (BABYLON) {
  18897. var Material = (function () {
  18898. function Material(name, scene, doNotAdd) {
  18899. this.name = name;
  18900. this.checkReadyOnEveryCall = true;
  18901. this.checkReadyOnlyOnce = false;
  18902. this.state = "";
  18903. this.alpha = 1.0;
  18904. this.backFaceCulling = true;
  18905. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18906. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18907. this.disableDepthWrite = false;
  18908. this.fogEnabled = true;
  18909. this._wasPreviouslyReady = false;
  18910. this._fillMode = Material.TriangleFillMode;
  18911. this.pointSize = 1.0;
  18912. this.zOffset = 0;
  18913. this.id = name;
  18914. this._scene = scene;
  18915. if (!doNotAdd) {
  18916. scene.materials.push(this);
  18917. }
  18918. }
  18919. Object.defineProperty(Material, "TriangleFillMode", {
  18920. get: function () {
  18921. return Material._TriangleFillMode;
  18922. },
  18923. enumerable: true,
  18924. configurable: true
  18925. });
  18926. Object.defineProperty(Material, "WireFrameFillMode", {
  18927. get: function () {
  18928. return Material._WireFrameFillMode;
  18929. },
  18930. enumerable: true,
  18931. configurable: true
  18932. });
  18933. Object.defineProperty(Material, "PointFillMode", {
  18934. get: function () {
  18935. return Material._PointFillMode;
  18936. },
  18937. enumerable: true,
  18938. configurable: true
  18939. });
  18940. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18941. get: function () {
  18942. return Material._ClockWiseSideOrientation;
  18943. },
  18944. enumerable: true,
  18945. configurable: true
  18946. });
  18947. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18948. get: function () {
  18949. return Material._CounterClockWiseSideOrientation;
  18950. },
  18951. enumerable: true,
  18952. configurable: true
  18953. });
  18954. Object.defineProperty(Material.prototype, "wireframe", {
  18955. get: function () {
  18956. return this._fillMode === Material.WireFrameFillMode;
  18957. },
  18958. set: function (value) {
  18959. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18960. },
  18961. enumerable: true,
  18962. configurable: true
  18963. });
  18964. Object.defineProperty(Material.prototype, "pointsCloud", {
  18965. get: function () {
  18966. return this._fillMode === Material.PointFillMode;
  18967. },
  18968. set: function (value) {
  18969. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18970. },
  18971. enumerable: true,
  18972. configurable: true
  18973. });
  18974. Object.defineProperty(Material.prototype, "fillMode", {
  18975. get: function () {
  18976. return this._fillMode;
  18977. },
  18978. set: function (value) {
  18979. this._fillMode = value;
  18980. },
  18981. enumerable: true,
  18982. configurable: true
  18983. });
  18984. Material.prototype.isReady = function (mesh, useInstances) {
  18985. return true;
  18986. };
  18987. Material.prototype.getEffect = function () {
  18988. return this._effect;
  18989. };
  18990. Material.prototype.getScene = function () {
  18991. return this._scene;
  18992. };
  18993. Material.prototype.needAlphaBlending = function () {
  18994. return (this.alpha < 1.0);
  18995. };
  18996. Material.prototype.needAlphaTesting = function () {
  18997. return false;
  18998. };
  18999. Material.prototype.getAlphaTestTexture = function () {
  19000. return null;
  19001. };
  19002. Material.prototype.trackCreation = function (onCompiled, onError) {
  19003. };
  19004. Material.prototype._preBind = function () {
  19005. var engine = this._scene.getEngine();
  19006. engine.enableEffect(this._effect);
  19007. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19008. };
  19009. Material.prototype.bind = function (world, mesh) {
  19010. this._scene._cachedMaterial = this;
  19011. if (this.onBind) {
  19012. this.onBind(this, mesh);
  19013. }
  19014. if (this.disableDepthWrite) {
  19015. var engine = this._scene.getEngine();
  19016. this._cachedDepthWriteState = engine.getDepthWrite();
  19017. engine.setDepthWrite(false);
  19018. }
  19019. };
  19020. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19021. };
  19022. Material.prototype.unbind = function () {
  19023. if (this.disableDepthWrite) {
  19024. var engine = this._scene.getEngine();
  19025. engine.setDepthWrite(this._cachedDepthWriteState);
  19026. }
  19027. };
  19028. Material.prototype.clone = function (name) {
  19029. return null;
  19030. };
  19031. Material.prototype.getBindedMeshes = function () {
  19032. var result = new Array();
  19033. for (var index = 0; index < this._scene.meshes.length; index++) {
  19034. var mesh = this._scene.meshes[index];
  19035. if (mesh.material === this) {
  19036. result.push(mesh);
  19037. }
  19038. }
  19039. return result;
  19040. };
  19041. Material.prototype.dispose = function (forceDisposeEffect) {
  19042. // Remove from scene
  19043. var index = this._scene.materials.indexOf(this);
  19044. if (index >= 0) {
  19045. this._scene.materials.splice(index, 1);
  19046. }
  19047. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19048. if (forceDisposeEffect && this._effect) {
  19049. this._scene.getEngine()._releaseEffect(this._effect);
  19050. this._effect = null;
  19051. }
  19052. // Remove from meshes
  19053. for (index = 0; index < this._scene.meshes.length; index++) {
  19054. var mesh = this._scene.meshes[index];
  19055. if (mesh.material === this) {
  19056. mesh.material = null;
  19057. }
  19058. }
  19059. // Callback
  19060. if (this.onDispose) {
  19061. this.onDispose();
  19062. }
  19063. };
  19064. Material.prototype.copyTo = function (other) {
  19065. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  19066. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19067. other.alpha = this.alpha;
  19068. other.fillMode = this.fillMode;
  19069. other.backFaceCulling = this.backFaceCulling;
  19070. other.wireframe = this.wireframe;
  19071. other.fogEnabled = this.fogEnabled;
  19072. other.wireframe = this.wireframe;
  19073. other.zOffset = this.zOffset;
  19074. other.alphaMode = this.alphaMode;
  19075. other.sideOrientation = this.sideOrientation;
  19076. other.disableDepthWrite = this.disableDepthWrite;
  19077. other.pointSize = this.pointSize;
  19078. other.pointsCloud = this.pointsCloud;
  19079. };
  19080. Material._TriangleFillMode = 0;
  19081. Material._WireFrameFillMode = 1;
  19082. Material._PointFillMode = 2;
  19083. Material._ClockWiseSideOrientation = 0;
  19084. Material._CounterClockWiseSideOrientation = 1;
  19085. return Material;
  19086. })();
  19087. BABYLON.Material = Material;
  19088. })(BABYLON || (BABYLON = {}));
  19089. var BABYLON;
  19090. (function (BABYLON) {
  19091. var maxSimultaneousLights = 4;
  19092. var FresnelParameters = (function () {
  19093. function FresnelParameters() {
  19094. this.isEnabled = true;
  19095. this.leftColor = BABYLON.Color3.White();
  19096. this.rightColor = BABYLON.Color3.Black();
  19097. this.bias = 0;
  19098. this.power = 1;
  19099. }
  19100. FresnelParameters.prototype.clone = function () {
  19101. var newFresnelParameters = new FresnelParameters();
  19102. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19103. return new FresnelParameters;
  19104. };
  19105. return FresnelParameters;
  19106. })();
  19107. BABYLON.FresnelParameters = FresnelParameters;
  19108. var StandardMaterialDefines = (function () {
  19109. function StandardMaterialDefines() {
  19110. this.DIFFUSE = false;
  19111. this.AMBIENT = false;
  19112. this.OPACITY = false;
  19113. this.OPACITYRGB = false;
  19114. this.REFLECTION = false;
  19115. this.EMISSIVE = false;
  19116. this.SPECULAR = false;
  19117. this.BUMP = false;
  19118. this.SPECULAROVERALPHA = false;
  19119. this.CLIPPLANE = false;
  19120. this.ALPHATEST = false;
  19121. this.ALPHAFROMDIFFUSE = false;
  19122. this.POINTSIZE = false;
  19123. this.FOG = false;
  19124. this.LIGHT0 = false;
  19125. this.LIGHT1 = false;
  19126. this.LIGHT2 = false;
  19127. this.LIGHT3 = false;
  19128. this.SPOTLIGHT0 = false;
  19129. this.SPOTLIGHT1 = false;
  19130. this.SPOTLIGHT2 = false;
  19131. this.SPOTLIGHT3 = false;
  19132. this.HEMILIGHT0 = false;
  19133. this.HEMILIGHT1 = false;
  19134. this.HEMILIGHT2 = false;
  19135. this.HEMILIGHT3 = false;
  19136. this.POINTDIRLIGHT0 = false;
  19137. this.POINTDIRLIGHT1 = false;
  19138. this.POINTDIRLIGHT2 = false;
  19139. this.POINTDIRLIGHT3 = false;
  19140. this.SPECULARTERM = false;
  19141. this.SHADOW0 = false;
  19142. this.SHADOW1 = false;
  19143. this.SHADOW2 = false;
  19144. this.SHADOW3 = false;
  19145. this.SHADOWS = false;
  19146. this.SHADOWVSM0 = false;
  19147. this.SHADOWVSM1 = false;
  19148. this.SHADOWVSM2 = false;
  19149. this.SHADOWVSM3 = false;
  19150. this.SHADOWPCF0 = false;
  19151. this.SHADOWPCF1 = false;
  19152. this.SHADOWPCF2 = false;
  19153. this.SHADOWPCF3 = false;
  19154. this.DIFFUSEFRESNEL = false;
  19155. this.OPACITYFRESNEL = false;
  19156. this.REFLECTIONFRESNEL = false;
  19157. this.EMISSIVEFRESNEL = false;
  19158. this.FRESNEL = false;
  19159. this.NORMAL = false;
  19160. this.UV1 = false;
  19161. this.UV2 = false;
  19162. this.VERTEXCOLOR = false;
  19163. this.VERTEXALPHA = false;
  19164. this.BONES = false;
  19165. this.BONES4 = false;
  19166. this.BonesPerMesh = 0;
  19167. this.INSTANCES = false;
  19168. this.GLOSSINESS = false;
  19169. this.ROUGHNESS = false;
  19170. this.EMISSIVEASILLUMINATION = false;
  19171. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19172. this.LIGHTMAP = false;
  19173. this.REFLECTIONMAP_3D = false;
  19174. this.REFLECTIONMAP_SPHERICAL = false;
  19175. this.REFLECTIONMAP_PLANAR = false;
  19176. this.REFLECTIONMAP_CUBIC = false;
  19177. this.REFLECTIONMAP_PROJECTION = false;
  19178. this.REFLECTIONMAP_SKYBOX = false;
  19179. this.REFLECTIONMAP_EXPLICIT = false;
  19180. this.INVERTCUBICMAP = false;
  19181. this._keys = Object.keys(this);
  19182. }
  19183. StandardMaterialDefines.prototype.isEqual = function (other) {
  19184. for (var index = 0; index < this._keys.length; index++) {
  19185. var prop = this._keys[index];
  19186. if (this[prop] !== other[prop]) {
  19187. return false;
  19188. }
  19189. }
  19190. return true;
  19191. };
  19192. StandardMaterialDefines.prototype.cloneTo = function (other) {
  19193. for (var index = 0; index < this._keys.length; index++) {
  19194. var prop = this._keys[index];
  19195. other[prop] = this[prop];
  19196. }
  19197. };
  19198. StandardMaterialDefines.prototype.reset = function () {
  19199. for (var index = 0; index < this._keys.length; index++) {
  19200. var prop = this._keys[index];
  19201. if (prop === "BonesPerMesh") {
  19202. this[prop] = 0;
  19203. continue;
  19204. }
  19205. this[prop] = false;
  19206. }
  19207. };
  19208. StandardMaterialDefines.prototype.toString = function () {
  19209. var result = "";
  19210. for (var index = 0; index < this._keys.length; index++) {
  19211. var prop = this._keys[index];
  19212. if (prop === "BonesPerMesh" && this[prop] > 0) {
  19213. result += "#define BonesPerMesh " + this[prop] + "\n";
  19214. continue;
  19215. }
  19216. if (this[prop]) {
  19217. result += "#define " + prop + "\n";
  19218. }
  19219. }
  19220. return result;
  19221. };
  19222. return StandardMaterialDefines;
  19223. })();
  19224. var StandardMaterial = (function (_super) {
  19225. __extends(StandardMaterial, _super);
  19226. function StandardMaterial(name, scene) {
  19227. var _this = this;
  19228. _super.call(this, name, scene);
  19229. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19230. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19231. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19232. this.specularPower = 64;
  19233. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19234. this.useAlphaFromDiffuseTexture = false;
  19235. this.useEmissiveAsIllumination = false;
  19236. this.useReflectionFresnelFromSpecular = false;
  19237. this.useSpecularOverAlpha = true;
  19238. this.disableLighting = false;
  19239. this.roughness = 0;
  19240. this.lightmapThreshold = 0;
  19241. this.useGlossinessFromSpecularMapAlpha = false;
  19242. this._renderTargets = new BABYLON.SmartArray(16);
  19243. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19244. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19245. this._scaledDiffuse = new BABYLON.Color3();
  19246. this._scaledSpecular = new BABYLON.Color3();
  19247. this._defines = new StandardMaterialDefines();
  19248. this._cachedDefines = new StandardMaterialDefines();
  19249. this._cachedDefines.BonesPerMesh = -1;
  19250. this.getRenderTargetTextures = function () {
  19251. _this._renderTargets.reset();
  19252. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19253. _this._renderTargets.push(_this.reflectionTexture);
  19254. }
  19255. return _this._renderTargets;
  19256. };
  19257. }
  19258. StandardMaterial.prototype.needAlphaBlending = function () {
  19259. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19260. };
  19261. StandardMaterial.prototype.needAlphaTesting = function () {
  19262. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19263. };
  19264. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19265. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19266. };
  19267. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19268. return this.diffuseTexture;
  19269. };
  19270. // Methods
  19271. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19272. if (this.checkReadyOnlyOnce) {
  19273. if (this._wasPreviouslyReady) {
  19274. return true;
  19275. }
  19276. }
  19277. var scene = this.getScene();
  19278. if (!this.checkReadyOnEveryCall) {
  19279. if (this._renderId === scene.getRenderId()) {
  19280. return true;
  19281. }
  19282. }
  19283. var engine = scene.getEngine();
  19284. var needNormals = false;
  19285. var needUVs = false;
  19286. this._defines.reset();
  19287. // Textures
  19288. if (scene.texturesEnabled) {
  19289. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19290. if (!this.diffuseTexture.isReady()) {
  19291. return false;
  19292. }
  19293. else {
  19294. needUVs = true;
  19295. this._defines.DIFFUSE = true;
  19296. }
  19297. }
  19298. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19299. if (!this.ambientTexture.isReady()) {
  19300. return false;
  19301. }
  19302. else {
  19303. needUVs = true;
  19304. this._defines.AMBIENT = true;
  19305. }
  19306. }
  19307. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19308. if (!this.opacityTexture.isReady()) {
  19309. return false;
  19310. }
  19311. else {
  19312. needUVs = true;
  19313. this._defines.OPACITY = true;
  19314. if (this.opacityTexture.getAlphaFromRGB) {
  19315. this._defines.OPACITYRGB = true;
  19316. }
  19317. }
  19318. }
  19319. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19320. if (!this.reflectionTexture.isReady()) {
  19321. return false;
  19322. }
  19323. else {
  19324. needNormals = true;
  19325. needUVs = true;
  19326. this._defines.REFLECTION = true;
  19327. if (this.roughness > 0) {
  19328. this._defines.ROUGHNESS = true;
  19329. }
  19330. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19331. this._defines.INVERTCUBICMAP = true;
  19332. }
  19333. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19334. switch (this.reflectionTexture.coordinatesMode) {
  19335. case BABYLON.Texture.CUBIC_MODE:
  19336. case BABYLON.Texture.INVCUBIC_MODE:
  19337. this._defines.REFLECTIONMAP_CUBIC = true;
  19338. break;
  19339. case BABYLON.Texture.EXPLICIT_MODE:
  19340. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19341. break;
  19342. case BABYLON.Texture.PLANAR_MODE:
  19343. this._defines.REFLECTIONMAP_PLANAR = true;
  19344. break;
  19345. case BABYLON.Texture.PROJECTION_MODE:
  19346. this._defines.REFLECTIONMAP_PROJECTION = true;
  19347. break;
  19348. case BABYLON.Texture.SKYBOX_MODE:
  19349. this._defines.REFLECTIONMAP_SKYBOX = true;
  19350. break;
  19351. case BABYLON.Texture.SPHERICAL_MODE:
  19352. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19353. break;
  19354. }
  19355. }
  19356. }
  19357. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19358. if (!this.emissiveTexture.isReady()) {
  19359. return false;
  19360. }
  19361. else {
  19362. needUVs = true;
  19363. this._defines.EMISSIVE = true;
  19364. }
  19365. }
  19366. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19367. if (!this.lightmapTexture.isReady()) {
  19368. return false;
  19369. }
  19370. else {
  19371. needUVs = true;
  19372. this._defines.LIGHTMAP = true;
  19373. }
  19374. }
  19375. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19376. if (!this.specularTexture.isReady()) {
  19377. return false;
  19378. }
  19379. else {
  19380. needUVs = true;
  19381. this._defines.SPECULAR = true;
  19382. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19383. }
  19384. }
  19385. }
  19386. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19387. if (!this.bumpTexture.isReady()) {
  19388. return false;
  19389. }
  19390. else {
  19391. needUVs = true;
  19392. this._defines.BUMP = true;
  19393. }
  19394. }
  19395. // Effect
  19396. if (scene.clipPlane) {
  19397. this._defines.CLIPPLANE = true;
  19398. }
  19399. if (engine.getAlphaTesting()) {
  19400. this._defines.ALPHATEST = true;
  19401. }
  19402. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19403. this._defines.ALPHAFROMDIFFUSE = true;
  19404. }
  19405. if (this.useEmissiveAsIllumination) {
  19406. this._defines.EMISSIVEASILLUMINATION = true;
  19407. }
  19408. if (this.useReflectionFresnelFromSpecular) {
  19409. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19410. }
  19411. // Point size
  19412. if (this.pointsCloud || scene.forcePointsCloud) {
  19413. this._defines.POINTSIZE = true;
  19414. }
  19415. // Fog
  19416. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19417. this._defines.FOG = true;
  19418. }
  19419. var lightIndex = 0;
  19420. if (scene.lightsEnabled && !this.disableLighting) {
  19421. for (var index = 0; index < scene.lights.length; index++) {
  19422. var light = scene.lights[index];
  19423. if (!light.isEnabled()) {
  19424. continue;
  19425. }
  19426. // Excluded check
  19427. if (light._excludedMeshesIds.length > 0) {
  19428. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19429. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19430. if (excludedMesh) {
  19431. light.excludedMeshes.push(excludedMesh);
  19432. }
  19433. }
  19434. light._excludedMeshesIds = [];
  19435. }
  19436. // Included check
  19437. if (light._includedOnlyMeshesIds.length > 0) {
  19438. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19439. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19440. if (includedOnlyMesh) {
  19441. light.includedOnlyMeshes.push(includedOnlyMesh);
  19442. }
  19443. }
  19444. light._includedOnlyMeshesIds = [];
  19445. }
  19446. if (!light.canAffectMesh(mesh)) {
  19447. continue;
  19448. }
  19449. needNormals = true;
  19450. this._defines["LIGHT" + lightIndex] = true;
  19451. var type;
  19452. if (light instanceof BABYLON.SpotLight) {
  19453. type = "SPOTLIGHT" + lightIndex;
  19454. }
  19455. else if (light instanceof BABYLON.HemisphericLight) {
  19456. type = "HEMILIGHT" + lightIndex;
  19457. }
  19458. else {
  19459. type = "POINTDIRLIGHT" + lightIndex;
  19460. }
  19461. this._defines[type] = true;
  19462. // Specular
  19463. if (!light.specular.equalsFloats(0, 0, 0)) {
  19464. this._defines.SPECULARTERM = true;
  19465. }
  19466. // Shadows
  19467. if (scene.shadowsEnabled) {
  19468. var shadowGenerator = light.getShadowGenerator();
  19469. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19470. this._defines["SHADOW" + lightIndex] = true;
  19471. this._defines.SHADOWS = true;
  19472. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19473. this._defines["SHADOWVSM" + lightIndex] = true;
  19474. }
  19475. if (shadowGenerator.usePoissonSampling) {
  19476. this._defines["SHADOWPCF" + lightIndex] = true;
  19477. }
  19478. }
  19479. }
  19480. lightIndex++;
  19481. if (lightIndex === maxSimultaneousLights)
  19482. break;
  19483. }
  19484. }
  19485. if (StandardMaterial.FresnelEnabled) {
  19486. // Fresnel
  19487. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19488. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19489. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19490. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19491. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19492. this._defines.DIFFUSEFRESNEL = true;
  19493. }
  19494. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19495. this._defines.OPACITYFRESNEL = true;
  19496. }
  19497. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19498. this._defines.REFLECTIONFRESNEL = true;
  19499. }
  19500. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19501. this._defines.EMISSIVEFRESNEL = true;
  19502. }
  19503. needNormals = true;
  19504. this._defines.FRESNEL = true;
  19505. }
  19506. }
  19507. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19508. this._defines.SPECULAROVERALPHA = true;
  19509. }
  19510. // Attribs
  19511. if (mesh) {
  19512. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19513. this._defines.NORMAL = true;
  19514. }
  19515. if (needUVs) {
  19516. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19517. this._defines.UV1 = true;
  19518. }
  19519. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19520. this._defines.UV2 = true;
  19521. }
  19522. }
  19523. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19524. this._defines.VERTEXCOLOR = true;
  19525. if (mesh.hasVertexAlpha) {
  19526. this._defines.VERTEXALPHA = true;
  19527. }
  19528. }
  19529. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19530. this._defines.BONES = true;
  19531. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19532. this._defines.BONES4 = true;
  19533. }
  19534. // Instances
  19535. if (useInstances) {
  19536. this._defines.INSTANCES = true;
  19537. }
  19538. }
  19539. // Get correct effect
  19540. if (!this._defines.isEqual(this._cachedDefines)) {
  19541. this._defines.cloneTo(this._cachedDefines);
  19542. scene.resetCachedMaterial();
  19543. // Fallbacks
  19544. var fallbacks = new BABYLON.EffectFallbacks();
  19545. if (this._defines.REFLECTION) {
  19546. fallbacks.addFallback(0, "REFLECTION");
  19547. }
  19548. if (this._defines.SPECULAR) {
  19549. fallbacks.addFallback(0, "SPECULAR");
  19550. }
  19551. if (this._defines.BUMP) {
  19552. fallbacks.addFallback(0, "BUMP");
  19553. }
  19554. if (this._defines.SPECULAROVERALPHA) {
  19555. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19556. }
  19557. if (this._defines.FOG) {
  19558. fallbacks.addFallback(1, "FOG");
  19559. }
  19560. for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19561. if (!this._defines["LIGHT" + lightIndex]) {
  19562. continue;
  19563. }
  19564. if (lightIndex > 0) {
  19565. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19566. }
  19567. if (this._defines["SHADOW" + lightIndex]) {
  19568. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19569. }
  19570. if (this._defines["SHADOWPCF" + lightIndex]) {
  19571. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19572. }
  19573. if (this._defines["SHADOWVSM" + lightIndex]) {
  19574. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19575. }
  19576. }
  19577. if (this._defines.SPECULARTERM) {
  19578. fallbacks.addFallback(0, "SPECULARTERM");
  19579. }
  19580. if (this._defines.DIFFUSEFRESNEL) {
  19581. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19582. }
  19583. if (this._defines.OPACITYFRESNEL) {
  19584. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19585. }
  19586. if (this._defines.REFLECTIONFRESNEL) {
  19587. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19588. }
  19589. if (this._defines.EMISSIVEFRESNEL) {
  19590. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19591. }
  19592. if (this._defines.FRESNEL) {
  19593. fallbacks.addFallback(4, "FRESNEL");
  19594. }
  19595. if (this._defines.BONES4) {
  19596. fallbacks.addFallback(0, "BONES4");
  19597. }
  19598. //Attributes
  19599. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19600. if (this._defines.NORMAL) {
  19601. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19602. }
  19603. if (this._defines.UV1) {
  19604. attribs.push(BABYLON.VertexBuffer.UVKind);
  19605. }
  19606. if (this._defines.UV2) {
  19607. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19608. }
  19609. if (this._defines.VERTEXCOLOR) {
  19610. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19611. }
  19612. if (this._defines.BONES) {
  19613. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19614. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19615. }
  19616. if (this._defines.INSTANCES) {
  19617. attribs.push("world0");
  19618. attribs.push("world1");
  19619. attribs.push("world2");
  19620. attribs.push("world3");
  19621. }
  19622. // Legacy browser patch
  19623. var shaderName = "default";
  19624. if (!scene.getEngine().getCaps().standardDerivatives) {
  19625. shaderName = "legacydefault";
  19626. }
  19627. var join = this._defines.toString();
  19628. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19629. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19630. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19631. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19632. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19633. "vFogInfos", "vFogColor", "pointSize",
  19634. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19635. "mBones",
  19636. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19637. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19638. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  19639. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19640. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19641. ], join, fallbacks, this.onCompiled, this.onError);
  19642. }
  19643. if (!this._effect.isReady()) {
  19644. return false;
  19645. }
  19646. this._renderId = scene.getRenderId();
  19647. this._wasPreviouslyReady = true;
  19648. return true;
  19649. };
  19650. StandardMaterial.prototype.unbind = function () {
  19651. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19652. this._effect.setTexture("reflection2DSampler", null);
  19653. }
  19654. _super.prototype.unbind.call(this);
  19655. };
  19656. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19657. this._effect.setMatrix("world", world);
  19658. };
  19659. StandardMaterial.prototype.bind = function (world, mesh) {
  19660. var scene = this.getScene();
  19661. // Matrices
  19662. this.bindOnlyWorldMatrix(world);
  19663. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19664. // Bones
  19665. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19666. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19667. }
  19668. if (scene.getCachedMaterial() !== this) {
  19669. if (StandardMaterial.FresnelEnabled) {
  19670. // Fresnel
  19671. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19672. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19673. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19674. }
  19675. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19676. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19677. }
  19678. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19679. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19680. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19681. }
  19682. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19683. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19684. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19685. }
  19686. }
  19687. // Textures
  19688. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19689. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19690. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19691. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19692. }
  19693. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19694. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19695. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19696. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19697. }
  19698. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19699. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19700. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19701. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19702. }
  19703. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19704. if (this.reflectionTexture.isCube) {
  19705. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19706. }
  19707. else {
  19708. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19709. }
  19710. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19711. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19712. }
  19713. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19714. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19715. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19716. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19717. }
  19718. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19719. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19720. this._effect.setFloat3("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level, this.lightmapThreshold);
  19721. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19722. }
  19723. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19724. this._effect.setTexture("specularSampler", this.specularTexture);
  19725. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19726. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19727. }
  19728. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19729. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19730. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19731. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19732. }
  19733. // Clip plane
  19734. if (scene.clipPlane) {
  19735. var clipPlane = scene.clipPlane;
  19736. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19737. }
  19738. // Point size
  19739. if (this.pointsCloud) {
  19740. this._effect.setFloat("pointSize", this.pointSize);
  19741. }
  19742. // Colors
  19743. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19744. // Scaling down color according to emissive
  19745. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19746. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19747. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19748. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19749. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19750. if (this._defines.SPECULARTERM) {
  19751. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19752. }
  19753. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19754. }
  19755. // Scaling down color according to emissive
  19756. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19757. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19758. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19759. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19760. if (scene.lightsEnabled && !this.disableLighting) {
  19761. var lightIndex = 0;
  19762. for (var index = 0; index < scene.lights.length; index++) {
  19763. var light = scene.lights[index];
  19764. if (!light.isEnabled()) {
  19765. continue;
  19766. }
  19767. if (!light.canAffectMesh(mesh)) {
  19768. continue;
  19769. }
  19770. if (light instanceof BABYLON.PointLight) {
  19771. // Point Light
  19772. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19773. }
  19774. else if (light instanceof BABYLON.DirectionalLight) {
  19775. // Directional Light
  19776. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19777. }
  19778. else if (light instanceof BABYLON.SpotLight) {
  19779. // Spot Light
  19780. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19781. }
  19782. else if (light instanceof BABYLON.HemisphericLight) {
  19783. // Hemispheric Light
  19784. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19785. }
  19786. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19787. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19788. if (this._defines.SPECULARTERM) {
  19789. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19790. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19791. }
  19792. // Shadows
  19793. if (scene.shadowsEnabled) {
  19794. var shadowGenerator = light.getShadowGenerator();
  19795. if (mesh.receiveShadows && shadowGenerator) {
  19796. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19797. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19798. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19799. }
  19800. }
  19801. lightIndex++;
  19802. if (lightIndex === maxSimultaneousLights)
  19803. break;
  19804. }
  19805. }
  19806. // View
  19807. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19808. this._effect.setMatrix("view", scene.getViewMatrix());
  19809. }
  19810. // Fog
  19811. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19812. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19813. this._effect.setColor3("vFogColor", scene.fogColor);
  19814. }
  19815. _super.prototype.bind.call(this, world, mesh);
  19816. };
  19817. StandardMaterial.prototype.getAnimatables = function () {
  19818. var results = [];
  19819. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19820. results.push(this.diffuseTexture);
  19821. }
  19822. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19823. results.push(this.ambientTexture);
  19824. }
  19825. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19826. results.push(this.opacityTexture);
  19827. }
  19828. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19829. results.push(this.reflectionTexture);
  19830. }
  19831. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19832. results.push(this.emissiveTexture);
  19833. }
  19834. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19835. results.push(this.specularTexture);
  19836. }
  19837. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19838. results.push(this.bumpTexture);
  19839. }
  19840. return results;
  19841. };
  19842. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19843. if (this.diffuseTexture) {
  19844. this.diffuseTexture.dispose();
  19845. }
  19846. if (this.ambientTexture) {
  19847. this.ambientTexture.dispose();
  19848. }
  19849. if (this.opacityTexture) {
  19850. this.opacityTexture.dispose();
  19851. }
  19852. if (this.reflectionTexture) {
  19853. this.reflectionTexture.dispose();
  19854. }
  19855. if (this.emissiveTexture) {
  19856. this.emissiveTexture.dispose();
  19857. }
  19858. if (this.specularTexture) {
  19859. this.specularTexture.dispose();
  19860. }
  19861. if (this.bumpTexture) {
  19862. this.bumpTexture.dispose();
  19863. }
  19864. _super.prototype.dispose.call(this, forceDisposeEffect);
  19865. };
  19866. StandardMaterial.prototype.clone = function (name) {
  19867. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19868. // Base material
  19869. this.copyTo(newStandardMaterial);
  19870. // Standard material
  19871. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19872. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19873. }
  19874. if (this.ambientTexture && this.ambientTexture.clone) {
  19875. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19876. }
  19877. if (this.opacityTexture && this.opacityTexture.clone) {
  19878. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19879. }
  19880. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19881. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19882. }
  19883. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19884. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19885. }
  19886. if (this.specularTexture && this.specularTexture.clone) {
  19887. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19888. }
  19889. if (this.bumpTexture && this.bumpTexture.clone) {
  19890. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19891. }
  19892. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19893. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19894. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19895. newStandardMaterial.lightmapThreshold = this.lightmapThreshold;
  19896. }
  19897. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19898. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19899. newStandardMaterial.specularColor = this.specularColor.clone();
  19900. newStandardMaterial.specularPower = this.specularPower;
  19901. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19902. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19903. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19904. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19905. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19906. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19907. newStandardMaterial.roughness = this.roughness;
  19908. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19909. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19910. }
  19911. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19912. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19913. }
  19914. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19915. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19916. }
  19917. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19918. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19919. }
  19920. return newStandardMaterial;
  19921. };
  19922. // Statics
  19923. // Flags used to enable or disable a type of texture for all Standard Materials
  19924. StandardMaterial.DiffuseTextureEnabled = true;
  19925. StandardMaterial.AmbientTextureEnabled = true;
  19926. StandardMaterial.OpacityTextureEnabled = true;
  19927. StandardMaterial.ReflectionTextureEnabled = true;
  19928. StandardMaterial.EmissiveTextureEnabled = true;
  19929. StandardMaterial.SpecularTextureEnabled = true;
  19930. StandardMaterial.BumpTextureEnabled = true;
  19931. StandardMaterial.FresnelEnabled = true;
  19932. StandardMaterial.LightmapEnabled = true;
  19933. return StandardMaterial;
  19934. })(BABYLON.Material);
  19935. BABYLON.StandardMaterial = StandardMaterial;
  19936. })(BABYLON || (BABYLON = {}));
  19937. var BABYLON;
  19938. (function (BABYLON) {
  19939. var MultiMaterial = (function (_super) {
  19940. __extends(MultiMaterial, _super);
  19941. function MultiMaterial(name, scene) {
  19942. _super.call(this, name, scene, true);
  19943. this.subMaterials = new Array();
  19944. scene.multiMaterials.push(this);
  19945. }
  19946. // Properties
  19947. MultiMaterial.prototype.getSubMaterial = function (index) {
  19948. if (index < 0 || index >= this.subMaterials.length) {
  19949. return this.getScene().defaultMaterial;
  19950. }
  19951. return this.subMaterials[index];
  19952. };
  19953. // Methods
  19954. MultiMaterial.prototype.isReady = function (mesh) {
  19955. for (var index = 0; index < this.subMaterials.length; index++) {
  19956. var subMaterial = this.subMaterials[index];
  19957. if (subMaterial) {
  19958. if (!this.subMaterials[index].isReady(mesh)) {
  19959. return false;
  19960. }
  19961. }
  19962. }
  19963. return true;
  19964. };
  19965. MultiMaterial.prototype.clone = function (name) {
  19966. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19967. for (var index = 0; index < this.subMaterials.length; index++) {
  19968. var subMaterial = this.subMaterials[index];
  19969. newMultiMaterial.subMaterials.push(subMaterial);
  19970. }
  19971. return newMultiMaterial;
  19972. };
  19973. return MultiMaterial;
  19974. })(BABYLON.Material);
  19975. BABYLON.MultiMaterial = MultiMaterial;
  19976. })(BABYLON || (BABYLON = {}));
  19977. var BABYLON;
  19978. (function (BABYLON) {
  19979. var SceneLoader = (function () {
  19980. function SceneLoader() {
  19981. }
  19982. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19983. get: function () {
  19984. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19985. },
  19986. set: function (value) {
  19987. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19988. },
  19989. enumerable: true,
  19990. configurable: true
  19991. });
  19992. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19993. get: function () {
  19994. return SceneLoader._ShowLoadingScreen;
  19995. },
  19996. set: function (value) {
  19997. SceneLoader._ShowLoadingScreen = value;
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20003. var dotPosition = sceneFilename.lastIndexOf(".");
  20004. var queryStringPosition = sceneFilename.indexOf("?");
  20005. if (queryStringPosition === -1) {
  20006. queryStringPosition = sceneFilename.length;
  20007. }
  20008. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20009. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20010. var plugin = this._registeredPlugins[index];
  20011. if (plugin.extensions.indexOf(extension) !== -1) {
  20012. return plugin;
  20013. }
  20014. }
  20015. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20016. };
  20017. // Public functions
  20018. SceneLoader.RegisterPlugin = function (plugin) {
  20019. plugin.extensions = plugin.extensions.toLowerCase();
  20020. SceneLoader._registeredPlugins.push(plugin);
  20021. };
  20022. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20023. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20024. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20025. return;
  20026. }
  20027. var loadingToken = {};
  20028. scene._addPendingData(loadingToken);
  20029. var manifestChecked = function (success) {
  20030. scene.database = database;
  20031. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20032. var importMeshFromData = function (data) {
  20033. var meshes = [];
  20034. var particleSystems = [];
  20035. var skeletons = [];
  20036. try {
  20037. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20038. if (onerror) {
  20039. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20040. }
  20041. scene._removePendingData(loadingToken);
  20042. return;
  20043. }
  20044. }
  20045. catch (e) {
  20046. if (onerror) {
  20047. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20048. }
  20049. scene._removePendingData(loadingToken);
  20050. return;
  20051. }
  20052. if (onsuccess) {
  20053. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20054. onsuccess(meshes, particleSystems, skeletons);
  20055. scene._removePendingData(loadingToken);
  20056. }
  20057. };
  20058. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20059. // Direct load
  20060. importMeshFromData(sceneFilename.substr(5));
  20061. return;
  20062. }
  20063. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20064. importMeshFromData(data);
  20065. }, progressCallBack, database);
  20066. };
  20067. if (scene.getEngine().enableOfflineSupport) {
  20068. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20069. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20070. }
  20071. else {
  20072. manifestChecked(true);
  20073. }
  20074. };
  20075. /**
  20076. * Load a scene
  20077. * @param rootUrl a string that defines the root url for scene and resources
  20078. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20079. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20080. */
  20081. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20082. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20083. };
  20084. /**
  20085. * Append a scene
  20086. * @param rootUrl a string that defines the root url for scene and resources
  20087. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20088. * @param scene is the instance of BABYLON.Scene to append to
  20089. */
  20090. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20091. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20092. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20093. return;
  20094. }
  20095. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20096. var database;
  20097. var loadingToken = {};
  20098. scene._addPendingData(loadingToken);
  20099. if (SceneLoader.ShowLoadingScreen) {
  20100. scene.getEngine().displayLoadingUI();
  20101. }
  20102. var loadSceneFromData = function (data) {
  20103. scene.database = database;
  20104. if (!plugin.load(scene, data, rootUrl)) {
  20105. if (onerror) {
  20106. onerror(scene);
  20107. }
  20108. scene._removePendingData(loadingToken);
  20109. scene.getEngine().hideLoadingUI();
  20110. return;
  20111. }
  20112. if (onsuccess) {
  20113. onsuccess(scene);
  20114. }
  20115. scene._removePendingData(loadingToken);
  20116. if (SceneLoader.ShowLoadingScreen) {
  20117. scene.executeWhenReady(function () {
  20118. scene.getEngine().hideLoadingUI();
  20119. });
  20120. }
  20121. };
  20122. var manifestChecked = function (success) {
  20123. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20124. };
  20125. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20126. // Direct load
  20127. loadSceneFromData(sceneFilename.substr(5));
  20128. return;
  20129. }
  20130. if (rootUrl.indexOf("file:") === -1) {
  20131. if (scene.getEngine().enableOfflineSupport) {
  20132. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20133. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20134. }
  20135. else {
  20136. manifestChecked(true);
  20137. }
  20138. }
  20139. else {
  20140. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20141. }
  20142. };
  20143. // Flags
  20144. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20145. SceneLoader._ShowLoadingScreen = true;
  20146. // Members
  20147. SceneLoader._registeredPlugins = new Array();
  20148. return SceneLoader;
  20149. })();
  20150. BABYLON.SceneLoader = SceneLoader;
  20151. ;
  20152. })(BABYLON || (BABYLON = {}));
  20153. var BABYLON;
  20154. (function (BABYLON) {
  20155. var Internals;
  20156. (function (Internals) {
  20157. var checkColors4 = function (colors, count) {
  20158. // Check if color3 was used
  20159. if (colors.length === count * 3) {
  20160. var colors4 = [];
  20161. for (var index = 0; index < colors.length; index += 3) {
  20162. var newIndex = (index / 3) * 4;
  20163. colors4[newIndex] = colors[index];
  20164. colors4[newIndex + 1] = colors[index + 1];
  20165. colors4[newIndex + 2] = colors[index + 2];
  20166. colors4[newIndex + 3] = 1.0;
  20167. }
  20168. return colors4;
  20169. }
  20170. return colors;
  20171. };
  20172. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  20173. var texture = null;
  20174. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  20175. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20176. texture.name = parsedTexture.name;
  20177. texture.hasAlpha = parsedTexture.hasAlpha;
  20178. texture.level = parsedTexture.level;
  20179. texture.coordinatesMode = parsedTexture.coordinatesMode;
  20180. }
  20181. return texture;
  20182. };
  20183. var loadTexture = function (rootUrl, parsedTexture, scene) {
  20184. if (parsedTexture.isCube) {
  20185. return loadCubeTexture(rootUrl, parsedTexture, scene);
  20186. }
  20187. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20188. return null;
  20189. }
  20190. var texture;
  20191. if (parsedTexture.mirrorPlane) {
  20192. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20193. texture._waitingRenderList = parsedTexture.renderList;
  20194. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20195. }
  20196. else if (parsedTexture.isRenderTarget) {
  20197. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20198. texture._waitingRenderList = parsedTexture.renderList;
  20199. }
  20200. else {
  20201. if (parsedTexture.base64String) {
  20202. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20203. }
  20204. else {
  20205. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  20206. }
  20207. }
  20208. texture.name = parsedTexture.name;
  20209. texture.hasAlpha = parsedTexture.hasAlpha;
  20210. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  20211. texture.level = parsedTexture.level;
  20212. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  20213. texture.coordinatesMode = parsedTexture.coordinatesMode;
  20214. texture.uOffset = parsedTexture.uOffset;
  20215. texture.vOffset = parsedTexture.vOffset;
  20216. texture.uScale = parsedTexture.uScale;
  20217. texture.vScale = parsedTexture.vScale;
  20218. texture.uAng = parsedTexture.uAng;
  20219. texture.vAng = parsedTexture.vAng;
  20220. texture.wAng = parsedTexture.wAng;
  20221. texture.wrapU = parsedTexture.wrapU;
  20222. texture.wrapV = parsedTexture.wrapV;
  20223. // Animations
  20224. if (parsedTexture.animations) {
  20225. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20226. var parsedAnimation = parsedTexture.animations[animationIndex];
  20227. texture.animations.push(parseAnimation(parsedAnimation));
  20228. }
  20229. }
  20230. return texture;
  20231. };
  20232. var parseSkeleton = function (parsedSkeleton, scene) {
  20233. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  20234. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  20235. var parsedBone = parsedSkeleton.bones[index];
  20236. var parentBone = null;
  20237. if (parsedBone.parentBoneIndex > -1) {
  20238. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  20239. }
  20240. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  20241. if (parsedBone.animation) {
  20242. bone.animations.push(parseAnimation(parsedBone.animation));
  20243. }
  20244. }
  20245. return skeleton;
  20246. };
  20247. var parseFresnelParameters = function (parsedFresnelParameters) {
  20248. var fresnelParameters = new BABYLON.FresnelParameters();
  20249. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  20250. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  20251. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  20252. fresnelParameters.bias = parsedFresnelParameters.bias;
  20253. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  20254. return fresnelParameters;
  20255. };
  20256. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  20257. var material;
  20258. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  20259. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  20260. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  20261. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  20262. material.specularPower = parsedMaterial.specularPower;
  20263. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  20264. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  20265. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  20266. material.alpha = parsedMaterial.alpha;
  20267. material.id = parsedMaterial.id;
  20268. if (parsedMaterial.disableDepthWrite) {
  20269. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  20270. }
  20271. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  20272. material.backFaceCulling = parsedMaterial.backFaceCulling;
  20273. material.wireframe = parsedMaterial.wireframe;
  20274. if (parsedMaterial.diffuseTexture) {
  20275. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  20276. }
  20277. if (parsedMaterial.diffuseFresnelParameters) {
  20278. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  20279. }
  20280. if (parsedMaterial.ambientTexture) {
  20281. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  20282. }
  20283. if (parsedMaterial.opacityTexture) {
  20284. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  20285. }
  20286. if (parsedMaterial.opacityFresnelParameters) {
  20287. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  20288. }
  20289. if (parsedMaterial.reflectionTexture) {
  20290. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  20291. }
  20292. if (parsedMaterial.reflectionFresnelParameters) {
  20293. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  20294. }
  20295. if (parsedMaterial.emissiveTexture) {
  20296. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  20297. }
  20298. if (parsedMaterial.lightmapTexture) {
  20299. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  20300. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  20301. }
  20302. if (parsedMaterial.emissiveFresnelParameters) {
  20303. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  20304. }
  20305. if (parsedMaterial.specularTexture) {
  20306. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  20307. }
  20308. if (parsedMaterial.bumpTexture) {
  20309. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  20310. }
  20311. if (parsedMaterial.checkReadyOnlyOnce) {
  20312. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  20313. }
  20314. return material;
  20315. };
  20316. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20317. for (var index = 0; index < parsedData.materials.length; index++) {
  20318. var parsedMaterial = parsedData.materials[index];
  20319. if (parsedMaterial.id === id) {
  20320. return parseMaterial(parsedMaterial, scene, rootUrl);
  20321. }
  20322. }
  20323. return null;
  20324. };
  20325. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  20326. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  20327. multiMaterial.id = parsedMultiMaterial.id;
  20328. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  20329. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20330. var subMatId = parsedMultiMaterial.materials[matIndex];
  20331. if (subMatId) {
  20332. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  20333. }
  20334. else {
  20335. multiMaterial.subMaterials.push(null);
  20336. }
  20337. }
  20338. return multiMaterial;
  20339. };
  20340. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  20341. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  20342. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  20343. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  20344. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  20345. var parsedFlare = parsedLensFlareSystem.flares[index];
  20346. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  20347. }
  20348. return lensFlareSystem;
  20349. };
  20350. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  20351. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  20352. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  20353. if (parsedParticleSystem.textureName) {
  20354. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  20355. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  20356. }
  20357. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  20358. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  20359. particleSystem.minSize = parsedParticleSystem.minSize;
  20360. particleSystem.maxSize = parsedParticleSystem.maxSize;
  20361. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  20362. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  20363. particleSystem.emitter = emitter;
  20364. particleSystem.emitRate = parsedParticleSystem.emitRate;
  20365. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  20366. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  20367. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  20368. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  20369. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  20370. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  20371. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  20372. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  20373. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  20374. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  20375. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  20376. particleSystem.blendMode = parsedParticleSystem.blendMode;
  20377. particleSystem.start();
  20378. return particleSystem;
  20379. };
  20380. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  20381. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  20382. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  20383. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  20384. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  20385. shadowGenerator.getShadowMap().renderList.push(mesh);
  20386. }
  20387. if (parsedShadowGenerator.usePoissonSampling) {
  20388. shadowGenerator.usePoissonSampling = true;
  20389. }
  20390. else if (parsedShadowGenerator.useVarianceShadowMap) {
  20391. shadowGenerator.useVarianceShadowMap = true;
  20392. }
  20393. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  20394. shadowGenerator.useBlurVarianceShadowMap = true;
  20395. if (parsedShadowGenerator.blurScale) {
  20396. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  20397. }
  20398. if (parsedShadowGenerator.blurBoxOffset) {
  20399. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  20400. }
  20401. }
  20402. if (parsedShadowGenerator.bias !== undefined) {
  20403. shadowGenerator.bias = parsedShadowGenerator.bias;
  20404. }
  20405. return shadowGenerator;
  20406. };
  20407. var parseAnimation = function (parsedAnimation) {
  20408. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  20409. var dataType = parsedAnimation.dataType;
  20410. var keys = [];
  20411. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  20412. var key = parsedAnimation.keys[index];
  20413. var data;
  20414. switch (dataType) {
  20415. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  20416. data = key.values[0];
  20417. break;
  20418. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  20419. data = BABYLON.Quaternion.FromArray(key.values);
  20420. break;
  20421. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  20422. data = BABYLON.Matrix.FromArray(key.values);
  20423. break;
  20424. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  20425. default:
  20426. data = BABYLON.Vector3.FromArray(key.values);
  20427. break;
  20428. }
  20429. keys.push({
  20430. frame: key.frame,
  20431. value: data
  20432. });
  20433. }
  20434. animation.setKeys(keys);
  20435. return animation;
  20436. };
  20437. var parseLight = function (parsedLight, scene) {
  20438. var light;
  20439. switch (parsedLight.type) {
  20440. case 0:
  20441. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  20442. break;
  20443. case 1:
  20444. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20445. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  20446. break;
  20447. case 2:
  20448. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  20449. break;
  20450. case 3:
  20451. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20452. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  20453. break;
  20454. }
  20455. light.id = parsedLight.id;
  20456. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  20457. if (parsedLight.intensity !== undefined) {
  20458. light.intensity = parsedLight.intensity;
  20459. }
  20460. if (parsedLight.range) {
  20461. light.range = parsedLight.range;
  20462. }
  20463. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  20464. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  20465. if (parsedLight.excludedMeshesIds) {
  20466. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  20467. }
  20468. // Parent
  20469. if (parsedLight.parentId) {
  20470. light._waitingParentId = parsedLight.parentId;
  20471. }
  20472. if (parsedLight.includedOnlyMeshesIds) {
  20473. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  20474. }
  20475. // Animations
  20476. if (parsedLight.animations) {
  20477. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  20478. var parsedAnimation = parsedLight.animations[animationIndex];
  20479. light.animations.push(parseAnimation(parsedAnimation));
  20480. }
  20481. }
  20482. if (parsedLight.autoAnimate) {
  20483. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  20484. }
  20485. };
  20486. var parseCamera = function (parsedCamera, scene) {
  20487. var camera;
  20488. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  20489. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  20490. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  20491. var alpha = parsedCamera.alpha;
  20492. var beta = parsedCamera.beta;
  20493. var radius = parsedCamera.radius;
  20494. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  20495. var interaxial_distance = parsedCamera.interaxial_distance;
  20496. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  20497. }
  20498. else {
  20499. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  20500. }
  20501. }
  20502. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  20503. interaxial_distance = parsedCamera.interaxial_distance;
  20504. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  20505. }
  20506. else if (parsedCamera.type === "DeviceOrientationCamera") {
  20507. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  20508. }
  20509. else if (parsedCamera.type === "FollowCamera") {
  20510. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  20511. camera.heightOffset = parsedCamera.heightOffset;
  20512. camera.radius = parsedCamera.radius;
  20513. camera.rotationOffset = parsedCamera.rotationOffset;
  20514. if (lockedTargetMesh)
  20515. camera.target = lockedTargetMesh;
  20516. }
  20517. else if (parsedCamera.type === "GamepadCamera") {
  20518. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  20519. }
  20520. else if (parsedCamera.type === "TouchCamera") {
  20521. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  20522. }
  20523. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  20524. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  20525. }
  20526. else if (parsedCamera.type === "WebVRFreeCamera") {
  20527. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  20528. }
  20529. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  20530. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  20531. }
  20532. else {
  20533. // Free Camera is the default value
  20534. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20535. }
  20536. // apply 3d rig, when found
  20537. if (parsedCamera.cameraRigMode) {
  20538. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20539. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20540. }
  20541. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20542. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20543. camera.lockedTarget = lockedTargetMesh;
  20544. }
  20545. camera.id = parsedCamera.id;
  20546. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20547. // Parent
  20548. if (parsedCamera.parentId) {
  20549. camera._waitingParentId = parsedCamera.parentId;
  20550. }
  20551. // Target
  20552. if (parsedCamera.target) {
  20553. if (camera.setTarget) {
  20554. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20555. }
  20556. else {
  20557. //For ArcRotate
  20558. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20559. }
  20560. }
  20561. else {
  20562. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20563. }
  20564. camera.fov = parsedCamera.fov;
  20565. camera.minZ = parsedCamera.minZ;
  20566. camera.maxZ = parsedCamera.maxZ;
  20567. camera.speed = parsedCamera.speed;
  20568. camera.inertia = parsedCamera.inertia;
  20569. camera.checkCollisions = parsedCamera.checkCollisions;
  20570. camera.applyGravity = parsedCamera.applyGravity;
  20571. if (parsedCamera.ellipsoid) {
  20572. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20573. }
  20574. // Animations
  20575. if (parsedCamera.animations) {
  20576. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20577. var parsedAnimation = parsedCamera.animations[animationIndex];
  20578. camera.animations.push(parseAnimation(parsedAnimation));
  20579. }
  20580. }
  20581. if (parsedCamera.autoAnimate) {
  20582. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20583. }
  20584. // Layer Mask
  20585. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20586. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20587. }
  20588. else {
  20589. camera.layerMask = 0x0FFFFFFF;
  20590. }
  20591. return camera;
  20592. };
  20593. var parseGeometry = function (parsedGeometry, scene) {
  20594. var id = parsedGeometry.id;
  20595. return scene.getGeometryByID(id);
  20596. };
  20597. var parseBox = function (parsedBox, scene) {
  20598. if (parseGeometry(parsedBox, scene)) {
  20599. return null; // null since geometry could be something else than a box...
  20600. }
  20601. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20602. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20603. scene.pushGeometry(box, true);
  20604. return box;
  20605. };
  20606. var parseSphere = function (parsedSphere, scene) {
  20607. if (parseGeometry(parsedSphere, scene)) {
  20608. return null; // null since geometry could be something else than a sphere...
  20609. }
  20610. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20611. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20612. scene.pushGeometry(sphere, true);
  20613. return sphere;
  20614. };
  20615. var parseCylinder = function (parsedCylinder, scene) {
  20616. if (parseGeometry(parsedCylinder, scene)) {
  20617. return null; // null since geometry could be something else than a cylinder...
  20618. }
  20619. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20620. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20621. scene.pushGeometry(cylinder, true);
  20622. return cylinder;
  20623. };
  20624. var parseTorus = function (parsedTorus, scene) {
  20625. if (parseGeometry(parsedTorus, scene)) {
  20626. return null; // null since geometry could be something else than a torus...
  20627. }
  20628. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20629. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20630. scene.pushGeometry(torus, true);
  20631. return torus;
  20632. };
  20633. var parseGround = function (parsedGround, scene) {
  20634. if (parseGeometry(parsedGround, scene)) {
  20635. return null; // null since geometry could be something else than a ground...
  20636. }
  20637. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20638. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20639. scene.pushGeometry(ground, true);
  20640. return ground;
  20641. };
  20642. var parsePlane = function (parsedPlane, scene) {
  20643. if (parseGeometry(parsedPlane, scene)) {
  20644. return null; // null since geometry could be something else than a plane...
  20645. }
  20646. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20647. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20648. scene.pushGeometry(plane, true);
  20649. return plane;
  20650. };
  20651. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20652. if (parseGeometry(parsedTorusKnot, scene)) {
  20653. return null; // null since geometry could be something else than a torusKnot...
  20654. }
  20655. 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);
  20656. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20657. scene.pushGeometry(torusKnot, true);
  20658. return torusKnot;
  20659. };
  20660. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20661. if (parseGeometry(parsedVertexData, scene)) {
  20662. return null; // null since geometry could be a primitive
  20663. }
  20664. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20665. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20666. if (parsedVertexData.delayLoadingFile) {
  20667. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20668. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20669. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20670. geometry._delayInfo = [];
  20671. if (parsedVertexData.hasUVs) {
  20672. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20673. }
  20674. if (parsedVertexData.hasUVs2) {
  20675. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20676. }
  20677. if (parsedVertexData.hasUVs3) {
  20678. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20679. }
  20680. if (parsedVertexData.hasUVs4) {
  20681. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20682. }
  20683. if (parsedVertexData.hasUVs5) {
  20684. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20685. }
  20686. if (parsedVertexData.hasUVs6) {
  20687. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20688. }
  20689. if (parsedVertexData.hasColors) {
  20690. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20691. }
  20692. if (parsedVertexData.hasMatricesIndices) {
  20693. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20694. }
  20695. if (parsedVertexData.hasMatricesWeights) {
  20696. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20697. }
  20698. geometry._delayLoadingFunction = importVertexData;
  20699. }
  20700. else {
  20701. importVertexData(parsedVertexData, geometry);
  20702. }
  20703. scene.pushGeometry(geometry, true);
  20704. return geometry;
  20705. };
  20706. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20707. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20708. mesh.id = parsedMesh.id;
  20709. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20710. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20711. if (parsedMesh.rotationQuaternion) {
  20712. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20713. }
  20714. else if (parsedMesh.rotation) {
  20715. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20716. }
  20717. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20718. if (parsedMesh.localMatrix) {
  20719. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20720. }
  20721. else if (parsedMesh.pivotMatrix) {
  20722. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20723. }
  20724. mesh.setEnabled(parsedMesh.isEnabled);
  20725. mesh.isVisible = parsedMesh.isVisible;
  20726. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20727. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20728. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20729. if (parsedMesh.applyFog !== undefined) {
  20730. mesh.applyFog = parsedMesh.applyFog;
  20731. }
  20732. if (parsedMesh.pickable !== undefined) {
  20733. mesh.isPickable = parsedMesh.pickable;
  20734. }
  20735. if (parsedMesh.alphaIndex !== undefined) {
  20736. mesh.alphaIndex = parsedMesh.alphaIndex;
  20737. }
  20738. mesh.receiveShadows = parsedMesh.receiveShadows;
  20739. mesh.billboardMode = parsedMesh.billboardMode;
  20740. if (parsedMesh.visibility !== undefined) {
  20741. mesh.visibility = parsedMesh.visibility;
  20742. }
  20743. mesh.checkCollisions = parsedMesh.checkCollisions;
  20744. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20745. // freezeWorldMatrix
  20746. if (parsedMesh.freezeWorldMatrix) {
  20747. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20748. }
  20749. // Parent
  20750. if (parsedMesh.parentId) {
  20751. mesh._waitingParentId = parsedMesh.parentId;
  20752. }
  20753. // Actions
  20754. if (parsedMesh.actions !== undefined) {
  20755. mesh._waitingActions = parsedMesh.actions;
  20756. }
  20757. // Geometry
  20758. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20759. if (parsedMesh.delayLoadingFile) {
  20760. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20761. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20762. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20763. if (parsedMesh._binaryInfo) {
  20764. mesh._binaryInfo = parsedMesh._binaryInfo;
  20765. }
  20766. mesh._delayInfo = [];
  20767. if (parsedMesh.hasUVs) {
  20768. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20769. }
  20770. if (parsedMesh.hasUVs2) {
  20771. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20772. }
  20773. if (parsedMesh.hasUVs3) {
  20774. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20775. }
  20776. if (parsedMesh.hasUVs4) {
  20777. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20778. }
  20779. if (parsedMesh.hasUVs5) {
  20780. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20781. }
  20782. if (parsedMesh.hasUVs6) {
  20783. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20784. }
  20785. if (parsedMesh.hasColors) {
  20786. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20787. }
  20788. if (parsedMesh.hasMatricesIndices) {
  20789. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20790. }
  20791. if (parsedMesh.hasMatricesWeights) {
  20792. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20793. }
  20794. mesh._delayLoadingFunction = importGeometry;
  20795. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20796. mesh._checkDelayState();
  20797. }
  20798. }
  20799. else {
  20800. importGeometry(parsedMesh, mesh);
  20801. }
  20802. // Material
  20803. if (parsedMesh.materialId) {
  20804. mesh.setMaterialByID(parsedMesh.materialId);
  20805. }
  20806. else {
  20807. mesh.material = null;
  20808. }
  20809. // Skeleton
  20810. if (parsedMesh.skeletonId > -1) {
  20811. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20812. }
  20813. // Physics
  20814. if (parsedMesh.physicsImpostor) {
  20815. if (!scene.isPhysicsEnabled()) {
  20816. scene.enablePhysics();
  20817. }
  20818. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20819. }
  20820. // Animations
  20821. if (parsedMesh.animations) {
  20822. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20823. var parsedAnimation = parsedMesh.animations[animationIndex];
  20824. mesh.animations.push(parseAnimation(parsedAnimation));
  20825. }
  20826. }
  20827. if (parsedMesh.autoAnimate) {
  20828. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20829. }
  20830. // Layer Mask
  20831. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20832. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20833. }
  20834. else {
  20835. mesh.layerMask = 0x0FFFFFFF;
  20836. }
  20837. // Instances
  20838. if (parsedMesh.instances) {
  20839. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20840. var parsedInstance = parsedMesh.instances[index];
  20841. var instance = mesh.createInstance(parsedInstance.name);
  20842. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20843. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20844. if (parsedInstance.rotationQuaternion) {
  20845. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20846. }
  20847. else if (parsedInstance.rotation) {
  20848. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20849. }
  20850. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20851. instance.checkCollisions = mesh.checkCollisions;
  20852. if (parsedMesh.animations) {
  20853. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20854. parsedAnimation = parsedMesh.animations[animationIndex];
  20855. instance.animations.push(parseAnimation(parsedAnimation));
  20856. }
  20857. }
  20858. }
  20859. }
  20860. return mesh;
  20861. };
  20862. var parseActions = function (parsedActions, object, scene) {
  20863. var actionManager = new BABYLON.ActionManager(scene);
  20864. if (object === null)
  20865. scene.actionManager = actionManager;
  20866. else
  20867. object.actionManager = actionManager;
  20868. // instanciate a new object
  20869. var instanciate = function (name, params) {
  20870. var newInstance = Object.create(BABYLON[name].prototype);
  20871. newInstance.constructor.apply(newInstance, params);
  20872. return newInstance;
  20873. };
  20874. var parseParameter = function (name, value, target, propertyPath) {
  20875. if (propertyPath === null) {
  20876. // String, boolean or float
  20877. var floatValue = parseFloat(value);
  20878. if (value === "true" || value === "false")
  20879. return value === "true";
  20880. else
  20881. return isNaN(floatValue) ? value : floatValue;
  20882. }
  20883. var effectiveTarget = propertyPath.split(".");
  20884. var values = value.split(",");
  20885. // Get effective Target
  20886. for (var i = 0; i < effectiveTarget.length; i++) {
  20887. target = target[effectiveTarget[i]];
  20888. }
  20889. // Return appropriate value with its type
  20890. if (typeof (target) === "boolean")
  20891. return values[0] === "true";
  20892. if (typeof (target) === "string")
  20893. return values[0];
  20894. // Parameters with multiple values such as Vector3 etc.
  20895. var split = new Array();
  20896. for (var i = 0; i < values.length; i++)
  20897. split.push(parseFloat(values[i]));
  20898. if (target instanceof BABYLON.Vector3)
  20899. return BABYLON.Vector3.FromArray(split);
  20900. if (target instanceof BABYLON.Vector4)
  20901. return BABYLON.Vector4.FromArray(split);
  20902. if (target instanceof BABYLON.Color3)
  20903. return BABYLON.Color3.FromArray(split);
  20904. if (target instanceof BABYLON.Color4)
  20905. return BABYLON.Color4.FromArray(split);
  20906. return parseFloat(values[0]);
  20907. };
  20908. // traverse graph per trigger
  20909. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20910. if (combineArray === void 0) { combineArray = null; }
  20911. if (parsedAction.detached)
  20912. return;
  20913. var parameters = new Array();
  20914. var target = null;
  20915. var propertyPath = null;
  20916. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20917. // Parameters
  20918. if (parsedAction.type === 2)
  20919. parameters.push(actionManager);
  20920. else
  20921. parameters.push(trigger);
  20922. if (combine) {
  20923. var actions = new Array();
  20924. for (var j = 0; j < parsedAction.combine.length; j++) {
  20925. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20926. }
  20927. parameters.push(actions);
  20928. }
  20929. else {
  20930. for (var i = 0; i < parsedAction.properties.length; i++) {
  20931. var value = parsedAction.properties[i].value;
  20932. var name = parsedAction.properties[i].name;
  20933. var targetType = parsedAction.properties[i].targetType;
  20934. if (name === "target")
  20935. if (targetType !== null && targetType === "SceneProperties")
  20936. value = target = scene;
  20937. else
  20938. value = target = scene.getNodeByName(value);
  20939. else if (name === "parent")
  20940. value = scene.getNodeByName(value);
  20941. else if (name === "sound")
  20942. value = scene.getSoundByName(value);
  20943. else if (name !== "propertyPath") {
  20944. if (parsedAction.type === 2 && name === "operator")
  20945. value = BABYLON.ValueCondition[value];
  20946. else
  20947. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20948. }
  20949. else {
  20950. propertyPath = value;
  20951. }
  20952. parameters.push(value);
  20953. }
  20954. }
  20955. if (combineArray === null) {
  20956. parameters.push(condition);
  20957. }
  20958. else {
  20959. parameters.push(null);
  20960. }
  20961. // If interpolate value action
  20962. if (parsedAction.name === "InterpolateValueAction") {
  20963. var param = parameters[parameters.length - 2];
  20964. parameters[parameters.length - 1] = param;
  20965. parameters[parameters.length - 2] = condition;
  20966. }
  20967. // Action or condition(s) and not CombineAction
  20968. var newAction = instanciate(parsedAction.name, parameters);
  20969. if (newAction instanceof BABYLON.Condition && condition !== null) {
  20970. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  20971. if (action)
  20972. action.then(nothing);
  20973. else
  20974. actionManager.registerAction(nothing);
  20975. action = nothing;
  20976. }
  20977. if (combineArray === null) {
  20978. if (newAction instanceof BABYLON.Condition) {
  20979. condition = newAction;
  20980. newAction = action;
  20981. }
  20982. else {
  20983. condition = null;
  20984. if (action)
  20985. action.then(newAction);
  20986. else
  20987. actionManager.registerAction(newAction);
  20988. }
  20989. }
  20990. else {
  20991. combineArray.push(newAction);
  20992. }
  20993. for (var i = 0; i < parsedAction.children.length; i++)
  20994. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20995. };
  20996. // triggers
  20997. for (var i = 0; i < parsedActions.children.length; i++) {
  20998. var triggerParams;
  20999. var trigger = parsedActions.children[i];
  21000. if (trigger.properties.length > 0) {
  21001. var param = trigger.properties[0].value;
  21002. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  21003. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  21004. }
  21005. else
  21006. triggerParams = BABYLON.ActionManager[trigger.name];
  21007. for (var j = 0; j < trigger.children.length; j++) {
  21008. if (!trigger.detached)
  21009. traverse(trigger.children[j], triggerParams, null, null);
  21010. }
  21011. }
  21012. };
  21013. var parseSound = function (parsedSound, scene, rootUrl) {
  21014. var soundName = parsedSound.name;
  21015. var soundUrl = rootUrl + soundName;
  21016. var options = {
  21017. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  21018. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  21019. rolloffFactor: parsedSound.rolloffFactor,
  21020. refDistance: parsedSound.refDistance,
  21021. distanceModel: parsedSound.distanceModel,
  21022. playbackRate: parsedSound.playbackRate
  21023. };
  21024. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  21025. scene._addPendingData(newSound);
  21026. if (parsedSound.position) {
  21027. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  21028. newSound.setPosition(soundPosition);
  21029. }
  21030. if (parsedSound.isDirectional) {
  21031. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  21032. if (parsedSound.localDirectionToMesh) {
  21033. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  21034. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  21035. }
  21036. }
  21037. if (parsedSound.connectedMeshId) {
  21038. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  21039. if (connectedMesh) {
  21040. newSound.attachToMesh(connectedMesh);
  21041. }
  21042. }
  21043. };
  21044. var isDescendantOf = function (mesh, names, hierarchyIds) {
  21045. names = (names instanceof Array) ? names : [names];
  21046. for (var i in names) {
  21047. if (mesh.name === names[i]) {
  21048. hierarchyIds.push(mesh.id);
  21049. return true;
  21050. }
  21051. }
  21052. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  21053. hierarchyIds.push(mesh.id);
  21054. return true;
  21055. }
  21056. return false;
  21057. };
  21058. var importVertexData = function (parsedVertexData, geometry) {
  21059. var vertexData = new BABYLON.VertexData();
  21060. // positions
  21061. var positions = parsedVertexData.positions;
  21062. if (positions) {
  21063. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  21064. }
  21065. // normals
  21066. var normals = parsedVertexData.normals;
  21067. if (normals) {
  21068. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  21069. }
  21070. // uvs
  21071. var uvs = parsedVertexData.uvs;
  21072. if (uvs) {
  21073. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  21074. }
  21075. // uv2s
  21076. var uv2s = parsedVertexData.uv2s;
  21077. if (uv2s) {
  21078. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  21079. }
  21080. // uv3s
  21081. var uv3s = parsedVertexData.uv3s;
  21082. if (uv3s) {
  21083. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  21084. }
  21085. // uv4s
  21086. var uv4s = parsedVertexData.uv4s;
  21087. if (uv4s) {
  21088. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  21089. }
  21090. // uv5s
  21091. var uv5s = parsedVertexData.uv5s;
  21092. if (uv5s) {
  21093. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  21094. }
  21095. // uv6s
  21096. var uv6s = parsedVertexData.uv6s;
  21097. if (uv6s) {
  21098. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  21099. }
  21100. // colors
  21101. var colors = parsedVertexData.colors;
  21102. if (colors) {
  21103. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  21104. }
  21105. // matricesIndices
  21106. var matricesIndices = parsedVertexData.matricesIndices;
  21107. if (matricesIndices) {
  21108. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  21109. }
  21110. // matricesWeights
  21111. var matricesWeights = parsedVertexData.matricesWeights;
  21112. if (matricesWeights) {
  21113. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  21114. }
  21115. // indices
  21116. var indices = parsedVertexData.indices;
  21117. if (indices) {
  21118. vertexData.indices = indices;
  21119. }
  21120. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  21121. };
  21122. var importGeometry = function (parsedGeometry, mesh) {
  21123. var scene = mesh.getScene();
  21124. // Geometry
  21125. var geometryId = parsedGeometry.geometryId;
  21126. if (geometryId) {
  21127. var geometry = scene.getGeometryByID(geometryId);
  21128. if (geometry) {
  21129. geometry.applyToMesh(mesh);
  21130. }
  21131. }
  21132. else if (parsedGeometry instanceof ArrayBuffer) {
  21133. var binaryInfo = mesh._binaryInfo;
  21134. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  21135. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  21136. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  21137. }
  21138. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  21139. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  21140. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  21141. }
  21142. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  21143. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  21144. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  21145. }
  21146. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  21147. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  21148. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  21149. }
  21150. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  21151. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  21152. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  21153. }
  21154. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  21155. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  21156. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  21157. }
  21158. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  21159. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  21160. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  21161. }
  21162. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  21163. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  21164. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  21165. }
  21166. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  21167. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  21168. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  21169. }
  21170. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  21171. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  21172. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  21173. }
  21174. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  21175. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  21176. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  21177. }
  21178. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  21179. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  21180. mesh.setIndices(indicesData);
  21181. }
  21182. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  21183. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  21184. mesh.subMeshes = [];
  21185. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  21186. var materialIndex = subMeshesData[(i * 5) + 0];
  21187. var verticesStart = subMeshesData[(i * 5) + 1];
  21188. var verticesCount = subMeshesData[(i * 5) + 2];
  21189. var indexStart = subMeshesData[(i * 5) + 3];
  21190. var indexCount = subMeshesData[(i * 5) + 4];
  21191. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  21192. }
  21193. }
  21194. }
  21195. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  21196. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  21197. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  21198. if (parsedGeometry.uvs) {
  21199. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  21200. }
  21201. if (parsedGeometry.uvs2) {
  21202. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  21203. }
  21204. if (parsedGeometry.uvs3) {
  21205. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  21206. }
  21207. if (parsedGeometry.uvs4) {
  21208. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  21209. }
  21210. if (parsedGeometry.uvs5) {
  21211. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  21212. }
  21213. if (parsedGeometry.uvs6) {
  21214. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  21215. }
  21216. if (parsedGeometry.colors) {
  21217. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  21218. }
  21219. if (parsedGeometry.matricesIndices) {
  21220. if (!parsedGeometry.matricesIndices._isExpanded) {
  21221. var floatIndices = [];
  21222. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  21223. var matricesIndex = parsedGeometry.matricesIndices[i];
  21224. floatIndices.push(matricesIndex & 0x000000FF);
  21225. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  21226. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  21227. floatIndices.push(matricesIndex >> 24);
  21228. }
  21229. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  21230. }
  21231. else {
  21232. delete parsedGeometry.matricesIndices._isExpanded;
  21233. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  21234. }
  21235. }
  21236. if (parsedGeometry.matricesWeights) {
  21237. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  21238. }
  21239. mesh.setIndices(parsedGeometry.indices);
  21240. }
  21241. // SubMeshes
  21242. if (parsedGeometry.subMeshes) {
  21243. mesh.subMeshes = [];
  21244. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  21245. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  21246. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  21247. }
  21248. }
  21249. // Flat shading
  21250. if (mesh._shouldGenerateFlatShading) {
  21251. mesh.convertToFlatShadedMesh();
  21252. delete mesh._shouldGenerateFlatShading;
  21253. }
  21254. // Update
  21255. mesh.computeWorldMatrix(true);
  21256. // Octree
  21257. if (scene._selectionOctree) {
  21258. scene._selectionOctree.addMesh(mesh);
  21259. }
  21260. };
  21261. BABYLON.SceneLoader.RegisterPlugin({
  21262. extensions: ".babylon",
  21263. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21264. var parsedData = JSON.parse(data);
  21265. var loadedSkeletonsIds = [];
  21266. var loadedMaterialsIds = [];
  21267. var hierarchyIds = [];
  21268. for (var index = 0; index < parsedData.meshes.length; index++) {
  21269. var parsedMesh = parsedData.meshes[index];
  21270. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21271. if (meshesNames instanceof Array) {
  21272. // Remove found mesh name from list.
  21273. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21274. }
  21275. //Geometry?
  21276. if (parsedMesh.geometryId) {
  21277. //does the file contain geometries?
  21278. if (parsedData.geometries) {
  21279. //find the correct geometry and add it to the scene
  21280. var found = false;
  21281. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21282. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21283. return;
  21284. }
  21285. else {
  21286. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21287. if (parsedGeometryData.id == parsedMesh.geometryId) {
  21288. switch (geometryType) {
  21289. case "boxes":
  21290. parseBox(parsedGeometryData, scene);
  21291. break;
  21292. case "spheres":
  21293. parseSphere(parsedGeometryData, scene);
  21294. break;
  21295. case "cylinders":
  21296. parseCylinder(parsedGeometryData, scene);
  21297. break;
  21298. case "toruses":
  21299. parseTorus(parsedGeometryData, scene);
  21300. break;
  21301. case "grounds":
  21302. parseGround(parsedGeometryData, scene);
  21303. break;
  21304. case "planes":
  21305. parsePlane(parsedGeometryData, scene);
  21306. break;
  21307. case "torusKnots":
  21308. parseTorusKnot(parsedGeometryData, scene);
  21309. break;
  21310. case "vertexData":
  21311. parseVertexData(parsedGeometryData, scene, rootUrl);
  21312. break;
  21313. }
  21314. found = true;
  21315. }
  21316. });
  21317. }
  21318. });
  21319. if (!found) {
  21320. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21321. }
  21322. }
  21323. }
  21324. // Material ?
  21325. if (parsedMesh.materialId) {
  21326. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21327. if (!materialFound && parsedData.multiMaterials) {
  21328. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  21329. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21330. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  21331. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  21332. var subMatId = parsedMultiMaterial.materials[matIndex];
  21333. loadedMaterialsIds.push(subMatId);
  21334. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21335. }
  21336. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21337. parseMultiMaterial(parsedMultiMaterial, scene);
  21338. materialFound = true;
  21339. break;
  21340. }
  21341. }
  21342. }
  21343. if (!materialFound) {
  21344. loadedMaterialsIds.push(parsedMesh.materialId);
  21345. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21346. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21347. }
  21348. }
  21349. }
  21350. // Skeleton ?
  21351. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21352. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21353. if (!skeletonAlreadyLoaded) {
  21354. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  21355. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21356. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21357. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  21358. loadedSkeletonsIds.push(parsedSkeleton.id);
  21359. }
  21360. }
  21361. }
  21362. }
  21363. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  21364. meshes.push(mesh);
  21365. }
  21366. }
  21367. // Connecting parents
  21368. for (index = 0; index < scene.meshes.length; index++) {
  21369. var currentMesh = scene.meshes[index];
  21370. if (currentMesh._waitingParentId) {
  21371. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21372. currentMesh._waitingParentId = undefined;
  21373. }
  21374. }
  21375. // freeze world matrix application
  21376. for (index = 0; index < scene.meshes.length; index++) {
  21377. var currentMesh = scene.meshes[index];
  21378. if (currentMesh._waitingFreezeWorldMatrix) {
  21379. currentMesh.freezeWorldMatrix();
  21380. currentMesh._waitingFreezeWorldMatrix = undefined;
  21381. }
  21382. }
  21383. // Particles
  21384. if (parsedData.particleSystems) {
  21385. for (index = 0; index < parsedData.particleSystems.length; index++) {
  21386. var parsedParticleSystem = parsedData.particleSystems[index];
  21387. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21388. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  21389. }
  21390. }
  21391. }
  21392. return true;
  21393. },
  21394. load: function (scene, data, rootUrl) {
  21395. var parsedData = JSON.parse(data);
  21396. // Scene
  21397. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21398. scene.autoClear = parsedData.autoClear;
  21399. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21400. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21401. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21402. // Fog
  21403. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21404. scene.fogMode = parsedData.fogMode;
  21405. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21406. scene.fogStart = parsedData.fogStart;
  21407. scene.fogEnd = parsedData.fogEnd;
  21408. scene.fogDensity = parsedData.fogDensity;
  21409. }
  21410. // Lights
  21411. for (var index = 0; index < parsedData.lights.length; index++) {
  21412. var parsedLight = parsedData.lights[index];
  21413. parseLight(parsedLight, scene);
  21414. }
  21415. // Materials
  21416. if (parsedData.materials) {
  21417. for (index = 0; index < parsedData.materials.length; index++) {
  21418. var parsedMaterial = parsedData.materials[index];
  21419. parseMaterial(parsedMaterial, scene, rootUrl);
  21420. }
  21421. }
  21422. if (parsedData.multiMaterials) {
  21423. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  21424. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21425. parseMultiMaterial(parsedMultiMaterial, scene);
  21426. }
  21427. }
  21428. // Skeletons
  21429. if (parsedData.skeletons) {
  21430. for (index = 0; index < parsedData.skeletons.length; index++) {
  21431. var parsedSkeleton = parsedData.skeletons[index];
  21432. parseSkeleton(parsedSkeleton, scene);
  21433. }
  21434. }
  21435. // Geometries
  21436. var geometries = parsedData.geometries;
  21437. if (geometries) {
  21438. // Boxes
  21439. var boxes = geometries.boxes;
  21440. if (boxes) {
  21441. for (index = 0; index < boxes.length; index++) {
  21442. var parsedBox = boxes[index];
  21443. parseBox(parsedBox, scene);
  21444. }
  21445. }
  21446. // Spheres
  21447. var spheres = geometries.spheres;
  21448. if (spheres) {
  21449. for (index = 0; index < spheres.length; index++) {
  21450. var parsedSphere = spheres[index];
  21451. parseSphere(parsedSphere, scene);
  21452. }
  21453. }
  21454. // Cylinders
  21455. var cylinders = geometries.cylinders;
  21456. if (cylinders) {
  21457. for (index = 0; index < cylinders.length; index++) {
  21458. var parsedCylinder = cylinders[index];
  21459. parseCylinder(parsedCylinder, scene);
  21460. }
  21461. }
  21462. // Toruses
  21463. var toruses = geometries.toruses;
  21464. if (toruses) {
  21465. for (index = 0; index < toruses.length; index++) {
  21466. var parsedTorus = toruses[index];
  21467. parseTorus(parsedTorus, scene);
  21468. }
  21469. }
  21470. // Grounds
  21471. var grounds = geometries.grounds;
  21472. if (grounds) {
  21473. for (index = 0; index < grounds.length; index++) {
  21474. var parsedGround = grounds[index];
  21475. parseGround(parsedGround, scene);
  21476. }
  21477. }
  21478. // Planes
  21479. var planes = geometries.planes;
  21480. if (planes) {
  21481. for (index = 0; index < planes.length; index++) {
  21482. var parsedPlane = planes[index];
  21483. parsePlane(parsedPlane, scene);
  21484. }
  21485. }
  21486. // TorusKnots
  21487. var torusKnots = geometries.torusKnots;
  21488. if (torusKnots) {
  21489. for (index = 0; index < torusKnots.length; index++) {
  21490. var parsedTorusKnot = torusKnots[index];
  21491. parseTorusKnot(parsedTorusKnot, scene);
  21492. }
  21493. }
  21494. // VertexData
  21495. var vertexData = geometries.vertexData;
  21496. if (vertexData) {
  21497. for (index = 0; index < vertexData.length; index++) {
  21498. var parsedVertexData = vertexData[index];
  21499. parseVertexData(parsedVertexData, scene, rootUrl);
  21500. }
  21501. }
  21502. }
  21503. // Meshes
  21504. for (index = 0; index < parsedData.meshes.length; index++) {
  21505. var parsedMesh = parsedData.meshes[index];
  21506. parseMesh(parsedMesh, scene, rootUrl);
  21507. }
  21508. // Cameras
  21509. for (index = 0; index < parsedData.cameras.length; index++) {
  21510. var parsedCamera = parsedData.cameras[index];
  21511. parseCamera(parsedCamera, scene);
  21512. }
  21513. if (parsedData.activeCameraID) {
  21514. scene.setActiveCameraByID(parsedData.activeCameraID);
  21515. }
  21516. // Browsing all the graph to connect the dots
  21517. for (index = 0; index < scene.cameras.length; index++) {
  21518. var camera = scene.cameras[index];
  21519. if (camera._waitingParentId) {
  21520. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21521. camera._waitingParentId = undefined;
  21522. }
  21523. }
  21524. for (index = 0; index < scene.lights.length; index++) {
  21525. var light = scene.lights[index];
  21526. if (light._waitingParentId) {
  21527. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21528. light._waitingParentId = undefined;
  21529. }
  21530. }
  21531. // Sounds
  21532. if (parsedData.sounds) {
  21533. for (index = 0; index < parsedData.sounds.length; index++) {
  21534. var parsedSound = parsedData.sounds[index];
  21535. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21536. parseSound(parsedSound, scene, rootUrl);
  21537. }
  21538. else {
  21539. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21540. }
  21541. }
  21542. }
  21543. // Connect parents & children and parse actions
  21544. for (index = 0; index < scene.meshes.length; index++) {
  21545. var mesh = scene.meshes[index];
  21546. if (mesh._waitingParentId) {
  21547. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21548. mesh._waitingParentId = undefined;
  21549. }
  21550. if (mesh._waitingActions) {
  21551. parseActions(mesh._waitingActions, mesh, scene);
  21552. mesh._waitingActions = undefined;
  21553. }
  21554. }
  21555. // freeze world matrix application
  21556. for (index = 0; index < scene.meshes.length; index++) {
  21557. var currentMesh = scene.meshes[index];
  21558. if (currentMesh._waitingFreezeWorldMatrix) {
  21559. currentMesh.freezeWorldMatrix();
  21560. currentMesh._waitingFreezeWorldMatrix = undefined;
  21561. }
  21562. }
  21563. // Particles Systems
  21564. if (parsedData.particleSystems) {
  21565. for (index = 0; index < parsedData.particleSystems.length; index++) {
  21566. var parsedParticleSystem = parsedData.particleSystems[index];
  21567. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  21568. }
  21569. }
  21570. // Lens flares
  21571. if (parsedData.lensFlareSystems) {
  21572. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  21573. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21574. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  21575. }
  21576. }
  21577. // Shadows
  21578. if (parsedData.shadowGenerators) {
  21579. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  21580. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21581. parseShadowGenerator(parsedShadowGenerator, scene);
  21582. }
  21583. }
  21584. // Actions (scene)
  21585. if (parsedData.actions) {
  21586. parseActions(parsedData.actions, null, scene);
  21587. }
  21588. // Finish
  21589. return true;
  21590. }
  21591. });
  21592. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21593. })(BABYLON || (BABYLON = {}));
  21594. var BABYLON;
  21595. (function (BABYLON) {
  21596. var SpriteManager = (function () {
  21597. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21599. this.name = name;
  21600. this.cellSize = cellSize;
  21601. this.sprites = new Array();
  21602. this.renderingGroupId = 0;
  21603. this.layerMask = 0x0FFFFFFF;
  21604. this.fogEnabled = true;
  21605. this.isPickable = false;
  21606. this._vertexDeclaration = [4, 4, 4, 4];
  21607. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21608. this._capacity = capacity;
  21609. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21610. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21611. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21612. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21613. this._scene = scene;
  21614. this._scene.spriteManagers.push(this);
  21615. // VBO
  21616. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21617. var indices = [];
  21618. var index = 0;
  21619. for (var count = 0; count < capacity; count++) {
  21620. indices.push(index);
  21621. indices.push(index + 1);
  21622. indices.push(index + 2);
  21623. indices.push(index);
  21624. indices.push(index + 2);
  21625. indices.push(index + 3);
  21626. index += 4;
  21627. }
  21628. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21629. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21630. // Effects
  21631. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21632. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21633. }
  21634. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21635. var arrayOffset = index * 16;
  21636. if (offsetX === 0)
  21637. offsetX = this._epsilon;
  21638. else if (offsetX === 1)
  21639. offsetX = 1 - this._epsilon;
  21640. if (offsetY === 0)
  21641. offsetY = this._epsilon;
  21642. else if (offsetY === 1)
  21643. offsetY = 1 - this._epsilon;
  21644. this._vertices[arrayOffset] = sprite.position.x;
  21645. this._vertices[arrayOffset + 1] = sprite.position.y;
  21646. this._vertices[arrayOffset + 2] = sprite.position.z;
  21647. this._vertices[arrayOffset + 3] = sprite.angle;
  21648. this._vertices[arrayOffset + 4] = sprite.width;
  21649. this._vertices[arrayOffset + 5] = sprite.height;
  21650. this._vertices[arrayOffset + 6] = offsetX;
  21651. this._vertices[arrayOffset + 7] = offsetY;
  21652. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21653. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21654. var offset = (sprite.cellIndex / rowSize) >> 0;
  21655. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21656. this._vertices[arrayOffset + 11] = offset;
  21657. // Color
  21658. this._vertices[arrayOffset + 12] = sprite.color.r;
  21659. this._vertices[arrayOffset + 13] = sprite.color.g;
  21660. this._vertices[arrayOffset + 14] = sprite.color.b;
  21661. this._vertices[arrayOffset + 15] = sprite.color.a;
  21662. };
  21663. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21664. var count = Math.min(this._capacity, this.sprites.length);
  21665. var min = BABYLON.Vector3.Zero();
  21666. var max = BABYLON.Vector3.Zero();
  21667. var distance = Number.MAX_VALUE;
  21668. var currentSprite;
  21669. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21670. var cameraView = camera.getViewMatrix();
  21671. for (var index = 0; index < count; index++) {
  21672. var sprite = this.sprites[index];
  21673. if (!sprite) {
  21674. continue;
  21675. }
  21676. if (predicate) {
  21677. if (!predicate(sprite)) {
  21678. continue;
  21679. }
  21680. }
  21681. else if (!sprite.isPickable) {
  21682. continue;
  21683. }
  21684. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21685. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21686. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21687. if (ray.intersectsBoxMinMax(min, max)) {
  21688. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21689. if (distance > currentDistance) {
  21690. distance = currentDistance;
  21691. currentSprite = sprite;
  21692. if (fastCheck) {
  21693. break;
  21694. }
  21695. }
  21696. }
  21697. }
  21698. if (currentSprite) {
  21699. var result = new BABYLON.PickingInfo();
  21700. result.hit = true;
  21701. result.pickedSprite = currentSprite;
  21702. result.distance = distance;
  21703. return result;
  21704. }
  21705. return null;
  21706. };
  21707. SpriteManager.prototype.render = function () {
  21708. // Check
  21709. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21710. return;
  21711. var engine = this._scene.getEngine();
  21712. var baseSize = this._spriteTexture.getBaseSize();
  21713. // Sprites
  21714. var deltaTime = engine.getDeltaTime();
  21715. var max = Math.min(this._capacity, this.sprites.length);
  21716. var rowSize = baseSize.width / this.cellSize;
  21717. var offset = 0;
  21718. for (var index = 0; index < max; index++) {
  21719. var sprite = this.sprites[index];
  21720. if (!sprite) {
  21721. continue;
  21722. }
  21723. sprite._animate(deltaTime);
  21724. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21725. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21726. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21727. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21728. }
  21729. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21730. // Render
  21731. var effect = this._effectBase;
  21732. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21733. effect = this._effectFog;
  21734. }
  21735. engine.enableEffect(effect);
  21736. var viewMatrix = this._scene.getViewMatrix();
  21737. effect.setTexture("diffuseSampler", this._spriteTexture);
  21738. effect.setMatrix("view", viewMatrix);
  21739. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21740. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21741. // Fog
  21742. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21743. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21744. effect.setColor3("vFogColor", this._scene.fogColor);
  21745. }
  21746. // VBOs
  21747. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21748. // Draw order
  21749. engine.setDepthFunctionToLessOrEqual();
  21750. effect.setBool("alphaTest", true);
  21751. engine.setColorWrite(false);
  21752. engine.draw(true, 0, max * 6);
  21753. engine.setColorWrite(true);
  21754. effect.setBool("alphaTest", false);
  21755. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21756. engine.draw(true, 0, max * 6);
  21757. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21758. };
  21759. SpriteManager.prototype.dispose = function () {
  21760. if (this._vertexBuffer) {
  21761. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21762. this._vertexBuffer = null;
  21763. }
  21764. if (this._indexBuffer) {
  21765. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21766. this._indexBuffer = null;
  21767. }
  21768. if (this._spriteTexture) {
  21769. this._spriteTexture.dispose();
  21770. this._spriteTexture = null;
  21771. }
  21772. // Remove from scene
  21773. var index = this._scene.spriteManagers.indexOf(this);
  21774. this._scene.spriteManagers.splice(index, 1);
  21775. // Callback
  21776. if (this.onDispose) {
  21777. this.onDispose();
  21778. }
  21779. };
  21780. return SpriteManager;
  21781. })();
  21782. BABYLON.SpriteManager = SpriteManager;
  21783. })(BABYLON || (BABYLON = {}));
  21784. var BABYLON;
  21785. (function (BABYLON) {
  21786. var Sprite = (function () {
  21787. function Sprite(name, manager) {
  21788. this.name = name;
  21789. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21790. this.width = 1.0;
  21791. this.height = 1.0;
  21792. this.angle = 0;
  21793. this.cellIndex = 0;
  21794. this.invertU = 0;
  21795. this.invertV = 0;
  21796. this.animations = new Array();
  21797. this.isPickable = false;
  21798. this._animationStarted = false;
  21799. this._loopAnimation = false;
  21800. this._fromIndex = 0;
  21801. this._toIndex = 0;
  21802. this._delay = 0;
  21803. this._direction = 1;
  21804. this._frameCount = 0;
  21805. this._time = 0;
  21806. this._manager = manager;
  21807. this._manager.sprites.push(this);
  21808. this.position = BABYLON.Vector3.Zero();
  21809. }
  21810. Object.defineProperty(Sprite.prototype, "size", {
  21811. get: function () {
  21812. return this.width;
  21813. },
  21814. set: function (value) {
  21815. this.width = value;
  21816. this.height = value;
  21817. },
  21818. enumerable: true,
  21819. configurable: true
  21820. });
  21821. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21822. this._fromIndex = from;
  21823. this._toIndex = to;
  21824. this._loopAnimation = loop;
  21825. this._delay = delay;
  21826. this._animationStarted = true;
  21827. this._direction = from < to ? 1 : -1;
  21828. this.cellIndex = from;
  21829. this._time = 0;
  21830. };
  21831. Sprite.prototype.stopAnimation = function () {
  21832. this._animationStarted = false;
  21833. };
  21834. Sprite.prototype._animate = function (deltaTime) {
  21835. if (!this._animationStarted)
  21836. return;
  21837. this._time += deltaTime;
  21838. if (this._time > this._delay) {
  21839. this._time = this._time % this._delay;
  21840. this.cellIndex += this._direction;
  21841. if (this.cellIndex == this._toIndex) {
  21842. if (this._loopAnimation) {
  21843. this.cellIndex = this._fromIndex;
  21844. }
  21845. else {
  21846. this._animationStarted = false;
  21847. if (this.disposeWhenFinishedAnimating) {
  21848. this.dispose();
  21849. }
  21850. }
  21851. }
  21852. }
  21853. };
  21854. Sprite.prototype.dispose = function () {
  21855. for (var i = 0; i < this._manager.sprites.length; i++) {
  21856. if (this._manager.sprites[i] == this) {
  21857. this._manager.sprites.splice(i, 1);
  21858. }
  21859. }
  21860. };
  21861. return Sprite;
  21862. })();
  21863. BABYLON.Sprite = Sprite;
  21864. })(BABYLON || (BABYLON = {}));
  21865. var BABYLON;
  21866. (function (BABYLON) {
  21867. var Layer = (function () {
  21868. function Layer(name, imgUrl, scene, isBackground, color) {
  21869. this.name = name;
  21870. this._vertexDeclaration = [2];
  21871. this._vertexStrideSize = 2 * 4;
  21872. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21873. this.isBackground = isBackground === undefined ? true : isBackground;
  21874. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21875. this._scene = scene;
  21876. this._scene.layers.push(this);
  21877. // VBO
  21878. var vertices = [];
  21879. vertices.push(1, 1);
  21880. vertices.push(-1, 1);
  21881. vertices.push(-1, -1);
  21882. vertices.push(1, -1);
  21883. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21884. // Indices
  21885. var indices = [];
  21886. indices.push(0);
  21887. indices.push(1);
  21888. indices.push(2);
  21889. indices.push(0);
  21890. indices.push(2);
  21891. indices.push(3);
  21892. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21893. // Effects
  21894. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21895. }
  21896. Layer.prototype.render = function () {
  21897. // Check
  21898. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21899. return;
  21900. var engine = this._scene.getEngine();
  21901. // Render
  21902. engine.enableEffect(this._effect);
  21903. engine.setState(false);
  21904. // Texture
  21905. this._effect.setTexture("textureSampler", this.texture);
  21906. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21907. // Color
  21908. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21909. // VBOs
  21910. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21911. // Draw order
  21912. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21913. engine.draw(true, 0, 6);
  21914. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21915. };
  21916. Layer.prototype.dispose = function () {
  21917. if (this._vertexBuffer) {
  21918. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21919. this._vertexBuffer = null;
  21920. }
  21921. if (this._indexBuffer) {
  21922. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21923. this._indexBuffer = null;
  21924. }
  21925. if (this.texture) {
  21926. this.texture.dispose();
  21927. this.texture = null;
  21928. }
  21929. // Remove from scene
  21930. var index = this._scene.layers.indexOf(this);
  21931. this._scene.layers.splice(index, 1);
  21932. // Callback
  21933. if (this.onDispose) {
  21934. this.onDispose();
  21935. }
  21936. };
  21937. return Layer;
  21938. })();
  21939. BABYLON.Layer = Layer;
  21940. })(BABYLON || (BABYLON = {}));
  21941. var BABYLON;
  21942. (function (BABYLON) {
  21943. var Particle = (function () {
  21944. function Particle() {
  21945. this.position = BABYLON.Vector3.Zero();
  21946. this.direction = BABYLON.Vector3.Zero();
  21947. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21948. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21949. this.lifeTime = 1.0;
  21950. this.age = 0;
  21951. this.size = 0;
  21952. this.angle = 0;
  21953. this.angularSpeed = 0;
  21954. }
  21955. Particle.prototype.copyTo = function (other) {
  21956. other.position.copyFrom(this.position);
  21957. other.direction.copyFrom(this.direction);
  21958. other.color.copyFrom(this.color);
  21959. other.colorStep.copyFrom(this.colorStep);
  21960. other.lifeTime = this.lifeTime;
  21961. other.age = this.age;
  21962. other.size = this.size;
  21963. other.angle = this.angle;
  21964. other.angularSpeed = this.angularSpeed;
  21965. };
  21966. return Particle;
  21967. })();
  21968. BABYLON.Particle = Particle;
  21969. })(BABYLON || (BABYLON = {}));
  21970. var BABYLON;
  21971. (function (BABYLON) {
  21972. var randomNumber = function (min, max) {
  21973. if (min === max) {
  21974. return (min);
  21975. }
  21976. var random = Math.random();
  21977. return ((random * (max - min)) + min);
  21978. };
  21979. var ParticleSystem = (function () {
  21980. function ParticleSystem(name, capacity, scene, customEffect) {
  21981. var _this = this;
  21982. this.name = name;
  21983. this.renderingGroupId = 0;
  21984. this.emitter = null;
  21985. this.emitRate = 10;
  21986. this.manualEmitCount = -1;
  21987. this.updateSpeed = 0.01;
  21988. this.targetStopDuration = 0;
  21989. this.disposeOnStop = false;
  21990. this.minEmitPower = 1;
  21991. this.maxEmitPower = 1;
  21992. this.minLifeTime = 1;
  21993. this.maxLifeTime = 1;
  21994. this.minSize = 1;
  21995. this.maxSize = 1;
  21996. this.minAngularSpeed = 0;
  21997. this.maxAngularSpeed = 0;
  21998. this.layerMask = 0x0FFFFFFF;
  21999. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  22000. this.forceDepthWrite = false;
  22001. this.gravity = BABYLON.Vector3.Zero();
  22002. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  22003. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  22004. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  22005. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  22006. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  22007. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  22008. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  22009. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  22010. this.particles = new Array();
  22011. this._vertexDeclaration = [3, 4, 4];
  22012. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  22013. this._stockParticles = new Array();
  22014. this._newPartsExcess = 0;
  22015. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  22016. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  22017. this._scaledDirection = BABYLON.Vector3.Zero();
  22018. this._scaledGravity = BABYLON.Vector3.Zero();
  22019. this._currentRenderId = -1;
  22020. this._started = false;
  22021. this._stopped = false;
  22022. this._actualFrame = 0;
  22023. this.id = name;
  22024. this._capacity = capacity;
  22025. this._scene = scene;
  22026. this._customEffect = customEffect;
  22027. scene.particleSystems.push(this);
  22028. // VBO
  22029. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  22030. var indices = [];
  22031. var index = 0;
  22032. for (var count = 0; count < capacity; count++) {
  22033. indices.push(index);
  22034. indices.push(index + 1);
  22035. indices.push(index + 2);
  22036. indices.push(index);
  22037. indices.push(index + 2);
  22038. indices.push(index + 3);
  22039. index += 4;
  22040. }
  22041. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22042. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  22043. // Default behaviors
  22044. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  22045. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  22046. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  22047. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  22048. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  22049. };
  22050. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  22051. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  22052. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  22053. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  22054. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  22055. };
  22056. this.updateFunction = function (particles) {
  22057. for (var index = 0; index < particles.length; index++) {
  22058. var particle = particles[index];
  22059. particle.age += _this._scaledUpdateSpeed;
  22060. if (particle.age >= particle.lifeTime) {
  22061. _this.recycleParticle(particle);
  22062. index--;
  22063. continue;
  22064. }
  22065. else {
  22066. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  22067. particle.color.addInPlace(_this._scaledColorStep);
  22068. if (particle.color.a < 0)
  22069. particle.color.a = 0;
  22070. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  22071. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  22072. particle.position.addInPlace(_this._scaledDirection);
  22073. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  22074. particle.direction.addInPlace(_this._scaledGravity);
  22075. }
  22076. }
  22077. };
  22078. }
  22079. ParticleSystem.prototype.recycleParticle = function (particle) {
  22080. var lastParticle = this.particles.pop();
  22081. if (lastParticle !== particle) {
  22082. lastParticle.copyTo(particle);
  22083. this._stockParticles.push(lastParticle);
  22084. }
  22085. };
  22086. ParticleSystem.prototype.getCapacity = function () {
  22087. return this._capacity;
  22088. };
  22089. ParticleSystem.prototype.isAlive = function () {
  22090. return this._alive;
  22091. };
  22092. ParticleSystem.prototype.isStarted = function () {
  22093. return this._started;
  22094. };
  22095. ParticleSystem.prototype.start = function () {
  22096. this._started = true;
  22097. this._stopped = false;
  22098. this._actualFrame = 0;
  22099. };
  22100. ParticleSystem.prototype.stop = function () {
  22101. this._stopped = true;
  22102. };
  22103. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  22104. var offset = index * 11;
  22105. this._vertices[offset] = particle.position.x;
  22106. this._vertices[offset + 1] = particle.position.y;
  22107. this._vertices[offset + 2] = particle.position.z;
  22108. this._vertices[offset + 3] = particle.color.r;
  22109. this._vertices[offset + 4] = particle.color.g;
  22110. this._vertices[offset + 5] = particle.color.b;
  22111. this._vertices[offset + 6] = particle.color.a;
  22112. this._vertices[offset + 7] = particle.angle;
  22113. this._vertices[offset + 8] = particle.size;
  22114. this._vertices[offset + 9] = offsetX;
  22115. this._vertices[offset + 10] = offsetY;
  22116. };
  22117. ParticleSystem.prototype._update = function (newParticles) {
  22118. // Update current
  22119. this._alive = this.particles.length > 0;
  22120. this.updateFunction(this.particles);
  22121. // Add new ones
  22122. var worldMatrix;
  22123. if (this.emitter.position) {
  22124. worldMatrix = this.emitter.getWorldMatrix();
  22125. }
  22126. else {
  22127. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  22128. }
  22129. for (var index = 0; index < newParticles; index++) {
  22130. if (this.particles.length === this._capacity) {
  22131. break;
  22132. }
  22133. if (this._stockParticles.length !== 0) {
  22134. var particle = this._stockParticles.pop();
  22135. particle.age = 0;
  22136. }
  22137. else {
  22138. particle = new BABYLON.Particle();
  22139. }
  22140. this.particles.push(particle);
  22141. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  22142. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  22143. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  22144. particle.size = randomNumber(this.minSize, this.maxSize);
  22145. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  22146. this.startPositionFunction(worldMatrix, particle.position);
  22147. var step = randomNumber(0, 1.0);
  22148. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  22149. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  22150. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  22151. }
  22152. };
  22153. ParticleSystem.prototype._getEffect = function () {
  22154. if (this._customEffect) {
  22155. return this._customEffect;
  22156. }
  22157. ;
  22158. var defines = [];
  22159. if (this._scene.clipPlane) {
  22160. defines.push("#define CLIPPLANE");
  22161. }
  22162. // Effect
  22163. var join = defines.join("\n");
  22164. if (this._cachedDefines !== join) {
  22165. this._cachedDefines = join;
  22166. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  22167. }
  22168. return this._effect;
  22169. };
  22170. ParticleSystem.prototype.animate = function () {
  22171. if (!this._started)
  22172. return;
  22173. var effect = this._getEffect();
  22174. // Check
  22175. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  22176. return;
  22177. if (this._currentRenderId === this._scene.getRenderId()) {
  22178. return;
  22179. }
  22180. this._currentRenderId = this._scene.getRenderId();
  22181. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  22182. // determine the number of particles we need to create
  22183. var emitCout;
  22184. if (this.manualEmitCount > -1) {
  22185. emitCout = this.manualEmitCount;
  22186. this.manualEmitCount = 0;
  22187. }
  22188. else {
  22189. emitCout = this.emitRate;
  22190. }
  22191. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  22192. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  22193. if (this._newPartsExcess > 1.0) {
  22194. newParticles += this._newPartsExcess >> 0;
  22195. this._newPartsExcess -= this._newPartsExcess >> 0;
  22196. }
  22197. this._alive = false;
  22198. if (!this._stopped) {
  22199. this._actualFrame += this._scaledUpdateSpeed;
  22200. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22201. this.stop();
  22202. }
  22203. else {
  22204. newParticles = 0;
  22205. }
  22206. this._update(newParticles);
  22207. // Stopped?
  22208. if (this._stopped) {
  22209. if (!this._alive) {
  22210. this._started = false;
  22211. if (this.disposeOnStop) {
  22212. this._scene._toBeDisposed.push(this);
  22213. }
  22214. }
  22215. }
  22216. // Update VBO
  22217. var offset = 0;
  22218. for (var index = 0; index < this.particles.length; index++) {
  22219. var particle = this.particles[index];
  22220. this._appendParticleVertex(offset++, particle, 0, 0);
  22221. this._appendParticleVertex(offset++, particle, 1, 0);
  22222. this._appendParticleVertex(offset++, particle, 1, 1);
  22223. this._appendParticleVertex(offset++, particle, 0, 1);
  22224. }
  22225. var engine = this._scene.getEngine();
  22226. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22227. };
  22228. ParticleSystem.prototype.render = function () {
  22229. var effect = this._getEffect();
  22230. // Check
  22231. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22232. return 0;
  22233. var engine = this._scene.getEngine();
  22234. // Render
  22235. engine.enableEffect(effect);
  22236. engine.setState(false);
  22237. var viewMatrix = this._scene.getViewMatrix();
  22238. effect.setTexture("diffuseSampler", this.particleTexture);
  22239. effect.setMatrix("view", viewMatrix);
  22240. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22241. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22242. if (this._scene.clipPlane) {
  22243. var clipPlane = this._scene.clipPlane;
  22244. var invView = viewMatrix.clone();
  22245. invView.invert();
  22246. effect.setMatrix("invView", invView);
  22247. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22248. }
  22249. // VBOs
  22250. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22251. // Draw order
  22252. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22253. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22254. }
  22255. else {
  22256. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22257. }
  22258. if (this.forceDepthWrite) {
  22259. engine.setDepthWrite(true);
  22260. }
  22261. engine.draw(true, 0, this.particles.length * 6);
  22262. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22263. return this.particles.length;
  22264. };
  22265. ParticleSystem.prototype.dispose = function () {
  22266. if (this._vertexBuffer) {
  22267. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22268. this._vertexBuffer = null;
  22269. }
  22270. if (this._indexBuffer) {
  22271. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22272. this._indexBuffer = null;
  22273. }
  22274. if (this.particleTexture) {
  22275. this.particleTexture.dispose();
  22276. this.particleTexture = null;
  22277. }
  22278. // Remove from scene
  22279. var index = this._scene.particleSystems.indexOf(this);
  22280. this._scene.particleSystems.splice(index, 1);
  22281. // Callback
  22282. if (this.onDispose) {
  22283. this.onDispose();
  22284. }
  22285. };
  22286. // Clone
  22287. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22288. var result = new ParticleSystem(name, this._capacity, this._scene);
  22289. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22290. if (newEmitter === undefined) {
  22291. newEmitter = this.emitter;
  22292. }
  22293. result.emitter = newEmitter;
  22294. if (this.particleTexture) {
  22295. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22296. }
  22297. result.start();
  22298. return result;
  22299. };
  22300. // Statics
  22301. ParticleSystem.BLENDMODE_ONEONE = 0;
  22302. ParticleSystem.BLENDMODE_STANDARD = 1;
  22303. return ParticleSystem;
  22304. })();
  22305. BABYLON.ParticleSystem = ParticleSystem;
  22306. })(BABYLON || (BABYLON = {}));
  22307. var BABYLON;
  22308. (function (BABYLON) {
  22309. var Animation = (function () {
  22310. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  22311. this.name = name;
  22312. this.targetProperty = targetProperty;
  22313. this.framePerSecond = framePerSecond;
  22314. this.dataType = dataType;
  22315. this.loopMode = loopMode;
  22316. this._offsetsCache = {};
  22317. this._highLimitsCache = {};
  22318. this._stopped = false;
  22319. this.allowMatricesInterpolation = false;
  22320. this.targetPropertyPath = targetProperty.split(".");
  22321. this.dataType = dataType;
  22322. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22323. }
  22324. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22325. var dataType = undefined;
  22326. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22327. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22328. }
  22329. else if (from instanceof BABYLON.Quaternion) {
  22330. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22331. }
  22332. else if (from instanceof BABYLON.Vector3) {
  22333. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22334. }
  22335. else if (from instanceof BABYLON.Vector2) {
  22336. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22337. }
  22338. else if (from instanceof BABYLON.Color3) {
  22339. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22340. }
  22341. if (dataType == undefined) {
  22342. return null;
  22343. }
  22344. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22345. var keys = [];
  22346. keys.push({ frame: 0, value: from });
  22347. keys.push({ frame: totalFrame, value: to });
  22348. animation.setKeys(keys);
  22349. if (easingFunction !== undefined) {
  22350. animation.setEasingFunction(easingFunction);
  22351. }
  22352. mesh.animations.push(animation);
  22353. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22354. };
  22355. // Methods
  22356. Animation.prototype.reset = function () {
  22357. this._offsetsCache = {};
  22358. this._highLimitsCache = {};
  22359. this.currentFrame = 0;
  22360. };
  22361. Animation.prototype.isStopped = function () {
  22362. return this._stopped;
  22363. };
  22364. Animation.prototype.getKeys = function () {
  22365. return this._keys;
  22366. };
  22367. Animation.prototype.getEasingFunction = function () {
  22368. return this._easingFunction;
  22369. };
  22370. Animation.prototype.setEasingFunction = function (easingFunction) {
  22371. this._easingFunction = easingFunction;
  22372. };
  22373. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22374. return startValue + (endValue - startValue) * gradient;
  22375. };
  22376. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22377. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22378. };
  22379. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22380. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22381. };
  22382. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22383. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22384. };
  22385. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22386. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22387. };
  22388. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22389. var startScale = new BABYLON.Vector3(0, 0, 0);
  22390. var startRotation = new BABYLON.Quaternion();
  22391. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  22392. startValue.decompose(startScale, startRotation, startTranslation);
  22393. var endScale = new BABYLON.Vector3(0, 0, 0);
  22394. var endRotation = new BABYLON.Quaternion();
  22395. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  22396. endValue.decompose(endScale, endRotation, endTranslation);
  22397. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  22398. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  22399. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  22400. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  22401. return result;
  22402. };
  22403. Animation.prototype.clone = function () {
  22404. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22405. if (this._keys) {
  22406. clone.setKeys(this._keys);
  22407. }
  22408. return clone;
  22409. };
  22410. Animation.prototype.setKeys = function (values) {
  22411. this._keys = values.slice(0);
  22412. this._offsetsCache = {};
  22413. this._highLimitsCache = {};
  22414. };
  22415. Animation.prototype._getKeyValue = function (value) {
  22416. if (typeof value === "function") {
  22417. return value();
  22418. }
  22419. return value;
  22420. };
  22421. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22422. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22423. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22424. }
  22425. this.currentFrame = currentFrame;
  22426. // Try to get a hash to find the right key
  22427. 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));
  22428. if (this._keys[startKey].frame >= currentFrame) {
  22429. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22430. startKey--;
  22431. }
  22432. }
  22433. for (var key = startKey; key < this._keys.length; key++) {
  22434. if (this._keys[key + 1].frame >= currentFrame) {
  22435. var startValue = this._getKeyValue(this._keys[key].value);
  22436. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22437. // gradient : percent of currentFrame between the frame inf and the frame sup
  22438. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22439. // check for easingFunction and correction of gradient
  22440. if (this._easingFunction != null) {
  22441. gradient = this._easingFunction.ease(gradient);
  22442. }
  22443. switch (this.dataType) {
  22444. // Float
  22445. case Animation.ANIMATIONTYPE_FLOAT:
  22446. switch (loopMode) {
  22447. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22448. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22449. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22450. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22451. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22452. }
  22453. break;
  22454. // Quaternion
  22455. case Animation.ANIMATIONTYPE_QUATERNION:
  22456. var quaternion = null;
  22457. switch (loopMode) {
  22458. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22459. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22460. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22461. break;
  22462. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22463. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22464. break;
  22465. }
  22466. return quaternion;
  22467. // Vector3
  22468. case Animation.ANIMATIONTYPE_VECTOR3:
  22469. switch (loopMode) {
  22470. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22471. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22472. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22473. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22474. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22475. }
  22476. // Vector2
  22477. case Animation.ANIMATIONTYPE_VECTOR2:
  22478. switch (loopMode) {
  22479. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22480. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22481. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22482. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22483. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22484. }
  22485. // Color3
  22486. case Animation.ANIMATIONTYPE_COLOR3:
  22487. switch (loopMode) {
  22488. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22489. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22490. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22491. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22492. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22493. }
  22494. // Matrix
  22495. case Animation.ANIMATIONTYPE_MATRIX:
  22496. switch (loopMode) {
  22497. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22498. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22499. if (this.allowMatricesInterpolation) {
  22500. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22501. }
  22502. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22503. return startValue;
  22504. }
  22505. default:
  22506. break;
  22507. }
  22508. break;
  22509. }
  22510. }
  22511. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22512. };
  22513. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22514. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22515. this._stopped = true;
  22516. return false;
  22517. }
  22518. var returnValue = true;
  22519. // Adding a start key at frame 0 if missing
  22520. if (this._keys[0].frame !== 0) {
  22521. var newKey = { frame: 0, value: this._keys[0].value };
  22522. this._keys.splice(0, 0, newKey);
  22523. }
  22524. // Check limits
  22525. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22526. from = this._keys[0].frame;
  22527. }
  22528. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22529. to = this._keys[this._keys.length - 1].frame;
  22530. }
  22531. // Compute ratio
  22532. var range = to - from;
  22533. var offsetValue;
  22534. // ratio represents the frame delta between from and to
  22535. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22536. var highLimitValue = 0;
  22537. if (ratio > range && !loop) {
  22538. returnValue = false;
  22539. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22540. }
  22541. else {
  22542. // Get max value if required
  22543. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22544. var keyOffset = to.toString() + from.toString();
  22545. if (!this._offsetsCache[keyOffset]) {
  22546. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22547. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22548. switch (this.dataType) {
  22549. // Float
  22550. case Animation.ANIMATIONTYPE_FLOAT:
  22551. this._offsetsCache[keyOffset] = toValue - fromValue;
  22552. break;
  22553. // Quaternion
  22554. case Animation.ANIMATIONTYPE_QUATERNION:
  22555. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22556. break;
  22557. // Vector3
  22558. case Animation.ANIMATIONTYPE_VECTOR3:
  22559. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22560. // Vector2
  22561. case Animation.ANIMATIONTYPE_VECTOR2:
  22562. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22563. // Color3
  22564. case Animation.ANIMATIONTYPE_COLOR3:
  22565. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22566. default:
  22567. break;
  22568. }
  22569. this._highLimitsCache[keyOffset] = toValue;
  22570. }
  22571. highLimitValue = this._highLimitsCache[keyOffset];
  22572. offsetValue = this._offsetsCache[keyOffset];
  22573. }
  22574. }
  22575. if (offsetValue === undefined) {
  22576. switch (this.dataType) {
  22577. // Float
  22578. case Animation.ANIMATIONTYPE_FLOAT:
  22579. offsetValue = 0;
  22580. break;
  22581. // Quaternion
  22582. case Animation.ANIMATIONTYPE_QUATERNION:
  22583. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22584. break;
  22585. // Vector3
  22586. case Animation.ANIMATIONTYPE_VECTOR3:
  22587. offsetValue = BABYLON.Vector3.Zero();
  22588. break;
  22589. // Vector2
  22590. case Animation.ANIMATIONTYPE_VECTOR2:
  22591. offsetValue = BABYLON.Vector2.Zero();
  22592. break;
  22593. // Color3
  22594. case Animation.ANIMATIONTYPE_COLOR3:
  22595. offsetValue = BABYLON.Color3.Black();
  22596. }
  22597. }
  22598. // Compute value
  22599. var repeatCount = (ratio / range) >> 0;
  22600. var currentFrame = returnValue ? from + ratio % range : to;
  22601. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22602. // Set value
  22603. if (this.targetPropertyPath.length > 1) {
  22604. var property = this._target[this.targetPropertyPath[0]];
  22605. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22606. property = property[this.targetPropertyPath[index]];
  22607. }
  22608. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22609. }
  22610. else {
  22611. this._target[this.targetPropertyPath[0]] = currentValue;
  22612. }
  22613. if (this._target.markAsDirty) {
  22614. this._target.markAsDirty(this.targetProperty);
  22615. }
  22616. if (!returnValue) {
  22617. this._stopped = true;
  22618. }
  22619. return returnValue;
  22620. };
  22621. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22622. get: function () {
  22623. return Animation._ANIMATIONTYPE_FLOAT;
  22624. },
  22625. enumerable: true,
  22626. configurable: true
  22627. });
  22628. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22629. get: function () {
  22630. return Animation._ANIMATIONTYPE_VECTOR3;
  22631. },
  22632. enumerable: true,
  22633. configurable: true
  22634. });
  22635. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22636. get: function () {
  22637. return Animation._ANIMATIONTYPE_VECTOR2;
  22638. },
  22639. enumerable: true,
  22640. configurable: true
  22641. });
  22642. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22643. get: function () {
  22644. return Animation._ANIMATIONTYPE_QUATERNION;
  22645. },
  22646. enumerable: true,
  22647. configurable: true
  22648. });
  22649. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22650. get: function () {
  22651. return Animation._ANIMATIONTYPE_MATRIX;
  22652. },
  22653. enumerable: true,
  22654. configurable: true
  22655. });
  22656. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22657. get: function () {
  22658. return Animation._ANIMATIONTYPE_COLOR3;
  22659. },
  22660. enumerable: true,
  22661. configurable: true
  22662. });
  22663. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22664. get: function () {
  22665. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22666. },
  22667. enumerable: true,
  22668. configurable: true
  22669. });
  22670. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22671. get: function () {
  22672. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22673. },
  22674. enumerable: true,
  22675. configurable: true
  22676. });
  22677. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22678. get: function () {
  22679. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22680. },
  22681. enumerable: true,
  22682. configurable: true
  22683. });
  22684. // Statics
  22685. Animation._ANIMATIONTYPE_FLOAT = 0;
  22686. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22687. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22688. Animation._ANIMATIONTYPE_MATRIX = 3;
  22689. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22690. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22691. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22692. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22693. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22694. return Animation;
  22695. })();
  22696. BABYLON.Animation = Animation;
  22697. })(BABYLON || (BABYLON = {}));
  22698. var BABYLON;
  22699. (function (BABYLON) {
  22700. var Animatable = (function () {
  22701. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22702. if (fromFrame === void 0) { fromFrame = 0; }
  22703. if (toFrame === void 0) { toFrame = 100; }
  22704. if (loopAnimation === void 0) { loopAnimation = false; }
  22705. if (speedRatio === void 0) { speedRatio = 1.0; }
  22706. this.target = target;
  22707. this.fromFrame = fromFrame;
  22708. this.toFrame = toFrame;
  22709. this.loopAnimation = loopAnimation;
  22710. this.speedRatio = speedRatio;
  22711. this.onAnimationEnd = onAnimationEnd;
  22712. this._animations = new Array();
  22713. this._paused = false;
  22714. this.animationStarted = false;
  22715. if (animations) {
  22716. this.appendAnimations(target, animations);
  22717. }
  22718. this._scene = scene;
  22719. scene._activeAnimatables.push(this);
  22720. }
  22721. // Methods
  22722. Animatable.prototype.appendAnimations = function (target, animations) {
  22723. for (var index = 0; index < animations.length; index++) {
  22724. var animation = animations[index];
  22725. animation._target = target;
  22726. this._animations.push(animation);
  22727. }
  22728. };
  22729. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22730. var animations = this._animations;
  22731. for (var index = 0; index < animations.length; index++) {
  22732. if (animations[index].targetProperty === property) {
  22733. return animations[index];
  22734. }
  22735. }
  22736. return null;
  22737. };
  22738. Animatable.prototype.reset = function () {
  22739. var animations = this._animations;
  22740. for (var index = 0; index < animations.length; index++) {
  22741. animations[index].reset();
  22742. }
  22743. this._localDelayOffset = null;
  22744. this._pausedDelay = null;
  22745. };
  22746. Animatable.prototype.pause = function () {
  22747. if (this._paused) {
  22748. return;
  22749. }
  22750. this._paused = true;
  22751. };
  22752. Animatable.prototype.restart = function () {
  22753. this._paused = false;
  22754. };
  22755. Animatable.prototype.stop = function () {
  22756. var index = this._scene._activeAnimatables.indexOf(this);
  22757. if (index > -1) {
  22758. this._scene._activeAnimatables.splice(index, 1);
  22759. }
  22760. if (this.onAnimationEnd) {
  22761. this.onAnimationEnd();
  22762. }
  22763. };
  22764. Animatable.prototype._animate = function (delay) {
  22765. if (this._paused) {
  22766. if (!this._pausedDelay) {
  22767. this._pausedDelay = delay;
  22768. }
  22769. return true;
  22770. }
  22771. if (!this._localDelayOffset) {
  22772. this._localDelayOffset = delay;
  22773. }
  22774. else if (this._pausedDelay) {
  22775. this._localDelayOffset += delay - this._pausedDelay;
  22776. this._pausedDelay = null;
  22777. }
  22778. // Animating
  22779. var running = false;
  22780. var animations = this._animations;
  22781. for (var index = 0; index < animations.length; index++) {
  22782. var animation = animations[index];
  22783. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22784. running = running || isRunning;
  22785. }
  22786. if (!running) {
  22787. // Remove from active animatables
  22788. index = this._scene._activeAnimatables.indexOf(this);
  22789. this._scene._activeAnimatables.splice(index, 1);
  22790. }
  22791. if (!running && this.onAnimationEnd) {
  22792. this.onAnimationEnd();
  22793. }
  22794. return running;
  22795. };
  22796. return Animatable;
  22797. })();
  22798. BABYLON.Animatable = Animatable;
  22799. })(BABYLON || (BABYLON = {}));
  22800. var BABYLON;
  22801. (function (BABYLON) {
  22802. var EasingFunction = (function () {
  22803. function EasingFunction() {
  22804. // Properties
  22805. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22806. }
  22807. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22808. get: function () {
  22809. return EasingFunction._EASINGMODE_EASEIN;
  22810. },
  22811. enumerable: true,
  22812. configurable: true
  22813. });
  22814. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22815. get: function () {
  22816. return EasingFunction._EASINGMODE_EASEOUT;
  22817. },
  22818. enumerable: true,
  22819. configurable: true
  22820. });
  22821. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22822. get: function () {
  22823. return EasingFunction._EASINGMODE_EASEINOUT;
  22824. },
  22825. enumerable: true,
  22826. configurable: true
  22827. });
  22828. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22829. var n = Math.min(Math.max(easingMode, 0), 2);
  22830. this._easingMode = n;
  22831. };
  22832. EasingFunction.prototype.getEasingMode = function () {
  22833. return this._easingMode;
  22834. };
  22835. EasingFunction.prototype.easeInCore = function (gradient) {
  22836. throw new Error('You must implement this method');
  22837. };
  22838. EasingFunction.prototype.ease = function (gradient) {
  22839. switch (this._easingMode) {
  22840. case EasingFunction.EASINGMODE_EASEIN:
  22841. return this.easeInCore(gradient);
  22842. case EasingFunction.EASINGMODE_EASEOUT:
  22843. return (1 - this.easeInCore(1 - gradient));
  22844. }
  22845. if (gradient >= 0.5) {
  22846. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22847. }
  22848. return (this.easeInCore(gradient * 2) * 0.5);
  22849. };
  22850. //Statics
  22851. EasingFunction._EASINGMODE_EASEIN = 0;
  22852. EasingFunction._EASINGMODE_EASEOUT = 1;
  22853. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22854. return EasingFunction;
  22855. })();
  22856. BABYLON.EasingFunction = EasingFunction;
  22857. var CircleEase = (function (_super) {
  22858. __extends(CircleEase, _super);
  22859. function CircleEase() {
  22860. _super.apply(this, arguments);
  22861. }
  22862. CircleEase.prototype.easeInCore = function (gradient) {
  22863. gradient = Math.max(0, Math.min(1, gradient));
  22864. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22865. };
  22866. return CircleEase;
  22867. })(EasingFunction);
  22868. BABYLON.CircleEase = CircleEase;
  22869. var BackEase = (function (_super) {
  22870. __extends(BackEase, _super);
  22871. function BackEase(amplitude) {
  22872. if (amplitude === void 0) { amplitude = 1; }
  22873. _super.call(this);
  22874. this.amplitude = amplitude;
  22875. }
  22876. BackEase.prototype.easeInCore = function (gradient) {
  22877. var num = Math.max(0, this.amplitude);
  22878. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22879. };
  22880. return BackEase;
  22881. })(EasingFunction);
  22882. BABYLON.BackEase = BackEase;
  22883. var BounceEase = (function (_super) {
  22884. __extends(BounceEase, _super);
  22885. function BounceEase(bounces, bounciness) {
  22886. if (bounces === void 0) { bounces = 3; }
  22887. if (bounciness === void 0) { bounciness = 2; }
  22888. _super.call(this);
  22889. this.bounces = bounces;
  22890. this.bounciness = bounciness;
  22891. }
  22892. BounceEase.prototype.easeInCore = function (gradient) {
  22893. var y = Math.max(0.0, this.bounces);
  22894. var bounciness = this.bounciness;
  22895. if (bounciness <= 1.0) {
  22896. bounciness = 1.001;
  22897. }
  22898. var num9 = Math.pow(bounciness, y);
  22899. var num5 = 1.0 - bounciness;
  22900. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22901. var num15 = gradient * num4;
  22902. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22903. var num3 = Math.floor(num65);
  22904. var num13 = num3 + 1.0;
  22905. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22906. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22907. var num7 = (num8 + num12) * 0.5;
  22908. var num6 = gradient - num7;
  22909. var num2 = num7 - num8;
  22910. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22911. };
  22912. return BounceEase;
  22913. })(EasingFunction);
  22914. BABYLON.BounceEase = BounceEase;
  22915. var CubicEase = (function (_super) {
  22916. __extends(CubicEase, _super);
  22917. function CubicEase() {
  22918. _super.apply(this, arguments);
  22919. }
  22920. CubicEase.prototype.easeInCore = function (gradient) {
  22921. return (gradient * gradient * gradient);
  22922. };
  22923. return CubicEase;
  22924. })(EasingFunction);
  22925. BABYLON.CubicEase = CubicEase;
  22926. var ElasticEase = (function (_super) {
  22927. __extends(ElasticEase, _super);
  22928. function ElasticEase(oscillations, springiness) {
  22929. if (oscillations === void 0) { oscillations = 3; }
  22930. if (springiness === void 0) { springiness = 3; }
  22931. _super.call(this);
  22932. this.oscillations = oscillations;
  22933. this.springiness = springiness;
  22934. }
  22935. ElasticEase.prototype.easeInCore = function (gradient) {
  22936. var num2;
  22937. var num3 = Math.max(0.0, this.oscillations);
  22938. var num = Math.max(0.0, this.springiness);
  22939. if (num == 0) {
  22940. num2 = gradient;
  22941. }
  22942. else {
  22943. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22944. }
  22945. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22946. };
  22947. return ElasticEase;
  22948. })(EasingFunction);
  22949. BABYLON.ElasticEase = ElasticEase;
  22950. var ExponentialEase = (function (_super) {
  22951. __extends(ExponentialEase, _super);
  22952. function ExponentialEase(exponent) {
  22953. if (exponent === void 0) { exponent = 2; }
  22954. _super.call(this);
  22955. this.exponent = exponent;
  22956. }
  22957. ExponentialEase.prototype.easeInCore = function (gradient) {
  22958. if (this.exponent <= 0) {
  22959. return gradient;
  22960. }
  22961. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22962. };
  22963. return ExponentialEase;
  22964. })(EasingFunction);
  22965. BABYLON.ExponentialEase = ExponentialEase;
  22966. var PowerEase = (function (_super) {
  22967. __extends(PowerEase, _super);
  22968. function PowerEase(power) {
  22969. if (power === void 0) { power = 2; }
  22970. _super.call(this);
  22971. this.power = power;
  22972. }
  22973. PowerEase.prototype.easeInCore = function (gradient) {
  22974. var y = Math.max(0.0, this.power);
  22975. return Math.pow(gradient, y);
  22976. };
  22977. return PowerEase;
  22978. })(EasingFunction);
  22979. BABYLON.PowerEase = PowerEase;
  22980. var QuadraticEase = (function (_super) {
  22981. __extends(QuadraticEase, _super);
  22982. function QuadraticEase() {
  22983. _super.apply(this, arguments);
  22984. }
  22985. QuadraticEase.prototype.easeInCore = function (gradient) {
  22986. return (gradient * gradient);
  22987. };
  22988. return QuadraticEase;
  22989. })(EasingFunction);
  22990. BABYLON.QuadraticEase = QuadraticEase;
  22991. var QuarticEase = (function (_super) {
  22992. __extends(QuarticEase, _super);
  22993. function QuarticEase() {
  22994. _super.apply(this, arguments);
  22995. }
  22996. QuarticEase.prototype.easeInCore = function (gradient) {
  22997. return (gradient * gradient * gradient * gradient);
  22998. };
  22999. return QuarticEase;
  23000. })(EasingFunction);
  23001. BABYLON.QuarticEase = QuarticEase;
  23002. var QuinticEase = (function (_super) {
  23003. __extends(QuinticEase, _super);
  23004. function QuinticEase() {
  23005. _super.apply(this, arguments);
  23006. }
  23007. QuinticEase.prototype.easeInCore = function (gradient) {
  23008. return (gradient * gradient * gradient * gradient * gradient);
  23009. };
  23010. return QuinticEase;
  23011. })(EasingFunction);
  23012. BABYLON.QuinticEase = QuinticEase;
  23013. var SineEase = (function (_super) {
  23014. __extends(SineEase, _super);
  23015. function SineEase() {
  23016. _super.apply(this, arguments);
  23017. }
  23018. SineEase.prototype.easeInCore = function (gradient) {
  23019. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  23020. };
  23021. return SineEase;
  23022. })(EasingFunction);
  23023. BABYLON.SineEase = SineEase;
  23024. var BezierCurveEase = (function (_super) {
  23025. __extends(BezierCurveEase, _super);
  23026. function BezierCurveEase(x1, y1, x2, y2) {
  23027. if (x1 === void 0) { x1 = 0; }
  23028. if (y1 === void 0) { y1 = 0; }
  23029. if (x2 === void 0) { x2 = 1; }
  23030. if (y2 === void 0) { y2 = 1; }
  23031. _super.call(this);
  23032. this.x1 = x1;
  23033. this.y1 = y1;
  23034. this.x2 = x2;
  23035. this.y2 = y2;
  23036. }
  23037. BezierCurveEase.prototype.easeInCore = function (gradient) {
  23038. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  23039. };
  23040. return BezierCurveEase;
  23041. })(EasingFunction);
  23042. BABYLON.BezierCurveEase = BezierCurveEase;
  23043. })(BABYLON || (BABYLON = {}));
  23044. var BABYLON;
  23045. (function (BABYLON) {
  23046. var Octree = (function () {
  23047. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  23048. if (maxDepth === void 0) { maxDepth = 2; }
  23049. this.maxDepth = maxDepth;
  23050. this.dynamicContent = new Array();
  23051. this._maxBlockCapacity = maxBlockCapacity || 64;
  23052. this._selectionContent = new BABYLON.SmartArray(1024);
  23053. this._creationFunc = creationFunc;
  23054. }
  23055. // Methods
  23056. Octree.prototype.update = function (worldMin, worldMax, entries) {
  23057. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  23058. };
  23059. Octree.prototype.addMesh = function (entry) {
  23060. for (var index = 0; index < this.blocks.length; index++) {
  23061. var block = this.blocks[index];
  23062. block.addEntry(entry);
  23063. }
  23064. };
  23065. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  23066. this._selectionContent.reset();
  23067. for (var index = 0; index < this.blocks.length; index++) {
  23068. var block = this.blocks[index];
  23069. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  23070. }
  23071. if (allowDuplicate) {
  23072. this._selectionContent.concat(this.dynamicContent);
  23073. }
  23074. else {
  23075. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  23076. }
  23077. return this._selectionContent;
  23078. };
  23079. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  23080. this._selectionContent.reset();
  23081. for (var index = 0; index < this.blocks.length; index++) {
  23082. var block = this.blocks[index];
  23083. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  23084. }
  23085. if (allowDuplicate) {
  23086. this._selectionContent.concat(this.dynamicContent);
  23087. }
  23088. else {
  23089. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  23090. }
  23091. return this._selectionContent;
  23092. };
  23093. Octree.prototype.intersectsRay = function (ray) {
  23094. this._selectionContent.reset();
  23095. for (var index = 0; index < this.blocks.length; index++) {
  23096. var block = this.blocks[index];
  23097. block.intersectsRay(ray, this._selectionContent);
  23098. }
  23099. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  23100. return this._selectionContent;
  23101. };
  23102. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  23103. target.blocks = new Array();
  23104. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  23105. // Segmenting space
  23106. for (var x = 0; x < 2; x++) {
  23107. for (var y = 0; y < 2; y++) {
  23108. for (var z = 0; z < 2; z++) {
  23109. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  23110. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  23111. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  23112. block.addEntries(entries);
  23113. target.blocks.push(block);
  23114. }
  23115. }
  23116. }
  23117. };
  23118. Octree.CreationFuncForMeshes = function (entry, block) {
  23119. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  23120. block.entries.push(entry);
  23121. }
  23122. };
  23123. Octree.CreationFuncForSubMeshes = function (entry, block) {
  23124. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  23125. block.entries.push(entry);
  23126. }
  23127. };
  23128. return Octree;
  23129. })();
  23130. BABYLON.Octree = Octree;
  23131. })(BABYLON || (BABYLON = {}));
  23132. var BABYLON;
  23133. (function (BABYLON) {
  23134. var OctreeBlock = (function () {
  23135. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  23136. this.entries = new Array();
  23137. this._boundingVectors = new Array();
  23138. this._capacity = capacity;
  23139. this._depth = depth;
  23140. this._maxDepth = maxDepth;
  23141. this._creationFunc = creationFunc;
  23142. this._minPoint = minPoint;
  23143. this._maxPoint = maxPoint;
  23144. this._boundingVectors.push(minPoint.clone());
  23145. this._boundingVectors.push(maxPoint.clone());
  23146. this._boundingVectors.push(minPoint.clone());
  23147. this._boundingVectors[2].x = maxPoint.x;
  23148. this._boundingVectors.push(minPoint.clone());
  23149. this._boundingVectors[3].y = maxPoint.y;
  23150. this._boundingVectors.push(minPoint.clone());
  23151. this._boundingVectors[4].z = maxPoint.z;
  23152. this._boundingVectors.push(maxPoint.clone());
  23153. this._boundingVectors[5].z = minPoint.z;
  23154. this._boundingVectors.push(maxPoint.clone());
  23155. this._boundingVectors[6].x = minPoint.x;
  23156. this._boundingVectors.push(maxPoint.clone());
  23157. this._boundingVectors[7].y = minPoint.y;
  23158. }
  23159. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  23160. // Property
  23161. get: function () {
  23162. return this._capacity;
  23163. },
  23164. enumerable: true,
  23165. configurable: true
  23166. });
  23167. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  23168. get: function () {
  23169. return this._minPoint;
  23170. },
  23171. enumerable: true,
  23172. configurable: true
  23173. });
  23174. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  23175. get: function () {
  23176. return this._maxPoint;
  23177. },
  23178. enumerable: true,
  23179. configurable: true
  23180. });
  23181. // Methods
  23182. OctreeBlock.prototype.addEntry = function (entry) {
  23183. if (this.blocks) {
  23184. for (var index = 0; index < this.blocks.length; index++) {
  23185. var block = this.blocks[index];
  23186. block.addEntry(entry);
  23187. }
  23188. return;
  23189. }
  23190. this._creationFunc(entry, this);
  23191. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  23192. this.createInnerBlocks();
  23193. }
  23194. };
  23195. OctreeBlock.prototype.addEntries = function (entries) {
  23196. for (var index = 0; index < entries.length; index++) {
  23197. var mesh = entries[index];
  23198. this.addEntry(mesh);
  23199. }
  23200. };
  23201. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  23202. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  23203. if (this.blocks) {
  23204. for (var index = 0; index < this.blocks.length; index++) {
  23205. var block = this.blocks[index];
  23206. block.select(frustumPlanes, selection, allowDuplicate);
  23207. }
  23208. return;
  23209. }
  23210. if (allowDuplicate) {
  23211. selection.concat(this.entries);
  23212. }
  23213. else {
  23214. selection.concatWithNoDuplicate(this.entries);
  23215. }
  23216. }
  23217. };
  23218. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  23219. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  23220. if (this.blocks) {
  23221. for (var index = 0; index < this.blocks.length; index++) {
  23222. var block = this.blocks[index];
  23223. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  23224. }
  23225. return;
  23226. }
  23227. if (allowDuplicate) {
  23228. selection.concat(this.entries);
  23229. }
  23230. else {
  23231. selection.concatWithNoDuplicate(this.entries);
  23232. }
  23233. }
  23234. };
  23235. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  23236. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  23237. if (this.blocks) {
  23238. for (var index = 0; index < this.blocks.length; index++) {
  23239. var block = this.blocks[index];
  23240. block.intersectsRay(ray, selection);
  23241. }
  23242. return;
  23243. }
  23244. selection.concatWithNoDuplicate(this.entries);
  23245. }
  23246. };
  23247. OctreeBlock.prototype.createInnerBlocks = function () {
  23248. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  23249. };
  23250. return OctreeBlock;
  23251. })();
  23252. BABYLON.OctreeBlock = OctreeBlock;
  23253. })(BABYLON || (BABYLON = {}));
  23254. var BABYLON;
  23255. (function (BABYLON) {
  23256. var Bone = (function (_super) {
  23257. __extends(Bone, _super);
  23258. function Bone(name, skeleton, parentBone, matrix) {
  23259. _super.call(this, name, skeleton.getScene());
  23260. this.name = name;
  23261. this.children = new Array();
  23262. this.animations = new Array();
  23263. this._worldTransform = new BABYLON.Matrix();
  23264. this._absoluteTransform = new BABYLON.Matrix();
  23265. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23266. this._skeleton = skeleton;
  23267. this._matrix = matrix;
  23268. this._baseMatrix = matrix;
  23269. skeleton.bones.push(this);
  23270. if (parentBone) {
  23271. this._parent = parentBone;
  23272. parentBone.children.push(this);
  23273. }
  23274. else {
  23275. this._parent = null;
  23276. }
  23277. this._updateDifferenceMatrix();
  23278. }
  23279. // Members
  23280. Bone.prototype.getParent = function () {
  23281. return this._parent;
  23282. };
  23283. Bone.prototype.getLocalMatrix = function () {
  23284. return this._matrix;
  23285. };
  23286. Bone.prototype.getBaseMatrix = function () {
  23287. return this._baseMatrix;
  23288. };
  23289. Bone.prototype.getWorldMatrix = function () {
  23290. return this._worldTransform;
  23291. };
  23292. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23293. return this._invertedAbsoluteTransform;
  23294. };
  23295. Bone.prototype.getAbsoluteMatrix = function () {
  23296. var matrix = this._matrix.clone();
  23297. var parent = this._parent;
  23298. while (parent) {
  23299. matrix = matrix.multiply(parent.getLocalMatrix());
  23300. parent = parent.getParent();
  23301. }
  23302. return matrix;
  23303. };
  23304. // Methods
  23305. Bone.prototype.updateMatrix = function (matrix) {
  23306. this._matrix = matrix;
  23307. this._skeleton._markAsDirty();
  23308. this._updateDifferenceMatrix();
  23309. };
  23310. Bone.prototype._updateDifferenceMatrix = function () {
  23311. if (this._parent) {
  23312. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23313. }
  23314. else {
  23315. this._absoluteTransform.copyFrom(this._matrix);
  23316. }
  23317. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23318. for (var index = 0; index < this.children.length; index++) {
  23319. this.children[index]._updateDifferenceMatrix();
  23320. }
  23321. };
  23322. Bone.prototype.markAsDirty = function () {
  23323. this._currentRenderId++;
  23324. this._skeleton._markAsDirty();
  23325. };
  23326. return Bone;
  23327. })(BABYLON.Node);
  23328. BABYLON.Bone = Bone;
  23329. })(BABYLON || (BABYLON = {}));
  23330. var BABYLON;
  23331. (function (BABYLON) {
  23332. var Skeleton = (function () {
  23333. function Skeleton(name, id, scene) {
  23334. this.name = name;
  23335. this.id = id;
  23336. this.bones = new Array();
  23337. this._isDirty = true;
  23338. this._identity = BABYLON.Matrix.Identity();
  23339. this.bones = [];
  23340. this._scene = scene;
  23341. scene.skeletons.push(this);
  23342. this.prepare();
  23343. //make sure it will recalculate the matrix next time prepare is called.
  23344. this._isDirty = true;
  23345. }
  23346. // Members
  23347. Skeleton.prototype.getTransformMatrices = function () {
  23348. return this._transformMatrices;
  23349. };
  23350. Skeleton.prototype.getScene = function () {
  23351. return this._scene;
  23352. };
  23353. // Methods
  23354. Skeleton.prototype._markAsDirty = function () {
  23355. this._isDirty = true;
  23356. };
  23357. Skeleton.prototype.prepare = function () {
  23358. if (!this._isDirty) {
  23359. return;
  23360. }
  23361. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23362. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23363. }
  23364. for (var index = 0; index < this.bones.length; index++) {
  23365. var bone = this.bones[index];
  23366. var parentBone = bone.getParent();
  23367. if (parentBone) {
  23368. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23369. }
  23370. else {
  23371. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23372. }
  23373. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  23374. }
  23375. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  23376. this._isDirty = false;
  23377. this._scene._activeBones += this.bones.length;
  23378. };
  23379. Skeleton.prototype.getAnimatables = function () {
  23380. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23381. this._animatables = [];
  23382. for (var index = 0; index < this.bones.length; index++) {
  23383. this._animatables.push(this.bones[index]);
  23384. }
  23385. }
  23386. return this._animatables;
  23387. };
  23388. Skeleton.prototype.clone = function (name, id) {
  23389. var result = new Skeleton(name, id || name, this._scene);
  23390. for (var index = 0; index < this.bones.length; index++) {
  23391. var source = this.bones[index];
  23392. var parentBone = null;
  23393. if (source.getParent()) {
  23394. var parentIndex = this.bones.indexOf(source.getParent());
  23395. parentBone = result.bones[parentIndex];
  23396. }
  23397. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  23398. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23399. }
  23400. return result;
  23401. };
  23402. return Skeleton;
  23403. })();
  23404. BABYLON.Skeleton = Skeleton;
  23405. })(BABYLON || (BABYLON = {}));
  23406. var BABYLON;
  23407. (function (BABYLON) {
  23408. var PostProcess = (function () {
  23409. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23410. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23411. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23412. this.name = name;
  23413. this.width = -1;
  23414. this.height = -1;
  23415. this._reusable = false;
  23416. this._textures = new BABYLON.SmartArray(2);
  23417. this._currentRenderTextureInd = 0;
  23418. if (camera != null) {
  23419. this._camera = camera;
  23420. this._scene = camera.getScene();
  23421. camera.attachPostProcess(this);
  23422. this._engine = this._scene.getEngine();
  23423. }
  23424. else {
  23425. this._engine = engine;
  23426. }
  23427. this._renderRatio = ratio;
  23428. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23429. this._reusable = reusable || false;
  23430. this._textureType = textureType;
  23431. samplers = samplers || [];
  23432. samplers.push("textureSampler");
  23433. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  23434. }
  23435. PostProcess.prototype.isReusable = function () {
  23436. return this._reusable;
  23437. };
  23438. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23439. camera = camera || this._camera;
  23440. var scene = camera.getScene();
  23441. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23442. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23443. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23444. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23445. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23446. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23447. if (this._textures.length > 0) {
  23448. for (var i = 0; i < this._textures.length; i++) {
  23449. this._engine._releaseTexture(this._textures.data[i]);
  23450. }
  23451. this._textures.reset();
  23452. }
  23453. this.width = desiredWidth;
  23454. this.height = desiredHeight;
  23455. 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, type: this._textureType }));
  23456. if (this._reusable) {
  23457. 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, type: this._textureType }));
  23458. }
  23459. if (this.onSizeChanged) {
  23460. this.onSizeChanged();
  23461. }
  23462. }
  23463. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23464. if (this.onActivate) {
  23465. this.onActivate(camera);
  23466. }
  23467. // Clear
  23468. if (this.clearColor) {
  23469. this._engine.clear(this.clearColor, true, true);
  23470. }
  23471. else {
  23472. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23473. }
  23474. if (this._reusable) {
  23475. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23476. }
  23477. };
  23478. PostProcess.prototype.apply = function () {
  23479. // Check
  23480. if (!this._effect.isReady())
  23481. return null;
  23482. // States
  23483. this._engine.enableEffect(this._effect);
  23484. this._engine.setState(false);
  23485. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23486. this._engine.setDepthBuffer(false);
  23487. this._engine.setDepthWrite(false);
  23488. // Texture
  23489. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23490. // Parameters
  23491. if (this.onApply) {
  23492. this.onApply(this._effect);
  23493. }
  23494. return this._effect;
  23495. };
  23496. PostProcess.prototype.dispose = function (camera) {
  23497. camera = camera || this._camera;
  23498. if (this._textures.length > 0) {
  23499. for (var i = 0; i < this._textures.length; i++) {
  23500. this._engine._releaseTexture(this._textures.data[i]);
  23501. }
  23502. this._textures.reset();
  23503. }
  23504. if (!camera) {
  23505. return;
  23506. }
  23507. camera.detachPostProcess(this);
  23508. var index = camera._postProcesses.indexOf(this);
  23509. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23510. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23511. }
  23512. };
  23513. return PostProcess;
  23514. })();
  23515. BABYLON.PostProcess = PostProcess;
  23516. })(BABYLON || (BABYLON = {}));
  23517. var BABYLON;
  23518. (function (BABYLON) {
  23519. var PostProcessManager = (function () {
  23520. function PostProcessManager(scene) {
  23521. this._vertexDeclaration = [2];
  23522. this._vertexStrideSize = 2 * 4;
  23523. this._scene = scene;
  23524. }
  23525. PostProcessManager.prototype._prepareBuffers = function () {
  23526. if (this._vertexBuffer) {
  23527. return;
  23528. }
  23529. // VBO
  23530. var vertices = [];
  23531. vertices.push(1, 1);
  23532. vertices.push(-1, 1);
  23533. vertices.push(-1, -1);
  23534. vertices.push(1, -1);
  23535. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23536. // Indices
  23537. var indices = [];
  23538. indices.push(0);
  23539. indices.push(1);
  23540. indices.push(2);
  23541. indices.push(0);
  23542. indices.push(2);
  23543. indices.push(3);
  23544. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23545. };
  23546. // Methods
  23547. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23548. var postProcesses = this._scene.activeCamera._postProcesses;
  23549. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23550. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23551. return false;
  23552. }
  23553. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23554. return true;
  23555. };
  23556. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23557. var engine = this._scene.getEngine();
  23558. for (var index = 0; index < postProcesses.length; index++) {
  23559. if (index < postProcesses.length - 1) {
  23560. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23561. }
  23562. else {
  23563. if (targetTexture) {
  23564. engine.bindFramebuffer(targetTexture);
  23565. }
  23566. else {
  23567. engine.restoreDefaultFramebuffer();
  23568. }
  23569. }
  23570. var pp = postProcesses[index];
  23571. var effect = pp.apply();
  23572. if (effect) {
  23573. if (pp.onBeforeRender) {
  23574. pp.onBeforeRender(effect);
  23575. }
  23576. // VBOs
  23577. this._prepareBuffers();
  23578. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23579. // Draw order
  23580. engine.draw(true, 0, 6);
  23581. if (pp.onAfterRender) {
  23582. pp.onAfterRender(effect);
  23583. }
  23584. }
  23585. }
  23586. // Restore depth buffer
  23587. engine.setDepthBuffer(true);
  23588. engine.setDepthWrite(true);
  23589. };
  23590. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23591. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23592. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23593. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23594. return;
  23595. }
  23596. var engine = this._scene.getEngine();
  23597. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23598. if (index < postProcessesTakenIndices.length - 1) {
  23599. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  23600. }
  23601. else {
  23602. if (targetTexture) {
  23603. engine.bindFramebuffer(targetTexture, faceIndex);
  23604. }
  23605. else {
  23606. engine.restoreDefaultFramebuffer();
  23607. }
  23608. }
  23609. if (doNotPresent) {
  23610. break;
  23611. }
  23612. var pp = postProcesses[postProcessesTakenIndices[index]];
  23613. var effect = pp.apply();
  23614. if (effect) {
  23615. if (pp.onBeforeRender) {
  23616. pp.onBeforeRender(effect);
  23617. }
  23618. // VBOs
  23619. this._prepareBuffers();
  23620. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23621. // Draw order
  23622. engine.draw(true, 0, 6);
  23623. if (pp.onAfterRender) {
  23624. pp.onAfterRender(effect);
  23625. }
  23626. }
  23627. }
  23628. // Restore depth buffer
  23629. engine.setDepthBuffer(true);
  23630. engine.setDepthWrite(true);
  23631. };
  23632. PostProcessManager.prototype.dispose = function () {
  23633. if (this._vertexBuffer) {
  23634. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23635. this._vertexBuffer = null;
  23636. }
  23637. if (this._indexBuffer) {
  23638. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23639. this._indexBuffer = null;
  23640. }
  23641. };
  23642. return PostProcessManager;
  23643. })();
  23644. BABYLON.PostProcessManager = PostProcessManager;
  23645. })(BABYLON || (BABYLON = {}));
  23646. var BABYLON;
  23647. (function (BABYLON) {
  23648. var PassPostProcess = (function (_super) {
  23649. __extends(PassPostProcess, _super);
  23650. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23651. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23652. }
  23653. return PassPostProcess;
  23654. })(BABYLON.PostProcess);
  23655. BABYLON.PassPostProcess = PassPostProcess;
  23656. })(BABYLON || (BABYLON = {}));
  23657. var BABYLON;
  23658. (function (BABYLON) {
  23659. var BlurPostProcess = (function (_super) {
  23660. __extends(BlurPostProcess, _super);
  23661. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  23662. var _this = this;
  23663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  23664. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  23665. this.direction = direction;
  23666. this.blurWidth = blurWidth;
  23667. this.onApply = function (effect) {
  23668. effect.setFloat2("screenSize", _this.width, _this.height);
  23669. effect.setVector2("direction", _this.direction);
  23670. effect.setFloat("blurWidth", _this.blurWidth);
  23671. };
  23672. }
  23673. return BlurPostProcess;
  23674. })(BABYLON.PostProcess);
  23675. BABYLON.BlurPostProcess = BlurPostProcess;
  23676. })(BABYLON || (BABYLON = {}));
  23677. var BABYLON;
  23678. (function (BABYLON) {
  23679. var RefractionPostProcess = (function (_super) {
  23680. __extends(RefractionPostProcess, _super);
  23681. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  23682. var _this = this;
  23683. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  23684. this.color = color;
  23685. this.depth = depth;
  23686. this.colorLevel = colorLevel;
  23687. this.onActivate = function (cam) {
  23688. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  23689. };
  23690. this.onApply = function (effect) {
  23691. effect.setColor3("baseColor", _this.color);
  23692. effect.setFloat("depth", _this.depth);
  23693. effect.setFloat("colorLevel", _this.colorLevel);
  23694. effect.setTexture("refractionSampler", _this._refRexture);
  23695. };
  23696. }
  23697. // Methods
  23698. RefractionPostProcess.prototype.dispose = function (camera) {
  23699. if (this._refRexture) {
  23700. this._refRexture.dispose();
  23701. }
  23702. _super.prototype.dispose.call(this, camera);
  23703. };
  23704. return RefractionPostProcess;
  23705. })(BABYLON.PostProcess);
  23706. BABYLON.RefractionPostProcess = RefractionPostProcess;
  23707. })(BABYLON || (BABYLON = {}));
  23708. var BABYLON;
  23709. (function (BABYLON) {
  23710. var BlackAndWhitePostProcess = (function (_super) {
  23711. __extends(BlackAndWhitePostProcess, _super);
  23712. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23713. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  23714. }
  23715. return BlackAndWhitePostProcess;
  23716. })(BABYLON.PostProcess);
  23717. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  23718. })(BABYLON || (BABYLON = {}));
  23719. var BABYLON;
  23720. (function (BABYLON) {
  23721. var ConvolutionPostProcess = (function (_super) {
  23722. __extends(ConvolutionPostProcess, _super);
  23723. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  23724. var _this = this;
  23725. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  23726. this.kernel = kernel;
  23727. this.onApply = function (effect) {
  23728. effect.setFloat2("screenSize", _this.width, _this.height);
  23729. effect.setArray("kernel", _this.kernel);
  23730. };
  23731. }
  23732. // Statics
  23733. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  23734. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  23735. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  23736. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  23737. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  23738. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  23739. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  23740. return ConvolutionPostProcess;
  23741. })(BABYLON.PostProcess);
  23742. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  23743. })(BABYLON || (BABYLON = {}));
  23744. var BABYLON;
  23745. (function (BABYLON) {
  23746. var FilterPostProcess = (function (_super) {
  23747. __extends(FilterPostProcess, _super);
  23748. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  23749. var _this = this;
  23750. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23751. this.kernelMatrix = kernelMatrix;
  23752. this.onApply = function (effect) {
  23753. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23754. };
  23755. }
  23756. return FilterPostProcess;
  23757. })(BABYLON.PostProcess);
  23758. BABYLON.FilterPostProcess = FilterPostProcess;
  23759. })(BABYLON || (BABYLON = {}));
  23760. var BABYLON;
  23761. (function (BABYLON) {
  23762. var FxaaPostProcess = (function (_super) {
  23763. __extends(FxaaPostProcess, _super);
  23764. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23765. var _this = this;
  23766. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23767. this.onSizeChanged = function () {
  23768. _this.texelWidth = 1.0 / _this.width;
  23769. _this.texelHeight = 1.0 / _this.height;
  23770. };
  23771. this.onApply = function (effect) {
  23772. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23773. };
  23774. }
  23775. return FxaaPostProcess;
  23776. })(BABYLON.PostProcess);
  23777. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23778. })(BABYLON || (BABYLON = {}));
  23779. var BABYLON;
  23780. (function (BABYLON) {
  23781. var StereoscopicInterlacePostProcess = (function (_super) {
  23782. __extends(StereoscopicInterlacePostProcess, _super);
  23783. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23784. var _this = this;
  23785. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23786. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23787. this.onSizeChanged = function () {
  23788. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23789. };
  23790. this.onApply = function (effect) {
  23791. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23792. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23793. };
  23794. }
  23795. return StereoscopicInterlacePostProcess;
  23796. })(BABYLON.PostProcess);
  23797. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23798. })(BABYLON || (BABYLON = {}));
  23799. var BABYLON;
  23800. (function (BABYLON) {
  23801. var LensFlare = (function () {
  23802. function LensFlare(size, position, color, imgUrl, system) {
  23803. this.size = size;
  23804. this.position = position;
  23805. this.dispose = function () {
  23806. if (this.texture) {
  23807. this.texture.dispose();
  23808. }
  23809. // Remove from scene
  23810. var index = this._system.lensFlares.indexOf(this);
  23811. this._system.lensFlares.splice(index, 1);
  23812. };
  23813. this.color = color || new BABYLON.Color3(1, 1, 1);
  23814. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23815. this._system = system;
  23816. system.lensFlares.push(this);
  23817. }
  23818. return LensFlare;
  23819. })();
  23820. BABYLON.LensFlare = LensFlare;
  23821. })(BABYLON || (BABYLON = {}));
  23822. var BABYLON;
  23823. (function (BABYLON) {
  23824. var LensFlareSystem = (function () {
  23825. function LensFlareSystem(name, emitter, scene) {
  23826. this.name = name;
  23827. this.lensFlares = new Array();
  23828. this.borderLimit = 300;
  23829. this.layerMask = 0x0FFFFFFF;
  23830. this._vertexDeclaration = [2];
  23831. this._vertexStrideSize = 2 * 4;
  23832. this._isEnabled = true;
  23833. this._scene = scene;
  23834. this._emitter = emitter;
  23835. scene.lensFlareSystems.push(this);
  23836. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23837. // VBO
  23838. var vertices = [];
  23839. vertices.push(1, 1);
  23840. vertices.push(-1, 1);
  23841. vertices.push(-1, -1);
  23842. vertices.push(1, -1);
  23843. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23844. // Indices
  23845. var indices = [];
  23846. indices.push(0);
  23847. indices.push(1);
  23848. indices.push(2);
  23849. indices.push(0);
  23850. indices.push(2);
  23851. indices.push(3);
  23852. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23853. // Effects
  23854. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23855. }
  23856. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23857. get: function () {
  23858. return this._isEnabled;
  23859. },
  23860. set: function (value) {
  23861. this._isEnabled = value;
  23862. },
  23863. enumerable: true,
  23864. configurable: true
  23865. });
  23866. LensFlareSystem.prototype.getScene = function () {
  23867. return this._scene;
  23868. };
  23869. LensFlareSystem.prototype.getEmitter = function () {
  23870. return this._emitter;
  23871. };
  23872. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23873. this._emitter = newEmitter;
  23874. };
  23875. LensFlareSystem.prototype.getEmitterPosition = function () {
  23876. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23877. };
  23878. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23879. var position = this.getEmitterPosition();
  23880. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23881. this._positionX = position.x;
  23882. this._positionY = position.y;
  23883. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23884. if (position.z > 0) {
  23885. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23886. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23887. return true;
  23888. }
  23889. }
  23890. return false;
  23891. };
  23892. LensFlareSystem.prototype._isVisible = function () {
  23893. if (!this._isEnabled) {
  23894. return false;
  23895. }
  23896. var emitterPosition = this.getEmitterPosition();
  23897. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23898. var distance = direction.length();
  23899. direction.normalize();
  23900. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23901. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23902. return !pickInfo.hit || pickInfo.distance > distance;
  23903. };
  23904. LensFlareSystem.prototype.render = function () {
  23905. if (!this._effect.isReady())
  23906. return false;
  23907. var engine = this._scene.getEngine();
  23908. var viewport = this._scene.activeCamera.viewport;
  23909. var globalViewport = viewport.toGlobal(engine);
  23910. // Position
  23911. if (!this.computeEffectivePosition(globalViewport)) {
  23912. return false;
  23913. }
  23914. // Visibility
  23915. if (!this._isVisible()) {
  23916. return false;
  23917. }
  23918. // Intensity
  23919. var awayX;
  23920. var awayY;
  23921. if (this._positionX < this.borderLimit + globalViewport.x) {
  23922. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23923. }
  23924. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23925. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23926. }
  23927. else {
  23928. awayX = 0;
  23929. }
  23930. if (this._positionY < this.borderLimit + globalViewport.y) {
  23931. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23932. }
  23933. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23934. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23935. }
  23936. else {
  23937. awayY = 0;
  23938. }
  23939. var away = (awayX > awayY) ? awayX : awayY;
  23940. if (away > this.borderLimit) {
  23941. away = this.borderLimit;
  23942. }
  23943. var intensity = 1.0 - (away / this.borderLimit);
  23944. if (intensity < 0) {
  23945. return false;
  23946. }
  23947. if (intensity > 1.0) {
  23948. intensity = 1.0;
  23949. }
  23950. // Position
  23951. var centerX = globalViewport.x + globalViewport.width / 2;
  23952. var centerY = globalViewport.y + globalViewport.height / 2;
  23953. var distX = centerX - this._positionX;
  23954. var distY = centerY - this._positionY;
  23955. // Effects
  23956. engine.enableEffect(this._effect);
  23957. engine.setState(false);
  23958. engine.setDepthBuffer(false);
  23959. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23960. // VBOs
  23961. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23962. // Flares
  23963. for (var index = 0; index < this.lensFlares.length; index++) {
  23964. var flare = this.lensFlares[index];
  23965. var x = centerX - (distX * flare.position);
  23966. var y = centerY - (distY * flare.position);
  23967. var cw = flare.size;
  23968. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23969. var cx = 2 * (x / globalViewport.width) - 1.0;
  23970. var cy = 1.0 - 2 * (y / globalViewport.height);
  23971. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23972. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23973. // Texture
  23974. this._effect.setTexture("textureSampler", flare.texture);
  23975. // Color
  23976. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23977. // Draw order
  23978. engine.draw(true, 0, 6);
  23979. }
  23980. engine.setDepthBuffer(true);
  23981. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23982. return true;
  23983. };
  23984. LensFlareSystem.prototype.dispose = function () {
  23985. if (this._vertexBuffer) {
  23986. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23987. this._vertexBuffer = null;
  23988. }
  23989. if (this._indexBuffer) {
  23990. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23991. this._indexBuffer = null;
  23992. }
  23993. while (this.lensFlares.length) {
  23994. this.lensFlares[0].dispose();
  23995. }
  23996. // Remove from scene
  23997. var index = this._scene.lensFlareSystems.indexOf(this);
  23998. this._scene.lensFlareSystems.splice(index, 1);
  23999. };
  24000. return LensFlareSystem;
  24001. })();
  24002. BABYLON.LensFlareSystem = LensFlareSystem;
  24003. })(BABYLON || (BABYLON = {}));
  24004. var BABYLON;
  24005. (function (BABYLON) {
  24006. var CannonJSPlugin = (function () {
  24007. function CannonJSPlugin() {
  24008. this._registeredMeshes = [];
  24009. this._physicsMaterials = [];
  24010. this.updateBodyPosition = function (mesh) {
  24011. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24012. var registeredMesh = this._registeredMeshes[index];
  24013. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24014. var body = registeredMesh.body;
  24015. var center = mesh.getBoundingInfo().boundingBox.center;
  24016. body.position.set(center.x, center.z, center.y);
  24017. body.quaternion.x = mesh.rotationQuaternion.x;
  24018. body.quaternion.z = mesh.rotationQuaternion.y;
  24019. body.quaternion.y = mesh.rotationQuaternion.z;
  24020. body.quaternion.w = -mesh.rotationQuaternion.w;
  24021. return;
  24022. }
  24023. }
  24024. };
  24025. }
  24026. CannonJSPlugin.prototype.initialize = function (iterations) {
  24027. if (iterations === void 0) { iterations = 10; }
  24028. this._world = new CANNON.World();
  24029. this._world.broadphase = new CANNON.NaiveBroadphase();
  24030. this._world.solver.iterations = iterations;
  24031. };
  24032. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  24033. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24034. };
  24035. CannonJSPlugin.prototype.runOneStep = function (delta) {
  24036. this._world.step(delta);
  24037. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24038. var registeredMesh = this._registeredMeshes[index];
  24039. if (registeredMesh.isChild) {
  24040. continue;
  24041. }
  24042. // Body position
  24043. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  24044. var deltaPos = registeredMesh.delta;
  24045. if (deltaPos) {
  24046. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  24047. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  24048. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  24049. }
  24050. else {
  24051. registeredMesh.mesh.position.x = bodyX;
  24052. registeredMesh.mesh.position.y = bodyZ;
  24053. registeredMesh.mesh.position.z = bodyY;
  24054. }
  24055. if (!registeredMesh.mesh.rotationQuaternion) {
  24056. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24057. }
  24058. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  24059. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  24060. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  24061. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  24062. }
  24063. };
  24064. CannonJSPlugin.prototype.setGravity = function (gravity) {
  24065. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  24066. };
  24067. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24068. this.unregisterMesh(mesh);
  24069. mesh.computeWorldMatrix(true);
  24070. switch (impostor) {
  24071. case BABYLON.PhysicsEngine.SphereImpostor:
  24072. var bbox = mesh.getBoundingInfo().boundingBox;
  24073. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24074. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24075. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24076. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24077. case BABYLON.PhysicsEngine.BoxImpostor:
  24078. bbox = mesh.getBoundingInfo().boundingBox;
  24079. var min = bbox.minimumWorld;
  24080. var max = bbox.maximumWorld;
  24081. var box = max.subtract(min).scale(0.5);
  24082. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24083. case BABYLON.PhysicsEngine.PlaneImpostor:
  24084. return this._createPlane(mesh, options);
  24085. case BABYLON.PhysicsEngine.MeshImpostor:
  24086. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24087. var rawFaces = mesh.getIndices();
  24088. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24089. }
  24090. return null;
  24091. };
  24092. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24093. var shape = new CANNON.Sphere(radius);
  24094. if (!options) {
  24095. return shape;
  24096. }
  24097. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24098. };
  24099. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24100. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24101. if (!options) {
  24102. return shape;
  24103. }
  24104. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24105. };
  24106. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24107. var shape = new CANNON.Plane();
  24108. if (!options) {
  24109. return shape;
  24110. }
  24111. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24112. };
  24113. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24114. var verts = [], faces = [];
  24115. mesh.computeWorldMatrix(true);
  24116. // Get vertices
  24117. for (var i = 0; i < rawVerts.length; i += 3) {
  24118. var transformed = BABYLON.Vector3.Zero();
  24119. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24120. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24121. }
  24122. // Get faces
  24123. for (var j = 0; j < rawFaces.length; j += 3) {
  24124. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24125. }
  24126. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24127. if (!options) {
  24128. return shape;
  24129. }
  24130. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24131. };
  24132. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24133. var index;
  24134. var mat;
  24135. for (index = 0; index < this._physicsMaterials.length; index++) {
  24136. mat = this._physicsMaterials[index];
  24137. if (mat.friction === friction && mat.restitution === restitution) {
  24138. return mat;
  24139. }
  24140. }
  24141. var currentMat = new CANNON.Material();
  24142. currentMat.friction = friction;
  24143. currentMat.restitution = restitution;
  24144. this._physicsMaterials.push(currentMat);
  24145. for (index = 0; index < this._physicsMaterials.length; index++) {
  24146. mat = this._physicsMaterials[index];
  24147. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24148. contactMaterial.contactEquationStiffness = 1e10;
  24149. contactMaterial.contactEquationRegularizationTime = 10;
  24150. this._world.addContactMaterial(contactMaterial);
  24151. }
  24152. return currentMat;
  24153. };
  24154. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24155. var initialRotation = null;
  24156. if (mesh.rotationQuaternion) {
  24157. initialRotation = mesh.rotationQuaternion.clone();
  24158. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24159. }
  24160. // The delta between the mesh position and the mesh bounding box center
  24161. var bbox = mesh.getBoundingInfo().boundingBox;
  24162. var deltaPosition = mesh.position.subtract(bbox.center);
  24163. var material = this._addMaterial(friction, restitution);
  24164. var body = new CANNON.RigidBody(mass, shape, material);
  24165. if (initialRotation) {
  24166. body.quaternion.x = initialRotation.x;
  24167. body.quaternion.z = initialRotation.y;
  24168. body.quaternion.y = initialRotation.z;
  24169. body.quaternion.w = -initialRotation.w;
  24170. }
  24171. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24172. this._world.add(body);
  24173. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24174. return body;
  24175. };
  24176. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24177. var compoundShape = new CANNON.Compound();
  24178. for (var index = 0; index < parts.length; index++) {
  24179. var mesh = parts[index].mesh;
  24180. var shape = this.registerMesh(mesh, parts[index].impostor);
  24181. if (index == 0) {
  24182. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24183. }
  24184. else {
  24185. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24186. }
  24187. }
  24188. var initialMesh = parts[0].mesh;
  24189. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24190. body.parts = parts;
  24191. return body;
  24192. };
  24193. CannonJSPlugin.prototype._unbindBody = function (body) {
  24194. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24195. var registeredMesh = this._registeredMeshes[index];
  24196. if (registeredMesh.body === body) {
  24197. registeredMesh.body = null;
  24198. registeredMesh.delta = 0;
  24199. }
  24200. }
  24201. };
  24202. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24203. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24204. var registeredMesh = this._registeredMeshes[index];
  24205. if (registeredMesh.mesh === mesh) {
  24206. // Remove body
  24207. if (registeredMesh.body) {
  24208. this._world.remove(registeredMesh.body);
  24209. this._unbindBody(registeredMesh.body);
  24210. }
  24211. this._registeredMeshes.splice(index, 1);
  24212. return;
  24213. }
  24214. }
  24215. };
  24216. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24217. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24218. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24219. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24220. var registeredMesh = this._registeredMeshes[index];
  24221. if (registeredMesh.mesh === mesh) {
  24222. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24223. return;
  24224. }
  24225. }
  24226. };
  24227. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24228. var body1 = null, body2 = null;
  24229. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24230. var registeredMesh = this._registeredMeshes[index];
  24231. if (registeredMesh.mesh === mesh1) {
  24232. body1 = registeredMesh.body;
  24233. }
  24234. else if (registeredMesh.mesh === mesh2) {
  24235. body2 = registeredMesh.body;
  24236. }
  24237. }
  24238. if (!body1 || !body2) {
  24239. return false;
  24240. }
  24241. 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));
  24242. this._world.addConstraint(constraint);
  24243. return true;
  24244. };
  24245. CannonJSPlugin.prototype.dispose = function () {
  24246. while (this._registeredMeshes.length) {
  24247. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24248. }
  24249. };
  24250. CannonJSPlugin.prototype.isSupported = function () {
  24251. return window.CANNON !== undefined;
  24252. };
  24253. return CannonJSPlugin;
  24254. })();
  24255. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24256. })(BABYLON || (BABYLON = {}));
  24257. var BABYLON;
  24258. (function (BABYLON) {
  24259. var OimoJSPlugin = (function () {
  24260. function OimoJSPlugin() {
  24261. this._registeredMeshes = [];
  24262. /**
  24263. * Update the body position according to the mesh position
  24264. * @param mesh
  24265. */
  24266. this.updateBodyPosition = function (mesh) {
  24267. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24268. var registeredMesh = this._registeredMeshes[index];
  24269. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24270. var body = registeredMesh.body.body;
  24271. mesh.computeWorldMatrix(true);
  24272. var center = mesh.getBoundingInfo().boundingBox.center;
  24273. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  24274. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  24275. body.sleeping = false;
  24276. return;
  24277. }
  24278. // Case where the parent has been updated
  24279. if (registeredMesh.mesh.parent === mesh) {
  24280. mesh.computeWorldMatrix(true);
  24281. registeredMesh.mesh.computeWorldMatrix(true);
  24282. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  24283. var absoluteRotation = mesh.rotation;
  24284. body = registeredMesh.body.body;
  24285. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  24286. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  24287. body.sleeping = false;
  24288. return;
  24289. }
  24290. }
  24291. };
  24292. }
  24293. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  24294. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24295. };
  24296. OimoJSPlugin.prototype.initialize = function (iterations) {
  24297. this._world = new OIMO.World();
  24298. this._world.clear();
  24299. };
  24300. OimoJSPlugin.prototype.setGravity = function (gravity) {
  24301. this._world.gravity = gravity;
  24302. };
  24303. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24304. var body = null;
  24305. this.unregisterMesh(mesh);
  24306. mesh.computeWorldMatrix(true);
  24307. var initialRotation = null;
  24308. if (mesh.rotationQuaternion) {
  24309. initialRotation = mesh.rotationQuaternion.clone();
  24310. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24311. mesh.computeWorldMatrix(true);
  24312. }
  24313. var bbox = mesh.getBoundingInfo().boundingBox;
  24314. // The delta between the mesh position and the mesh bounding box center
  24315. var deltaPosition = mesh.position.subtract(bbox.center);
  24316. // Transform delta position with the rotation
  24317. if (initialRotation) {
  24318. var m = new BABYLON.Matrix();
  24319. initialRotation.toRotationMatrix(m);
  24320. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  24321. }
  24322. // register mesh
  24323. switch (impostor) {
  24324. case BABYLON.PhysicsEngine.SphereImpostor:
  24325. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24326. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24327. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24328. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  24329. body = new OIMO.Body({
  24330. type: 'sphere',
  24331. size: [size],
  24332. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  24333. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  24334. move: options.mass != 0,
  24335. config: [options.mass, options.friction, options.restitution],
  24336. world: this._world
  24337. });
  24338. break;
  24339. case BABYLON.PhysicsEngine.PlaneImpostor:
  24340. //Oimo "fakes" a cylinder as a box, so why don't we!
  24341. case BABYLON.PhysicsEngine.CylinderImpostor:
  24342. case BABYLON.PhysicsEngine.BoxImpostor:
  24343. var min = bbox.minimumWorld;
  24344. var max = bbox.maximumWorld;
  24345. var box = max.subtract(min);
  24346. var sizeX = this._checkWithEpsilon(box.x);
  24347. var sizeY = this._checkWithEpsilon(box.y);
  24348. var sizeZ = this._checkWithEpsilon(box.z);
  24349. body = new OIMO.Body({
  24350. type: 'box',
  24351. size: [sizeX, sizeY, sizeZ],
  24352. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  24353. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  24354. move: options.mass != 0,
  24355. config: [options.mass, options.friction, options.restitution],
  24356. world: this._world
  24357. });
  24358. break;
  24359. }
  24360. //If quaternion was set as the rotation of the object
  24361. if (initialRotation) {
  24362. //We have to access the rigid body's properties to set the quaternion.
  24363. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  24364. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  24365. //update the internal rotation matrix
  24366. body.body.syncShapes();
  24367. }
  24368. this._registeredMeshes.push({
  24369. mesh: mesh,
  24370. body: body,
  24371. delta: deltaPosition
  24372. });
  24373. return body;
  24374. };
  24375. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24376. var types = [], sizes = [], positions = [], rotations = [];
  24377. var initialMesh = parts[0].mesh;
  24378. for (var index = 0; index < parts.length; index++) {
  24379. var part = parts[index];
  24380. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  24381. types.push(bodyParameters.type);
  24382. sizes.push.apply(sizes, bodyParameters.size);
  24383. positions.push.apply(positions, bodyParameters.pos);
  24384. rotations.push.apply(rotations, bodyParameters.rot);
  24385. }
  24386. var body = new OIMO.Body({
  24387. type: types,
  24388. size: sizes,
  24389. pos: positions,
  24390. rot: rotations,
  24391. move: options.mass != 0,
  24392. config: [options.mass, options.friction, options.restitution],
  24393. world: this._world
  24394. });
  24395. this._registeredMeshes.push({
  24396. mesh: initialMesh,
  24397. body: body
  24398. });
  24399. return body;
  24400. };
  24401. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  24402. var bodyParameters = null;
  24403. var mesh = part.mesh;
  24404. // We need the bounding box/sphere info to compute the physics body
  24405. mesh.computeWorldMatrix();
  24406. switch (part.impostor) {
  24407. case BABYLON.PhysicsEngine.SphereImpostor:
  24408. var bbox = mesh.getBoundingInfo().boundingBox;
  24409. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24410. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24411. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24412. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  24413. bodyParameters = {
  24414. type: 'sphere',
  24415. /* bug with oimo : sphere needs 3 sizes in this case */
  24416. size: [size, -1, -1],
  24417. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  24418. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  24419. };
  24420. break;
  24421. case BABYLON.PhysicsEngine.PlaneImpostor:
  24422. case BABYLON.PhysicsEngine.BoxImpostor:
  24423. bbox = mesh.getBoundingInfo().boundingBox;
  24424. var min = bbox.minimumWorld;
  24425. var max = bbox.maximumWorld;
  24426. var box = max.subtract(min);
  24427. var sizeX = this._checkWithEpsilon(box.x);
  24428. var sizeY = this._checkWithEpsilon(box.y);
  24429. var sizeZ = this._checkWithEpsilon(box.z);
  24430. var relativePosition = mesh.position;
  24431. bodyParameters = {
  24432. type: 'box',
  24433. size: [sizeX, sizeY, sizeZ],
  24434. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  24435. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  24436. };
  24437. break;
  24438. }
  24439. return bodyParameters;
  24440. };
  24441. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  24442. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24443. var registeredMesh = this._registeredMeshes[index];
  24444. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24445. if (registeredMesh.body) {
  24446. this._world.removeRigidBody(registeredMesh.body.body);
  24447. this._unbindBody(registeredMesh.body);
  24448. }
  24449. this._registeredMeshes.splice(index, 1);
  24450. return;
  24451. }
  24452. }
  24453. };
  24454. OimoJSPlugin.prototype._unbindBody = function (body) {
  24455. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24456. var registeredMesh = this._registeredMeshes[index];
  24457. if (registeredMesh.body === body) {
  24458. registeredMesh.body = null;
  24459. }
  24460. }
  24461. };
  24462. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24463. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24464. var registeredMesh = this._registeredMeshes[index];
  24465. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24466. // Get object mass to have a behaviour similar to cannon.js
  24467. var mass = registeredMesh.body.body.massInfo.mass;
  24468. // The force is scaled with the mass of object
  24469. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  24470. return;
  24471. }
  24472. }
  24473. };
  24474. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  24475. var body1 = null, body2 = null;
  24476. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24477. var registeredMesh = this._registeredMeshes[index];
  24478. if (registeredMesh.mesh === mesh1) {
  24479. body1 = registeredMesh.body.body;
  24480. }
  24481. else if (registeredMesh.mesh === mesh2) {
  24482. body2 = registeredMesh.body.body;
  24483. }
  24484. }
  24485. if (!body1 || !body2) {
  24486. return false;
  24487. }
  24488. if (!options) {
  24489. options = {};
  24490. }
  24491. new OIMO.Link({
  24492. type: options.type,
  24493. body1: body1,
  24494. body2: body2,
  24495. min: options.min,
  24496. max: options.max,
  24497. axe1: options.axe1,
  24498. axe2: options.axe2,
  24499. pos1: [pivot1.x, pivot1.y, pivot1.z],
  24500. pos2: [pivot2.x, pivot2.y, pivot2.z],
  24501. collision: options.collision,
  24502. spring: options.spring,
  24503. world: this._world
  24504. });
  24505. return true;
  24506. };
  24507. OimoJSPlugin.prototype.dispose = function () {
  24508. this._world.clear();
  24509. while (this._registeredMeshes.length) {
  24510. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24511. }
  24512. };
  24513. OimoJSPlugin.prototype.isSupported = function () {
  24514. return OIMO !== undefined;
  24515. };
  24516. OimoJSPlugin.prototype._getLastShape = function (body) {
  24517. var lastShape = body.shapes;
  24518. while (lastShape.next) {
  24519. lastShape = lastShape.next;
  24520. }
  24521. return lastShape;
  24522. };
  24523. OimoJSPlugin.prototype.runOneStep = function (time) {
  24524. this._world.step();
  24525. // Update the position of all registered meshes
  24526. var i = this._registeredMeshes.length;
  24527. var m;
  24528. while (i--) {
  24529. var body = this._registeredMeshes[i].body.body;
  24530. var mesh = this._registeredMeshes[i].mesh;
  24531. var delta = this._registeredMeshes[i].delta;
  24532. if (!body.sleeping) {
  24533. if (body.shapes.next) {
  24534. var parentShape = this._getLastShape(body);
  24535. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  24536. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  24537. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  24538. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  24539. if (!mesh.rotationQuaternion) {
  24540. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24541. }
  24542. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  24543. mesh.computeWorldMatrix();
  24544. }
  24545. else {
  24546. m = body.getMatrix();
  24547. mtx = BABYLON.Matrix.FromArray(m);
  24548. // Body position
  24549. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  24550. if (!delta) {
  24551. mesh.position.x = bodyX;
  24552. mesh.position.y = bodyY;
  24553. mesh.position.z = bodyZ;
  24554. }
  24555. else {
  24556. mesh.position.x = bodyX + delta.x;
  24557. mesh.position.y = bodyY + delta.y;
  24558. mesh.position.z = bodyZ + delta.z;
  24559. }
  24560. if (!mesh.rotationQuaternion) {
  24561. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24562. }
  24563. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  24564. mesh.computeWorldMatrix();
  24565. }
  24566. }
  24567. }
  24568. };
  24569. return OimoJSPlugin;
  24570. })();
  24571. BABYLON.OimoJSPlugin = OimoJSPlugin;
  24572. })(BABYLON || (BABYLON = {}));
  24573. var BABYLON;
  24574. (function (BABYLON) {
  24575. var PhysicsEngine = (function () {
  24576. function PhysicsEngine(plugin) {
  24577. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  24578. }
  24579. PhysicsEngine.prototype._initialize = function (gravity) {
  24580. this._currentPlugin.initialize();
  24581. this._setGravity(gravity);
  24582. };
  24583. PhysicsEngine.prototype._runOneStep = function (delta) {
  24584. if (delta > 0.1) {
  24585. delta = 0.1;
  24586. }
  24587. else if (delta <= 0) {
  24588. delta = 1.0 / 60.0;
  24589. }
  24590. this._currentPlugin.runOneStep(delta);
  24591. };
  24592. PhysicsEngine.prototype._setGravity = function (gravity) {
  24593. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24594. this._currentPlugin.setGravity(this.gravity);
  24595. };
  24596. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  24597. return this._currentPlugin.registerMesh(mesh, impostor, options);
  24598. };
  24599. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  24600. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  24601. };
  24602. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  24603. this._currentPlugin.unregisterMesh(mesh);
  24604. };
  24605. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  24606. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  24607. };
  24608. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  24609. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  24610. };
  24611. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  24612. this._currentPlugin.updateBodyPosition(mesh);
  24613. };
  24614. PhysicsEngine.prototype.dispose = function () {
  24615. this._currentPlugin.dispose();
  24616. };
  24617. PhysicsEngine.prototype.isSupported = function () {
  24618. return this._currentPlugin.isSupported();
  24619. };
  24620. // Statics
  24621. PhysicsEngine.NoImpostor = 0;
  24622. PhysicsEngine.SphereImpostor = 1;
  24623. PhysicsEngine.BoxImpostor = 2;
  24624. PhysicsEngine.PlaneImpostor = 3;
  24625. PhysicsEngine.MeshImpostor = 4;
  24626. PhysicsEngine.CapsuleImpostor = 5;
  24627. PhysicsEngine.ConeImpostor = 6;
  24628. PhysicsEngine.CylinderImpostor = 7;
  24629. PhysicsEngine.ConvexHullImpostor = 8;
  24630. PhysicsEngine.Epsilon = 0.001;
  24631. return PhysicsEngine;
  24632. })();
  24633. BABYLON.PhysicsEngine = PhysicsEngine;
  24634. })(BABYLON || (BABYLON = {}));
  24635. var BABYLON;
  24636. (function (BABYLON) {
  24637. var serializeLight = function (light) {
  24638. var serializationObject = {};
  24639. serializationObject.name = light.name;
  24640. serializationObject.id = light.id;
  24641. serializationObject.tags = BABYLON.Tags.GetTags(light);
  24642. if (light instanceof BABYLON.PointLight) {
  24643. serializationObject.type = 0;
  24644. serializationObject.position = (light).position.asArray();
  24645. }
  24646. else if (light instanceof BABYLON.DirectionalLight) {
  24647. serializationObject.type = 1;
  24648. var directionalLight = light;
  24649. serializationObject.position = directionalLight.position.asArray();
  24650. serializationObject.direction = directionalLight.direction.asArray();
  24651. }
  24652. else if (light instanceof BABYLON.SpotLight) {
  24653. serializationObject.type = 2;
  24654. var spotLight = light;
  24655. serializationObject.position = spotLight.position.asArray();
  24656. serializationObject.direction = spotLight.position.asArray();
  24657. serializationObject.angle = spotLight.angle;
  24658. serializationObject.exponent = spotLight.exponent;
  24659. }
  24660. else if (light instanceof BABYLON.HemisphericLight) {
  24661. serializationObject.type = 3;
  24662. var hemisphericLight = light;
  24663. serializationObject.direction = hemisphericLight.direction.asArray();
  24664. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  24665. }
  24666. if (light.intensity) {
  24667. serializationObject.intensity = light.intensity;
  24668. }
  24669. serializationObject.range = light.range;
  24670. serializationObject.diffuse = light.diffuse.asArray();
  24671. serializationObject.specular = light.specular.asArray();
  24672. return serializationObject;
  24673. };
  24674. var serializeFresnelParameter = function (fresnelParameter) {
  24675. var serializationObject = {};
  24676. serializationObject.isEnabled = fresnelParameter.isEnabled;
  24677. serializationObject.leftColor = fresnelParameter.leftColor;
  24678. serializationObject.rightColor = fresnelParameter.rightColor;
  24679. serializationObject.bias = fresnelParameter.bias;
  24680. serializationObject.power = fresnelParameter.power;
  24681. return serializationObject;
  24682. };
  24683. var serializeAnimation;
  24684. var appendAnimations = function (source, destination) {
  24685. if (source.animations) {
  24686. destination.animations = [];
  24687. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24688. var animation = source.animations[animationIndex];
  24689. destination.animations.push(serializeAnimation(animation));
  24690. }
  24691. }
  24692. };
  24693. var serializeCamera = function (camera) {
  24694. var serializationObject = {};
  24695. serializationObject.name = camera.name;
  24696. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  24697. serializationObject.id = camera.id;
  24698. serializationObject.position = camera.position.asArray();
  24699. // Parent
  24700. if (camera.parent) {
  24701. serializationObject.parentId = camera.parent.id;
  24702. }
  24703. serializationObject.fov = camera.fov;
  24704. serializationObject.minZ = camera.minZ;
  24705. serializationObject.maxZ = camera.maxZ;
  24706. serializationObject.inertia = camera.inertia;
  24707. //setting the type
  24708. if (camera instanceof BABYLON.FreeCamera) {
  24709. serializationObject.type = "FreeCamera";
  24710. }
  24711. else if (camera instanceof BABYLON.ArcRotateCamera) {
  24712. serializationObject.type = "ArcRotateCamera";
  24713. }
  24714. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24715. serializationObject.type = "AnaglyphArcRotateCamera";
  24716. }
  24717. else if (camera instanceof BABYLON.GamepadCamera) {
  24718. serializationObject.type = "GamepadCamera";
  24719. }
  24720. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  24721. serializationObject.type = "AnaglyphFreeCamera";
  24722. }
  24723. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  24724. serializationObject.type = "DeviceOrientationCamera";
  24725. }
  24726. else if (camera instanceof BABYLON.FollowCamera) {
  24727. serializationObject.type = "FollowCamera";
  24728. }
  24729. else if (camera instanceof BABYLON.TouchCamera) {
  24730. serializationObject.type = "TouchCamera";
  24731. }
  24732. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  24733. serializationObject.type = "VirtualJoysticksCamera";
  24734. }
  24735. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  24736. serializationObject.type = "WebVRFreeCamera";
  24737. }
  24738. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  24739. serializationObject.type = "VRDeviceOrientationFreeCamera";
  24740. }
  24741. //special properties of specific cameras
  24742. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24743. var arcCamera = camera;
  24744. serializationObject.alpha = arcCamera.alpha;
  24745. serializationObject.beta = arcCamera.beta;
  24746. serializationObject.radius = arcCamera.radius;
  24747. if (arcCamera.target && arcCamera.target.id) {
  24748. serializationObject.lockedTargetId = arcCamera.target.id;
  24749. }
  24750. }
  24751. else if (camera instanceof BABYLON.FollowCamera) {
  24752. var followCam = camera;
  24753. serializationObject.radius = followCam.radius;
  24754. serializationObject.heightOffset = followCam.heightOffset;
  24755. serializationObject.rotationOffset = followCam.rotationOffset;
  24756. }
  24757. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24758. //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.
  24759. if (camera['_interaxialDistance'] !== undefined) {
  24760. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24761. }
  24762. }
  24763. //general properties that not all cameras have. The [] is due to typescript's type safety
  24764. if (camera['speed'] !== undefined) {
  24765. serializationObject.speed = camera['speed'];
  24766. }
  24767. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24768. serializationObject.target = camera['target'].asArray();
  24769. }
  24770. // Target
  24771. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24772. serializationObject.rotation = camera['rotation'].asArray();
  24773. }
  24774. // Locked target
  24775. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24776. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24777. }
  24778. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24779. serializationObject.applyGravity = camera['applyGravity'] || false;
  24780. if (camera['ellipsoid']) {
  24781. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24782. }
  24783. // Animations
  24784. appendAnimations(camera, serializationObject);
  24785. // Layer mask
  24786. serializationObject.layerMask = camera.layerMask;
  24787. return serializationObject;
  24788. };
  24789. serializeAnimation = function (animation) {
  24790. var serializationObject = {};
  24791. serializationObject.name = animation.name;
  24792. serializationObject.property = animation.targetProperty;
  24793. serializationObject.framePerSecond = animation.framePerSecond;
  24794. serializationObject.dataType = animation.dataType;
  24795. serializationObject.loopBehavior = animation.loopMode;
  24796. var dataType = animation.dataType;
  24797. serializationObject.keys = [];
  24798. var keys = animation.getKeys();
  24799. for (var index = 0; index < keys.length; index++) {
  24800. var animationKey = keys[index];
  24801. var key = {};
  24802. key.frame = animationKey.frame;
  24803. switch (dataType) {
  24804. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24805. key.values = [animationKey.value];
  24806. break;
  24807. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24808. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24809. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24810. key.values = animationKey.value.asArray();
  24811. break;
  24812. }
  24813. serializationObject.keys.push(key);
  24814. }
  24815. return serializationObject;
  24816. };
  24817. var serializeMultiMaterial = function (material) {
  24818. var serializationObject = {};
  24819. serializationObject.name = material.name;
  24820. serializationObject.id = material.id;
  24821. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24822. serializationObject.materials = [];
  24823. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24824. var subMat = material.subMaterials[matIndex];
  24825. if (subMat) {
  24826. serializationObject.materials.push(subMat.id);
  24827. }
  24828. else {
  24829. serializationObject.materials.push(null);
  24830. }
  24831. }
  24832. return serializationObject;
  24833. };
  24834. var serializeTexture;
  24835. var serializeMaterial = function (material) {
  24836. var serializationObject = {};
  24837. serializationObject.name = material.name;
  24838. serializationObject.ambient = material.ambientColor.asArray();
  24839. serializationObject.diffuse = material.diffuseColor.asArray();
  24840. serializationObject.specular = material.specularColor.asArray();
  24841. serializationObject.specularPower = material.specularPower;
  24842. serializationObject.emissive = material.emissiveColor.asArray();
  24843. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  24844. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  24845. serializationObject.alpha = material.alpha;
  24846. serializationObject.id = material.id;
  24847. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24848. serializationObject.backFaceCulling = material.backFaceCulling;
  24849. if (material.diffuseTexture) {
  24850. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24851. }
  24852. if (material.diffuseFresnelParameters) {
  24853. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24854. }
  24855. if (material.ambientTexture) {
  24856. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24857. }
  24858. if (material.opacityTexture) {
  24859. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24860. }
  24861. if (material.opacityFresnelParameters) {
  24862. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24863. }
  24864. if (material.reflectionTexture) {
  24865. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24866. }
  24867. if (material.reflectionFresnelParameters) {
  24868. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24869. }
  24870. if (material.emissiveTexture) {
  24871. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24872. }
  24873. if (material.lightmapTexture) {
  24874. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  24875. serializationObject.lightmapThreshold = material.lightmapThreshold;
  24876. }
  24877. if (material.emissiveFresnelParameters) {
  24878. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24879. }
  24880. if (material.specularTexture) {
  24881. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24882. }
  24883. if (material.bumpTexture) {
  24884. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24885. }
  24886. return serializationObject;
  24887. };
  24888. serializeTexture = function (texture) {
  24889. var serializationObject = {};
  24890. if (!texture.name) {
  24891. return null;
  24892. }
  24893. if (texture instanceof BABYLON.CubeTexture) {
  24894. serializationObject.name = texture.name;
  24895. serializationObject.hasAlpha = texture.hasAlpha;
  24896. serializationObject.isCube = true;
  24897. serializationObject.level = texture.level;
  24898. serializationObject.coordinatesMode = texture.coordinatesMode;
  24899. return serializationObject;
  24900. }
  24901. var index;
  24902. if (texture instanceof BABYLON.MirrorTexture) {
  24903. var mirrorTexture = texture;
  24904. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24905. serializationObject.renderList = [];
  24906. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  24907. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24908. }
  24909. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24910. }
  24911. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24912. var renderTargetTexture = texture;
  24913. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24914. serializationObject.renderList = [];
  24915. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24916. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24917. }
  24918. }
  24919. var regularTexture = texture;
  24920. serializationObject.name = texture.name;
  24921. serializationObject.hasAlpha = texture.hasAlpha;
  24922. serializationObject.level = texture.level;
  24923. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24924. serializationObject.coordinatesMode = texture.coordinatesMode;
  24925. serializationObject.uOffset = regularTexture.uOffset;
  24926. serializationObject.vOffset = regularTexture.vOffset;
  24927. serializationObject.uScale = regularTexture.uScale;
  24928. serializationObject.vScale = regularTexture.vScale;
  24929. serializationObject.uAng = regularTexture.uAng;
  24930. serializationObject.vAng = regularTexture.vAng;
  24931. serializationObject.wAng = regularTexture.wAng;
  24932. serializationObject.wrapU = texture.wrapU;
  24933. serializationObject.wrapV = texture.wrapV;
  24934. // Animations
  24935. appendAnimations(texture, serializationObject);
  24936. return serializationObject;
  24937. };
  24938. var serializeSkeleton = function (skeleton) {
  24939. var serializationObject = {};
  24940. serializationObject.name = skeleton.name;
  24941. serializationObject.id = skeleton.id;
  24942. serializationObject.bones = [];
  24943. for (var index = 0; index < skeleton.bones.length; index++) {
  24944. var bone = skeleton.bones[index];
  24945. var serializedBone = {
  24946. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24947. name: bone.name,
  24948. matrix: bone.getLocalMatrix().toArray()
  24949. };
  24950. serializationObject.bones.push(serializedBone);
  24951. if (bone.animations && bone.animations.length > 0) {
  24952. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24953. }
  24954. }
  24955. return serializationObject;
  24956. };
  24957. var serializeParticleSystem = function (particleSystem) {
  24958. var serializationObject = {};
  24959. serializationObject.emitterId = particleSystem.emitter.id;
  24960. serializationObject.capacity = particleSystem.getCapacity();
  24961. if (particleSystem.particleTexture) {
  24962. serializationObject.textureName = particleSystem.particleTexture.name;
  24963. }
  24964. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24965. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24966. serializationObject.minSize = particleSystem.minSize;
  24967. serializationObject.maxSize = particleSystem.maxSize;
  24968. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24969. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24970. serializationObject.emitRate = particleSystem.emitRate;
  24971. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24972. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24973. serializationObject.gravity = particleSystem.gravity.asArray();
  24974. serializationObject.direction1 = particleSystem.direction1.asArray();
  24975. serializationObject.direction2 = particleSystem.direction2.asArray();
  24976. serializationObject.color1 = particleSystem.color1.asArray();
  24977. serializationObject.color2 = particleSystem.color2.asArray();
  24978. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24979. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24980. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24981. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24982. serializationObject.blendMode = particleSystem.blendMode;
  24983. return serializationObject;
  24984. };
  24985. var serializeLensFlareSystem = function (lensFlareSystem) {
  24986. var serializationObject = {};
  24987. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24988. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24989. serializationObject.flares = [];
  24990. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24991. var flare = lensFlareSystem.lensFlares[index];
  24992. serializationObject.flares.push({
  24993. size: flare.size,
  24994. position: flare.position,
  24995. color: flare.color.asArray(),
  24996. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24997. });
  24998. }
  24999. return serializationObject;
  25000. };
  25001. var serializeShadowGenerator = function (light) {
  25002. var serializationObject = {};
  25003. var shadowGenerator = light.getShadowGenerator();
  25004. serializationObject.lightId = light.id;
  25005. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  25006. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  25007. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  25008. serializationObject.renderList = [];
  25009. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  25010. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  25011. serializationObject.renderList.push(mesh.id);
  25012. }
  25013. return serializationObject;
  25014. };
  25015. var serializedGeometries = [];
  25016. var serializeVertexData;
  25017. var serializeTorusKnot;
  25018. var serializePlane;
  25019. var serializeGround;
  25020. var serializeTorus;
  25021. var serializeCylinder;
  25022. var serializeSphere;
  25023. var serializeBox;
  25024. var serializeGeometry = function (geometry, serializationGeometries) {
  25025. if (serializedGeometries[geometry.id]) {
  25026. return;
  25027. }
  25028. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  25029. serializationGeometries.boxes.push(serializeBox(geometry));
  25030. }
  25031. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  25032. serializationGeometries.spheres.push(serializeSphere(geometry));
  25033. }
  25034. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  25035. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  25036. }
  25037. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  25038. serializationGeometries.toruses.push(serializeTorus(geometry));
  25039. }
  25040. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  25041. serializationGeometries.grounds.push(serializeGround(geometry));
  25042. }
  25043. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  25044. serializationGeometries.planes.push(serializePlane(geometry));
  25045. }
  25046. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  25047. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  25048. }
  25049. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  25050. throw new Error("Unknown primitive type");
  25051. }
  25052. else {
  25053. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  25054. }
  25055. serializedGeometries[geometry.id] = true;
  25056. };
  25057. var serializeGeometryBase = function (geometry) {
  25058. var serializationObject = {};
  25059. serializationObject.id = geometry.id;
  25060. if (BABYLON.Tags.HasTags(geometry)) {
  25061. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  25062. }
  25063. return serializationObject;
  25064. };
  25065. serializeVertexData = function (vertexData) {
  25066. var serializationObject = serializeGeometryBase(vertexData);
  25067. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25068. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25069. }
  25070. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25071. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25072. }
  25073. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25074. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25075. }
  25076. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25077. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  25078. }
  25079. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25080. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  25081. }
  25082. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25083. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  25084. }
  25085. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25086. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  25087. }
  25088. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25089. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  25090. }
  25091. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25092. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  25093. }
  25094. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25095. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25096. serializationObject.matricesIndices._isExpanded = true;
  25097. }
  25098. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25099. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25100. }
  25101. serializationObject.indices = vertexData.getIndices();
  25102. return serializationObject;
  25103. };
  25104. var serializePrimitive = function (primitive) {
  25105. var serializationObject = serializeGeometryBase(primitive);
  25106. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  25107. return serializationObject;
  25108. };
  25109. serializeBox = function (box) {
  25110. var serializationObject = serializePrimitive(box);
  25111. serializationObject.size = box.size;
  25112. return serializationObject;
  25113. };
  25114. serializeSphere = function (sphere) {
  25115. var serializationObject = serializePrimitive(sphere);
  25116. serializationObject.segments = sphere.segments;
  25117. serializationObject.diameter = sphere.diameter;
  25118. return serializationObject;
  25119. };
  25120. serializeCylinder = function (cylinder) {
  25121. var serializationObject = serializePrimitive(cylinder);
  25122. serializationObject.height = cylinder.height;
  25123. serializationObject.diameterTop = cylinder.diameterTop;
  25124. serializationObject.diameterBottom = cylinder.diameterBottom;
  25125. serializationObject.tessellation = cylinder.tessellation;
  25126. return serializationObject;
  25127. };
  25128. serializeTorus = function (torus) {
  25129. var serializationObject = serializePrimitive(torus);
  25130. serializationObject.diameter = torus.diameter;
  25131. serializationObject.thickness = torus.thickness;
  25132. serializationObject.tessellation = torus.tessellation;
  25133. return serializationObject;
  25134. };
  25135. serializeGround = function (ground) {
  25136. var serializationObject = serializePrimitive(ground);
  25137. serializationObject.width = ground.width;
  25138. serializationObject.height = ground.height;
  25139. serializationObject.subdivisions = ground.subdivisions;
  25140. return serializationObject;
  25141. };
  25142. serializePlane = function (plane) {
  25143. var serializationObject = serializePrimitive(plane);
  25144. serializationObject.size = plane.size;
  25145. return serializationObject;
  25146. };
  25147. serializeTorusKnot = function (torusKnot) {
  25148. var serializationObject = serializePrimitive(torusKnot);
  25149. serializationObject.radius = torusKnot.radius;
  25150. serializationObject.tube = torusKnot.tube;
  25151. serializationObject.radialSegments = torusKnot.radialSegments;
  25152. serializationObject.tubularSegments = torusKnot.tubularSegments;
  25153. serializationObject.p = torusKnot.p;
  25154. serializationObject.q = torusKnot.q;
  25155. return serializationObject;
  25156. };
  25157. var serializeMesh = function (mesh, serializationScene) {
  25158. var serializationObject = {};
  25159. serializationObject.name = mesh.name;
  25160. serializationObject.id = mesh.id;
  25161. if (BABYLON.Tags.HasTags(mesh)) {
  25162. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  25163. }
  25164. serializationObject.position = mesh.position.asArray();
  25165. if (mesh.rotationQuaternion) {
  25166. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  25167. }
  25168. else if (mesh.rotation) {
  25169. serializationObject.rotation = mesh.rotation.asArray();
  25170. }
  25171. serializationObject.scaling = mesh.scaling.asArray();
  25172. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  25173. serializationObject.isEnabled = mesh.isEnabled();
  25174. serializationObject.isVisible = mesh.isVisible;
  25175. serializationObject.infiniteDistance = mesh.infiniteDistance;
  25176. serializationObject.pickable = mesh.isPickable;
  25177. serializationObject.receiveShadows = mesh.receiveShadows;
  25178. serializationObject.billboardMode = mesh.billboardMode;
  25179. serializationObject.visibility = mesh.visibility;
  25180. serializationObject.checkCollisions = mesh.checkCollisions;
  25181. // Parent
  25182. if (mesh.parent) {
  25183. serializationObject.parentId = mesh.parent.id;
  25184. }
  25185. // Geometry
  25186. var geometry = mesh._geometry;
  25187. if (geometry) {
  25188. var geometryId = geometry.id;
  25189. serializationObject.geometryId = geometryId;
  25190. if (!mesh.getScene().getGeometryByID(geometryId)) {
  25191. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  25192. serializeGeometry(geometry, serializationScene.geometries);
  25193. }
  25194. // SubMeshes
  25195. serializationObject.subMeshes = [];
  25196. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25197. var subMesh = mesh.subMeshes[subIndex];
  25198. serializationObject.subMeshes.push({
  25199. materialIndex: subMesh.materialIndex,
  25200. verticesStart: subMesh.verticesStart,
  25201. verticesCount: subMesh.verticesCount,
  25202. indexStart: subMesh.indexStart,
  25203. indexCount: subMesh.indexCount
  25204. });
  25205. }
  25206. }
  25207. // Material
  25208. if (mesh.material) {
  25209. serializationObject.materialId = mesh.material.id;
  25210. }
  25211. else {
  25212. mesh.material = null;
  25213. }
  25214. // Skeleton
  25215. if (mesh.skeleton) {
  25216. serializationObject.skeletonId = mesh.skeleton.id;
  25217. }
  25218. // Physics
  25219. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  25220. serializationObject.physicsMass = mesh.getPhysicsMass();
  25221. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  25222. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  25223. switch (mesh.getPhysicsImpostor()) {
  25224. case BABYLON.PhysicsEngine.BoxImpostor:
  25225. serializationObject.physicsImpostor = 1;
  25226. break;
  25227. case BABYLON.PhysicsEngine.SphereImpostor:
  25228. serializationObject.physicsImpostor = 2;
  25229. break;
  25230. }
  25231. }
  25232. // Instances
  25233. serializationObject.instances = [];
  25234. for (var index = 0; index < mesh.instances.length; index++) {
  25235. var instance = mesh.instances[index];
  25236. var serializationInstance = {
  25237. name: instance.name,
  25238. position: instance.position.asArray(),
  25239. rotation: instance.rotation.asArray(),
  25240. rotationQuaternion: instance.rotationQuaternion.asArray(),
  25241. scaling: instance.scaling.asArray()
  25242. };
  25243. serializationObject.instances.push(serializationInstance);
  25244. // Animations
  25245. appendAnimations(instance, serializationInstance);
  25246. }
  25247. // Animations
  25248. appendAnimations(mesh, serializationObject);
  25249. // Layer mask
  25250. serializationObject.layerMask = mesh.layerMask;
  25251. return serializationObject;
  25252. };
  25253. var finalizeSingleMesh = function (mesh, serializationObject) {
  25254. //only works if the mesh is already loaded
  25255. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  25256. //serialize material
  25257. if (mesh.material) {
  25258. if (mesh.material instanceof BABYLON.StandardMaterial) {
  25259. serializationObject.materials = serializationObject.materials || [];
  25260. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  25261. serializationObject.materials.push(serializeMaterial(mesh.material));
  25262. }
  25263. }
  25264. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  25265. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  25266. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  25267. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  25268. }
  25269. }
  25270. }
  25271. //serialize geometry
  25272. var geometry = mesh._geometry;
  25273. if (geometry) {
  25274. if (!serializationObject.geometries) {
  25275. serializationObject.geometries = {};
  25276. serializationObject.geometries.boxes = [];
  25277. serializationObject.geometries.spheres = [];
  25278. serializationObject.geometries.cylinders = [];
  25279. serializationObject.geometries.toruses = [];
  25280. serializationObject.geometries.grounds = [];
  25281. serializationObject.geometries.planes = [];
  25282. serializationObject.geometries.torusKnots = [];
  25283. serializationObject.geometries.vertexData = [];
  25284. }
  25285. serializeGeometry(geometry, serializationObject.geometries);
  25286. }
  25287. // Skeletons
  25288. if (mesh.skeleton) {
  25289. serializationObject.skeletons = serializationObject.skeletons || [];
  25290. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  25291. }
  25292. //serialize the actual mesh
  25293. serializationObject.meshes = serializationObject.meshes || [];
  25294. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  25295. }
  25296. };
  25297. var SceneSerializer = (function () {
  25298. function SceneSerializer() {
  25299. }
  25300. SceneSerializer.Serialize = function (scene) {
  25301. var serializationObject = {};
  25302. // Scene
  25303. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  25304. serializationObject.autoClear = scene.autoClear;
  25305. serializationObject.clearColor = scene.clearColor.asArray();
  25306. serializationObject.ambientColor = scene.ambientColor.asArray();
  25307. serializationObject.gravity = scene.gravity.asArray();
  25308. // Fog
  25309. if (scene.fogMode && scene.fogMode !== 0) {
  25310. serializationObject.fogMode = scene.fogMode;
  25311. serializationObject.fogColor = scene.fogColor.asArray();
  25312. serializationObject.fogStart = scene.fogStart;
  25313. serializationObject.fogEnd = scene.fogEnd;
  25314. serializationObject.fogDensity = scene.fogDensity;
  25315. }
  25316. // Lights
  25317. serializationObject.lights = [];
  25318. var index;
  25319. var light;
  25320. for (index = 0; index < scene.lights.length; index++) {
  25321. light = scene.lights[index];
  25322. serializationObject.lights.push(serializeLight(light));
  25323. }
  25324. // Cameras
  25325. serializationObject.cameras = [];
  25326. for (index = 0; index < scene.cameras.length; index++) {
  25327. var camera = scene.cameras[index];
  25328. serializationObject.cameras.push(serializeCamera(camera));
  25329. }
  25330. if (scene.activeCamera) {
  25331. serializationObject.activeCameraID = scene.activeCamera.id;
  25332. }
  25333. // Materials
  25334. serializationObject.materials = [];
  25335. serializationObject.multiMaterials = [];
  25336. var material;
  25337. for (index = 0; index < scene.materials.length; index++) {
  25338. material = scene.materials[index];
  25339. serializationObject.materials.push(serializeMaterial(material));
  25340. }
  25341. // MultiMaterials
  25342. serializationObject.multiMaterials = [];
  25343. for (index = 0; index < scene.multiMaterials.length; index++) {
  25344. var multiMaterial = scene.multiMaterials[index];
  25345. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  25346. }
  25347. for (index = 0; index < scene.materials.length; index++) {
  25348. material = scene.materials[index];
  25349. if (material instanceof BABYLON.StandardMaterial) {
  25350. serializationObject.materials.push(serializeMaterial(material));
  25351. }
  25352. else if (material instanceof BABYLON.MultiMaterial) {
  25353. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  25354. }
  25355. }
  25356. // Skeletons
  25357. serializationObject.skeletons = [];
  25358. for (index = 0; index < scene.skeletons.length; index++) {
  25359. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  25360. }
  25361. // Geometries
  25362. serializationObject.geometries = {};
  25363. serializationObject.geometries.boxes = [];
  25364. serializationObject.geometries.spheres = [];
  25365. serializationObject.geometries.cylinders = [];
  25366. serializationObject.geometries.toruses = [];
  25367. serializationObject.geometries.grounds = [];
  25368. serializationObject.geometries.planes = [];
  25369. serializationObject.geometries.torusKnots = [];
  25370. serializationObject.geometries.vertexData = [];
  25371. serializedGeometries = [];
  25372. var geometries = scene.getGeometries();
  25373. for (index = 0; index < geometries.length; index++) {
  25374. var geometry = geometries[index];
  25375. if (geometry.isReady()) {
  25376. serializeGeometry(geometry, serializationObject.geometries);
  25377. }
  25378. }
  25379. // Meshes
  25380. serializationObject.meshes = [];
  25381. for (index = 0; index < scene.meshes.length; index++) {
  25382. var abstractMesh = scene.meshes[index];
  25383. if (abstractMesh instanceof BABYLON.Mesh) {
  25384. var mesh = abstractMesh;
  25385. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  25386. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  25387. }
  25388. }
  25389. }
  25390. // Particles Systems
  25391. serializationObject.particleSystems = [];
  25392. for (index = 0; index < scene.particleSystems.length; index++) {
  25393. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  25394. }
  25395. // Lens flares
  25396. serializationObject.lensFlareSystems = [];
  25397. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  25398. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  25399. }
  25400. // Shadows
  25401. serializationObject.shadowGenerators = [];
  25402. for (index = 0; index < scene.lights.length; index++) {
  25403. light = scene.lights[index];
  25404. if (light.getShadowGenerator()) {
  25405. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  25406. }
  25407. }
  25408. return serializationObject;
  25409. };
  25410. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  25411. if (withParents === void 0) { withParents = false; }
  25412. if (withChildren === void 0) { withChildren = false; }
  25413. var serializationObject = {};
  25414. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  25415. if (withParents || withChildren) {
  25416. //deliberate for loop! not for each, appended should be processed as well.
  25417. for (var i = 0; i < toSerialize.length; ++i) {
  25418. if (withChildren) {
  25419. toSerialize[i].getDescendants().forEach(function (node) {
  25420. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  25421. toSerialize.push(node);
  25422. }
  25423. });
  25424. }
  25425. //make sure the array doesn't contain the object already
  25426. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  25427. toSerialize.push(toSerialize[i].parent);
  25428. }
  25429. }
  25430. }
  25431. toSerialize.forEach(function (mesh) {
  25432. finalizeSingleMesh(mesh, serializationObject);
  25433. });
  25434. return serializationObject;
  25435. };
  25436. return SceneSerializer;
  25437. })();
  25438. BABYLON.SceneSerializer = SceneSerializer;
  25439. })(BABYLON || (BABYLON = {}));
  25440. var BABYLON;
  25441. (function (BABYLON) {
  25442. // Unique ID when we import meshes from Babylon to CSG
  25443. var currentCSGMeshId = 0;
  25444. // # class Vertex
  25445. // Represents a vertex of a polygon. Use your own vertex class instead of this
  25446. // one to provide additional features like texture coordinates and vertex
  25447. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  25448. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  25449. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  25450. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  25451. // is not used anywhere else.
  25452. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  25453. var Vertex = (function () {
  25454. function Vertex(pos, normal, uv) {
  25455. this.pos = pos;
  25456. this.normal = normal;
  25457. this.uv = uv;
  25458. }
  25459. Vertex.prototype.clone = function () {
  25460. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  25461. };
  25462. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  25463. // orientation of a polygon is flipped.
  25464. Vertex.prototype.flip = function () {
  25465. this.normal = this.normal.scale(-1);
  25466. };
  25467. // Create a new vertex between this vertex and `other` by linearly
  25468. // interpolating all properties using a parameter of `t`. Subclasses should
  25469. // override this to interpolate additional properties.
  25470. Vertex.prototype.interpolate = function (other, t) {
  25471. 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));
  25472. };
  25473. return Vertex;
  25474. })();
  25475. // # class Plane
  25476. // Represents a plane in 3D space.
  25477. var Plane = (function () {
  25478. function Plane(normal, w) {
  25479. this.normal = normal;
  25480. this.w = w;
  25481. }
  25482. Plane.FromPoints = function (a, b, c) {
  25483. var v0 = c.subtract(a);
  25484. var v1 = b.subtract(a);
  25485. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  25486. return null;
  25487. }
  25488. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  25489. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  25490. };
  25491. Plane.prototype.clone = function () {
  25492. return new Plane(this.normal.clone(), this.w);
  25493. };
  25494. Plane.prototype.flip = function () {
  25495. this.normal.scaleInPlace(-1);
  25496. this.w = -this.w;
  25497. };
  25498. // Split `polygon` by this plane if needed, then put the polygon or polygon
  25499. // fragments in the appropriate lists. Coplanar polygons go into either
  25500. // `coplanarFront` or `coplanarBack` depending on their orientation with
  25501. // respect to this plane. Polygons in front or in back of this plane go into
  25502. // either `front` or `back`.
  25503. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  25504. var COPLANAR = 0;
  25505. var FRONT = 1;
  25506. var BACK = 2;
  25507. var SPANNING = 3;
  25508. // Classify each point as well as the entire polygon into one of the above
  25509. // four classes.
  25510. var polygonType = 0;
  25511. var types = [];
  25512. for (var i = 0; i < polygon.vertices.length; i++) {
  25513. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  25514. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  25515. polygonType |= type;
  25516. types.push(type);
  25517. }
  25518. // Put the polygon in the correct list, splitting it when necessary.
  25519. switch (polygonType) {
  25520. case COPLANAR:
  25521. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  25522. break;
  25523. case FRONT:
  25524. front.push(polygon);
  25525. break;
  25526. case BACK:
  25527. back.push(polygon);
  25528. break;
  25529. case SPANNING:
  25530. var f = [], b = [];
  25531. for (i = 0; i < polygon.vertices.length; i++) {
  25532. var j = (i + 1) % polygon.vertices.length;
  25533. var ti = types[i], tj = types[j];
  25534. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  25535. if (ti != BACK)
  25536. f.push(vi);
  25537. if (ti != FRONT)
  25538. b.push(ti != BACK ? vi.clone() : vi);
  25539. if ((ti | tj) == SPANNING) {
  25540. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  25541. var v = vi.interpolate(vj, t);
  25542. f.push(v);
  25543. b.push(v.clone());
  25544. }
  25545. }
  25546. if (f.length >= 3) {
  25547. var poly = new Polygon(f, polygon.shared);
  25548. if (poly.plane)
  25549. front.push(poly);
  25550. }
  25551. if (b.length >= 3) {
  25552. poly = new Polygon(b, polygon.shared);
  25553. if (poly.plane)
  25554. back.push(poly);
  25555. }
  25556. break;
  25557. }
  25558. };
  25559. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  25560. // point is on the plane.
  25561. Plane.EPSILON = 1e-5;
  25562. return Plane;
  25563. })();
  25564. // # class Polygon
  25565. // Represents a convex polygon. The vertices used to initialize a polygon must
  25566. // be coplanar and form a convex loop.
  25567. //
  25568. // Each convex polygon has a `shared` property, which is shared between all
  25569. // polygons that are clones of each other or were split from the same polygon.
  25570. // This can be used to define per-polygon properties (such as surface color).
  25571. var Polygon = (function () {
  25572. function Polygon(vertices, shared) {
  25573. this.vertices = vertices;
  25574. this.shared = shared;
  25575. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  25576. }
  25577. Polygon.prototype.clone = function () {
  25578. var vertices = this.vertices.map(function (v) { return v.clone(); });
  25579. return new Polygon(vertices, this.shared);
  25580. };
  25581. Polygon.prototype.flip = function () {
  25582. this.vertices.reverse().map(function (v) { v.flip(); });
  25583. this.plane.flip();
  25584. };
  25585. return Polygon;
  25586. })();
  25587. // # class Node
  25588. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  25589. // by picking a polygon to split along. That polygon (and all other coplanar
  25590. // polygons) are added directly to that node and the other polygons are added to
  25591. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  25592. // no distinction between internal and leaf nodes.
  25593. var Node = (function () {
  25594. function Node(polygons) {
  25595. this.plane = null;
  25596. this.front = null;
  25597. this.back = null;
  25598. this.polygons = [];
  25599. if (polygons) {
  25600. this.build(polygons);
  25601. }
  25602. }
  25603. Node.prototype.clone = function () {
  25604. var node = new Node();
  25605. node.plane = this.plane && this.plane.clone();
  25606. node.front = this.front && this.front.clone();
  25607. node.back = this.back && this.back.clone();
  25608. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  25609. return node;
  25610. };
  25611. // Convert solid space to empty space and empty space to solid space.
  25612. Node.prototype.invert = function () {
  25613. for (var i = 0; i < this.polygons.length; i++) {
  25614. this.polygons[i].flip();
  25615. }
  25616. if (this.plane) {
  25617. this.plane.flip();
  25618. }
  25619. if (this.front) {
  25620. this.front.invert();
  25621. }
  25622. if (this.back) {
  25623. this.back.invert();
  25624. }
  25625. var temp = this.front;
  25626. this.front = this.back;
  25627. this.back = temp;
  25628. };
  25629. // Recursively remove all polygons in `polygons` that are inside this BSP
  25630. // tree.
  25631. Node.prototype.clipPolygons = function (polygons) {
  25632. if (!this.plane)
  25633. return polygons.slice();
  25634. var front = [], back = [];
  25635. for (var i = 0; i < polygons.length; i++) {
  25636. this.plane.splitPolygon(polygons[i], front, back, front, back);
  25637. }
  25638. if (this.front) {
  25639. front = this.front.clipPolygons(front);
  25640. }
  25641. if (this.back) {
  25642. back = this.back.clipPolygons(back);
  25643. }
  25644. else {
  25645. back = [];
  25646. }
  25647. return front.concat(back);
  25648. };
  25649. // Remove all polygons in this BSP tree that are inside the other BSP tree
  25650. // `bsp`.
  25651. Node.prototype.clipTo = function (bsp) {
  25652. this.polygons = bsp.clipPolygons(this.polygons);
  25653. if (this.front)
  25654. this.front.clipTo(bsp);
  25655. if (this.back)
  25656. this.back.clipTo(bsp);
  25657. };
  25658. // Return a list of all polygons in this BSP tree.
  25659. Node.prototype.allPolygons = function () {
  25660. var polygons = this.polygons.slice();
  25661. if (this.front)
  25662. polygons = polygons.concat(this.front.allPolygons());
  25663. if (this.back)
  25664. polygons = polygons.concat(this.back.allPolygons());
  25665. return polygons;
  25666. };
  25667. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  25668. // new polygons are filtered down to the bottom of the tree and become new
  25669. // nodes there. Each set of polygons is partitioned using the first polygon
  25670. // (no heuristic is used to pick a good split).
  25671. Node.prototype.build = function (polygons) {
  25672. if (!polygons.length)
  25673. return;
  25674. if (!this.plane)
  25675. this.plane = polygons[0].plane.clone();
  25676. var front = [], back = [];
  25677. for (var i = 0; i < polygons.length; i++) {
  25678. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  25679. }
  25680. if (front.length) {
  25681. if (!this.front)
  25682. this.front = new Node();
  25683. this.front.build(front);
  25684. }
  25685. if (back.length) {
  25686. if (!this.back)
  25687. this.back = new Node();
  25688. this.back.build(back);
  25689. }
  25690. };
  25691. return Node;
  25692. })();
  25693. var CSG = (function () {
  25694. function CSG() {
  25695. this.polygons = new Array();
  25696. }
  25697. // Convert BABYLON.Mesh to BABYLON.CSG
  25698. CSG.FromMesh = function (mesh) {
  25699. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  25700. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  25701. if (mesh instanceof BABYLON.Mesh) {
  25702. mesh.computeWorldMatrix(true);
  25703. matrix = mesh.getWorldMatrix();
  25704. meshPosition = mesh.position.clone();
  25705. meshRotation = mesh.rotation.clone();
  25706. if (mesh.rotationQuaternion) {
  25707. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  25708. }
  25709. meshScaling = mesh.scaling.clone();
  25710. }
  25711. else {
  25712. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  25713. }
  25714. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25715. var subMeshes = mesh.subMeshes;
  25716. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  25717. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  25718. vertices = [];
  25719. for (var j = 0; j < 3; j++) {
  25720. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  25721. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  25722. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  25723. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  25724. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  25725. vertex = new Vertex(position, normal, uv);
  25726. vertices.push(vertex);
  25727. }
  25728. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  25729. // To handle the case of degenerated triangle
  25730. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  25731. if (polygon.plane)
  25732. polygons.push(polygon);
  25733. }
  25734. }
  25735. var csg = CSG.FromPolygons(polygons);
  25736. csg.matrix = matrix;
  25737. csg.position = meshPosition;
  25738. csg.rotation = meshRotation;
  25739. csg.scaling = meshScaling;
  25740. csg.rotationQuaternion = meshRotationQuaternion;
  25741. currentCSGMeshId++;
  25742. return csg;
  25743. };
  25744. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  25745. CSG.FromPolygons = function (polygons) {
  25746. var csg = new CSG();
  25747. csg.polygons = polygons;
  25748. return csg;
  25749. };
  25750. CSG.prototype.clone = function () {
  25751. var csg = new CSG();
  25752. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  25753. csg.copyTransformAttributes(this);
  25754. return csg;
  25755. };
  25756. CSG.prototype.toPolygons = function () {
  25757. return this.polygons;
  25758. };
  25759. CSG.prototype.union = function (csg) {
  25760. var a = new Node(this.clone().polygons);
  25761. var b = new Node(csg.clone().polygons);
  25762. a.clipTo(b);
  25763. b.clipTo(a);
  25764. b.invert();
  25765. b.clipTo(a);
  25766. b.invert();
  25767. a.build(b.allPolygons());
  25768. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25769. };
  25770. CSG.prototype.unionInPlace = function (csg) {
  25771. var a = new Node(this.polygons);
  25772. var b = new Node(csg.polygons);
  25773. a.clipTo(b);
  25774. b.clipTo(a);
  25775. b.invert();
  25776. b.clipTo(a);
  25777. b.invert();
  25778. a.build(b.allPolygons());
  25779. this.polygons = a.allPolygons();
  25780. };
  25781. CSG.prototype.subtract = function (csg) {
  25782. var a = new Node(this.clone().polygons);
  25783. var b = new Node(csg.clone().polygons);
  25784. a.invert();
  25785. a.clipTo(b);
  25786. b.clipTo(a);
  25787. b.invert();
  25788. b.clipTo(a);
  25789. b.invert();
  25790. a.build(b.allPolygons());
  25791. a.invert();
  25792. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25793. };
  25794. CSG.prototype.subtractInPlace = function (csg) {
  25795. var a = new Node(this.polygons);
  25796. var b = new Node(csg.polygons);
  25797. a.invert();
  25798. a.clipTo(b);
  25799. b.clipTo(a);
  25800. b.invert();
  25801. b.clipTo(a);
  25802. b.invert();
  25803. a.build(b.allPolygons());
  25804. a.invert();
  25805. this.polygons = a.allPolygons();
  25806. };
  25807. CSG.prototype.intersect = function (csg) {
  25808. var a = new Node(this.clone().polygons);
  25809. var b = new Node(csg.clone().polygons);
  25810. a.invert();
  25811. b.clipTo(a);
  25812. b.invert();
  25813. a.clipTo(b);
  25814. b.clipTo(a);
  25815. a.build(b.allPolygons());
  25816. a.invert();
  25817. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25818. };
  25819. CSG.prototype.intersectInPlace = function (csg) {
  25820. var a = new Node(this.polygons);
  25821. var b = new Node(csg.polygons);
  25822. a.invert();
  25823. b.clipTo(a);
  25824. b.invert();
  25825. a.clipTo(b);
  25826. b.clipTo(a);
  25827. a.build(b.allPolygons());
  25828. a.invert();
  25829. this.polygons = a.allPolygons();
  25830. };
  25831. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25832. // not modified.
  25833. CSG.prototype.inverse = function () {
  25834. var csg = this.clone();
  25835. csg.inverseInPlace();
  25836. return csg;
  25837. };
  25838. CSG.prototype.inverseInPlace = function () {
  25839. this.polygons.map(function (p) { p.flip(); });
  25840. };
  25841. // This is used to keep meshes transformations so they can be restored
  25842. // when we build back a Babylon Mesh
  25843. // NB : All CSG operations are performed in world coordinates
  25844. CSG.prototype.copyTransformAttributes = function (csg) {
  25845. this.matrix = csg.matrix;
  25846. this.position = csg.position;
  25847. this.rotation = csg.rotation;
  25848. this.scaling = csg.scaling;
  25849. this.rotationQuaternion = csg.rotationQuaternion;
  25850. return this;
  25851. };
  25852. // Build Raw mesh from CSG
  25853. // Coordinates here are in world space
  25854. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25855. var matrix = this.matrix.clone();
  25856. matrix.invert();
  25857. 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;
  25858. if (keepSubMeshes) {
  25859. // Sort Polygons, since subMeshes are indices range
  25860. polygons.sort(function (a, b) {
  25861. if (a.shared.meshId === b.shared.meshId) {
  25862. return a.shared.subMeshId - b.shared.subMeshId;
  25863. }
  25864. else {
  25865. return a.shared.meshId - b.shared.meshId;
  25866. }
  25867. });
  25868. }
  25869. for (var i = 0, il = polygons.length; i < il; i++) {
  25870. polygon = polygons[i];
  25871. // Building SubMeshes
  25872. if (!subMesh_dict[polygon.shared.meshId]) {
  25873. subMesh_dict[polygon.shared.meshId] = {};
  25874. }
  25875. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25876. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25877. indexStart: +Infinity,
  25878. indexEnd: -Infinity,
  25879. materialIndex: polygon.shared.materialIndex
  25880. };
  25881. }
  25882. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25883. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25884. polygonIndices[0] = 0;
  25885. polygonIndices[1] = j - 1;
  25886. polygonIndices[2] = j;
  25887. for (var k = 0; k < 3; k++) {
  25888. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25889. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25890. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25891. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25892. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25893. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25894. // Check if 2 points can be merged
  25895. if (!(typeof vertex_idx !== 'undefined' &&
  25896. normals[vertex_idx * 3] === localNormal.x &&
  25897. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25898. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25899. uvs[vertex_idx * 2] === uv.x &&
  25900. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25901. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25902. uvs.push(uv.x, uv.y);
  25903. normals.push(normal.x, normal.y, normal.z);
  25904. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25905. }
  25906. indices.push(vertex_idx);
  25907. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25908. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25909. currentIndex++;
  25910. }
  25911. }
  25912. }
  25913. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25914. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25915. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25916. mesh.setIndices(indices);
  25917. if (keepSubMeshes) {
  25918. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25919. var materialIndexOffset = 0, materialMaxIndex;
  25920. mesh.subMeshes.length = 0;
  25921. for (var m in subMesh_dict) {
  25922. materialMaxIndex = -1;
  25923. for (var sm in subMesh_dict[m]) {
  25924. subMesh_obj = subMesh_dict[m][sm];
  25925. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25926. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25927. }
  25928. materialIndexOffset += ++materialMaxIndex;
  25929. }
  25930. }
  25931. return mesh;
  25932. };
  25933. // Build Mesh from CSG taking material and transforms into account
  25934. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25935. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25936. mesh.material = material;
  25937. mesh.position.copyFrom(this.position);
  25938. mesh.rotation.copyFrom(this.rotation);
  25939. if (this.rotationQuaternion) {
  25940. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25941. }
  25942. mesh.scaling.copyFrom(this.scaling);
  25943. mesh.computeWorldMatrix(true);
  25944. return mesh;
  25945. };
  25946. return CSG;
  25947. })();
  25948. BABYLON.CSG = CSG;
  25949. })(BABYLON || (BABYLON = {}));
  25950. var BABYLON;
  25951. (function (BABYLON) {
  25952. var VRDistortionCorrectionPostProcess = (function (_super) {
  25953. __extends(VRDistortionCorrectionPostProcess, _super);
  25954. //ANY
  25955. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25956. var _this = this;
  25957. _super.call(this, name, "vrDistortionCorrection", [
  25958. 'LensCenter',
  25959. 'Scale',
  25960. 'ScaleIn',
  25961. 'HmdWarpParam'
  25962. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25963. this._isRightEye = isRightEye;
  25964. this._distortionFactors = vrMetrics.distortionK;
  25965. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25966. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25967. this.onSizeChanged = function () {
  25968. _this.aspectRatio = _this.width * .5 / _this.height;
  25969. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25970. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25971. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25972. };
  25973. this.onApply = function (effect) {
  25974. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25975. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25976. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25977. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25978. };
  25979. }
  25980. return VRDistortionCorrectionPostProcess;
  25981. })(BABYLON.PostProcess);
  25982. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25983. })(BABYLON || (BABYLON = {}));
  25984. // Mainly based on these 2 articles :
  25985. // 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
  25986. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25987. var BABYLON;
  25988. (function (BABYLON) {
  25989. (function (JoystickAxis) {
  25990. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25991. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25992. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25993. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25994. var JoystickAxis = BABYLON.JoystickAxis;
  25995. var VirtualJoystick = (function () {
  25996. function VirtualJoystick(leftJoystick) {
  25997. var _this = this;
  25998. if (leftJoystick) {
  25999. this._leftJoystick = true;
  26000. }
  26001. else {
  26002. this._leftJoystick = false;
  26003. }
  26004. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  26005. VirtualJoystick._globalJoystickIndex++;
  26006. // By default left & right arrow keys are moving the X
  26007. // and up & down keys are moving the Y
  26008. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  26009. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  26010. this.reverseLeftRight = false;
  26011. this.reverseUpDown = false;
  26012. // collections of pointers
  26013. this._touches = new BABYLON.SmartCollection();
  26014. this.deltaPosition = BABYLON.Vector3.Zero();
  26015. this._joystickSensibility = 25;
  26016. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  26017. this._rotationSpeed = 25;
  26018. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  26019. this._rotateOnAxisRelativeToMesh = false;
  26020. this._onResize = function (evt) {
  26021. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  26022. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  26023. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  26024. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  26025. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  26026. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  26027. };
  26028. // injecting a canvas element on top of the canvas 3D game
  26029. if (!VirtualJoystick.vjCanvas) {
  26030. window.addEventListener("resize", this._onResize, false);
  26031. VirtualJoystick.vjCanvas = document.createElement("canvas");
  26032. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  26033. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  26034. VirtualJoystick.vjCanvas.width = window.innerWidth;
  26035. VirtualJoystick.vjCanvas.height = window.innerHeight;
  26036. VirtualJoystick.vjCanvas.style.width = "100%";
  26037. VirtualJoystick.vjCanvas.style.height = "100%";
  26038. VirtualJoystick.vjCanvas.style.position = "absolute";
  26039. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  26040. VirtualJoystick.vjCanvas.style.top = "0px";
  26041. VirtualJoystick.vjCanvas.style.left = "0px";
  26042. VirtualJoystick.vjCanvas.style.zIndex = "5";
  26043. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  26044. // Support for jQuery PEP polyfill
  26045. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  26046. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  26047. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  26048. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  26049. document.body.appendChild(VirtualJoystick.vjCanvas);
  26050. }
  26051. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  26052. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  26053. this.pressed = false;
  26054. // default joystick color
  26055. this._joystickColor = "cyan";
  26056. this._joystickPointerID = -1;
  26057. // current joystick position
  26058. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  26059. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  26060. // origin joystick position
  26061. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  26062. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  26063. this._onPointerDownHandlerRef = function (evt) {
  26064. _this._onPointerDown(evt);
  26065. };
  26066. this._onPointerMoveHandlerRef = function (evt) {
  26067. _this._onPointerMove(evt);
  26068. };
  26069. this._onPointerOutHandlerRef = function (evt) {
  26070. _this._onPointerUp(evt);
  26071. };
  26072. this._onPointerUpHandlerRef = function (evt) {
  26073. _this._onPointerUp(evt);
  26074. };
  26075. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  26076. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  26077. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  26078. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  26079. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  26080. evt.preventDefault(); // Disables system menu
  26081. }, false);
  26082. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  26083. }
  26084. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  26085. this._joystickSensibility = newJoystickSensibility;
  26086. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  26087. };
  26088. VirtualJoystick.prototype._onPointerDown = function (e) {
  26089. var positionOnScreenCondition;
  26090. e.preventDefault();
  26091. if (this._leftJoystick === true) {
  26092. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  26093. }
  26094. else {
  26095. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  26096. }
  26097. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  26098. // First contact will be dedicated to the virtual joystick
  26099. this._joystickPointerID = e.pointerId;
  26100. this._joystickPointerStartPos.x = e.clientX;
  26101. this._joystickPointerStartPos.y = e.clientY;
  26102. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  26103. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  26104. this._deltaJoystickVector.x = 0;
  26105. this._deltaJoystickVector.y = 0;
  26106. this.pressed = true;
  26107. this._touches.add(e.pointerId.toString(), e);
  26108. }
  26109. else {
  26110. // You can only trigger the action buttons with a joystick declared
  26111. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  26112. this._action();
  26113. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  26114. }
  26115. }
  26116. };
  26117. VirtualJoystick.prototype._onPointerMove = function (e) {
  26118. // If the current pointer is the one associated to the joystick (first touch contact)
  26119. if (this._joystickPointerID == e.pointerId) {
  26120. this._joystickPointerPos.x = e.clientX;
  26121. this._joystickPointerPos.y = e.clientY;
  26122. this._deltaJoystickVector = this._joystickPointerPos.clone();
  26123. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  26124. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  26125. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  26126. switch (this._axisTargetedByLeftAndRight) {
  26127. case JoystickAxis.X:
  26128. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  26129. break;
  26130. case JoystickAxis.Y:
  26131. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  26132. break;
  26133. case JoystickAxis.Z:
  26134. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  26135. break;
  26136. }
  26137. var directionUpDown = this.reverseUpDown ? 1 : -1;
  26138. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  26139. switch (this._axisTargetedByUpAndDown) {
  26140. case JoystickAxis.X:
  26141. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  26142. break;
  26143. case JoystickAxis.Y:
  26144. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  26145. break;
  26146. case JoystickAxis.Z:
  26147. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  26148. break;
  26149. }
  26150. }
  26151. else {
  26152. if (this._touches.item(e.pointerId.toString())) {
  26153. this._touches.item(e.pointerId.toString()).x = e.clientX;
  26154. this._touches.item(e.pointerId.toString()).y = e.clientY;
  26155. }
  26156. }
  26157. };
  26158. VirtualJoystick.prototype._onPointerUp = function (e) {
  26159. if (this._joystickPointerID == e.pointerId) {
  26160. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  26161. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  26162. this._joystickPointerID = -1;
  26163. this.pressed = false;
  26164. }
  26165. else {
  26166. var touch = this._touches.item(e.pointerId.toString());
  26167. if (touch) {
  26168. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  26169. }
  26170. }
  26171. this._deltaJoystickVector.x = 0;
  26172. this._deltaJoystickVector.y = 0;
  26173. this._touches.remove(e.pointerId.toString());
  26174. };
  26175. /**
  26176. * Change the color of the virtual joystick
  26177. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  26178. */
  26179. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  26180. this._joystickColor = newColor;
  26181. };
  26182. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  26183. this._action = action;
  26184. };
  26185. // Define which axis you'd like to control for left & right
  26186. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  26187. switch (axis) {
  26188. case JoystickAxis.X:
  26189. case JoystickAxis.Y:
  26190. case JoystickAxis.Z:
  26191. this._axisTargetedByLeftAndRight = axis;
  26192. break;
  26193. default:
  26194. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  26195. break;
  26196. }
  26197. };
  26198. // Define which axis you'd like to control for up & down
  26199. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  26200. switch (axis) {
  26201. case JoystickAxis.X:
  26202. case JoystickAxis.Y:
  26203. case JoystickAxis.Z:
  26204. this._axisTargetedByUpAndDown = axis;
  26205. break;
  26206. default:
  26207. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  26208. break;
  26209. }
  26210. };
  26211. VirtualJoystick.prototype._clearCanvas = function () {
  26212. if (this._leftJoystick) {
  26213. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  26214. }
  26215. else {
  26216. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  26217. }
  26218. };
  26219. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  26220. var _this = this;
  26221. if (this.pressed) {
  26222. this._touches.forEach(function (touch) {
  26223. if (touch.pointerId === _this._joystickPointerID) {
  26224. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  26225. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  26226. VirtualJoystick.vjCanvasContext.beginPath();
  26227. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  26228. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26229. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  26230. VirtualJoystick.vjCanvasContext.stroke();
  26231. VirtualJoystick.vjCanvasContext.closePath();
  26232. VirtualJoystick.vjCanvasContext.beginPath();
  26233. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26234. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  26235. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  26236. VirtualJoystick.vjCanvasContext.stroke();
  26237. VirtualJoystick.vjCanvasContext.closePath();
  26238. VirtualJoystick.vjCanvasContext.beginPath();
  26239. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26240. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  26241. VirtualJoystick.vjCanvasContext.stroke();
  26242. VirtualJoystick.vjCanvasContext.closePath();
  26243. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  26244. }
  26245. else {
  26246. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  26247. VirtualJoystick.vjCanvasContext.beginPath();
  26248. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  26249. VirtualJoystick.vjCanvasContext.beginPath();
  26250. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  26251. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  26252. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  26253. VirtualJoystick.vjCanvasContext.stroke();
  26254. VirtualJoystick.vjCanvasContext.closePath();
  26255. touch.prevX = touch.x;
  26256. touch.prevY = touch.y;
  26257. }
  26258. ;
  26259. });
  26260. }
  26261. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  26262. };
  26263. VirtualJoystick.prototype.releaseCanvas = function () {
  26264. if (VirtualJoystick.vjCanvas) {
  26265. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  26266. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  26267. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  26268. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  26269. window.removeEventListener("resize", this._onResize);
  26270. document.body.removeChild(VirtualJoystick.vjCanvas);
  26271. VirtualJoystick.vjCanvas = null;
  26272. }
  26273. };
  26274. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  26275. VirtualJoystick._globalJoystickIndex = 0;
  26276. return VirtualJoystick;
  26277. })();
  26278. BABYLON.VirtualJoystick = VirtualJoystick;
  26279. })(BABYLON || (BABYLON = {}));
  26280. var BABYLON;
  26281. (function (BABYLON) {
  26282. // We're mainly based on the logic defined into the FreeCamera code
  26283. var VirtualJoysticksCamera = (function (_super) {
  26284. __extends(VirtualJoysticksCamera, _super);
  26285. function VirtualJoysticksCamera(name, position, scene) {
  26286. _super.call(this, name, position, scene);
  26287. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  26288. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  26289. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  26290. this._leftjoystick.setJoystickSensibility(0.15);
  26291. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  26292. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  26293. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  26294. this._rightjoystick.reverseUpDown = true;
  26295. this._rightjoystick.setJoystickSensibility(0.05);
  26296. this._rightjoystick.setJoystickColor("yellow");
  26297. }
  26298. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  26299. return this._leftjoystick;
  26300. };
  26301. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  26302. return this._rightjoystick;
  26303. };
  26304. VirtualJoysticksCamera.prototype._checkInputs = function () {
  26305. var speed = this._computeLocalCameraSpeed() * 50;
  26306. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26307. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  26308. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26309. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  26310. if (!this._leftjoystick.pressed) {
  26311. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  26312. }
  26313. if (!this._rightjoystick.pressed) {
  26314. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  26315. }
  26316. _super.prototype._checkInputs.call(this);
  26317. };
  26318. VirtualJoysticksCamera.prototype.dispose = function () {
  26319. this._leftjoystick.releaseCanvas();
  26320. _super.prototype.dispose.call(this);
  26321. };
  26322. return VirtualJoysticksCamera;
  26323. })(BABYLON.FreeCamera);
  26324. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  26325. })(BABYLON || (BABYLON = {}));
  26326. var BABYLON;
  26327. (function (BABYLON) {
  26328. var ShaderMaterial = (function (_super) {
  26329. __extends(ShaderMaterial, _super);
  26330. function ShaderMaterial(name, scene, shaderPath, options) {
  26331. _super.call(this, name, scene);
  26332. this._textures = new Array();
  26333. this._floats = new Array();
  26334. this._floatsArrays = {};
  26335. this._colors3 = new Array();
  26336. this._colors4 = new Array();
  26337. this._vectors2 = new Array();
  26338. this._vectors3 = new Array();
  26339. this._vectors4 = new Array();
  26340. this._matrices = new Array();
  26341. this._matrices3x3 = new Array();
  26342. this._matrices2x2 = new Array();
  26343. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  26344. this._shaderPath = shaderPath;
  26345. options.needAlphaBlending = options.needAlphaBlending || false;
  26346. options.needAlphaTesting = options.needAlphaTesting || false;
  26347. options.attributes = options.attributes || ["position", "normal", "uv"];
  26348. options.uniforms = options.uniforms || ["worldViewProjection"];
  26349. options.samplers = options.samplers || [];
  26350. options.defines = options.defines || [];
  26351. this._options = options;
  26352. }
  26353. ShaderMaterial.prototype.needAlphaBlending = function () {
  26354. return this._options.needAlphaBlending;
  26355. };
  26356. ShaderMaterial.prototype.needAlphaTesting = function () {
  26357. return this._options.needAlphaTesting;
  26358. };
  26359. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  26360. if (this._options.uniforms.indexOf(uniformName) === -1) {
  26361. this._options.uniforms.push(uniformName);
  26362. }
  26363. };
  26364. ShaderMaterial.prototype.setTexture = function (name, texture) {
  26365. if (this._options.samplers.indexOf(name) === -1) {
  26366. this._options.samplers.push(name);
  26367. }
  26368. this._textures[name] = texture;
  26369. return this;
  26370. };
  26371. ShaderMaterial.prototype.setFloat = function (name, value) {
  26372. this._checkUniform(name);
  26373. this._floats[name] = value;
  26374. return this;
  26375. };
  26376. ShaderMaterial.prototype.setFloats = function (name, value) {
  26377. this._checkUniform(name);
  26378. this._floatsArrays[name] = value;
  26379. return this;
  26380. };
  26381. ShaderMaterial.prototype.setColor3 = function (name, value) {
  26382. this._checkUniform(name);
  26383. this._colors3[name] = value;
  26384. return this;
  26385. };
  26386. ShaderMaterial.prototype.setColor4 = function (name, value) {
  26387. this._checkUniform(name);
  26388. this._colors4[name] = value;
  26389. return this;
  26390. };
  26391. ShaderMaterial.prototype.setVector2 = function (name, value) {
  26392. this._checkUniform(name);
  26393. this._vectors2[name] = value;
  26394. return this;
  26395. };
  26396. ShaderMaterial.prototype.setVector3 = function (name, value) {
  26397. this._checkUniform(name);
  26398. this._vectors3[name] = value;
  26399. return this;
  26400. };
  26401. ShaderMaterial.prototype.setVector4 = function (name, value) {
  26402. this._checkUniform(name);
  26403. this._vectors4[name] = value;
  26404. return this;
  26405. };
  26406. ShaderMaterial.prototype.setMatrix = function (name, value) {
  26407. this._checkUniform(name);
  26408. this._matrices[name] = value;
  26409. return this;
  26410. };
  26411. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  26412. this._checkUniform(name);
  26413. this._matrices3x3[name] = value;
  26414. return this;
  26415. };
  26416. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  26417. this._checkUniform(name);
  26418. this._matrices2x2[name] = value;
  26419. return this;
  26420. };
  26421. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  26422. var scene = this.getScene();
  26423. var engine = scene.getEngine();
  26424. if (!this.checkReadyOnEveryCall) {
  26425. if (this._renderId === scene.getRenderId()) {
  26426. return true;
  26427. }
  26428. }
  26429. // Instances
  26430. var defines = [];
  26431. var fallbacks = new BABYLON.EffectFallbacks();
  26432. if (useInstances) {
  26433. defines.push("#define INSTANCES");
  26434. }
  26435. for (var index = 0; index < this._options.defines.length; index++) {
  26436. defines.push(this._options.defines[index]);
  26437. }
  26438. // Bones
  26439. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26440. defines.push("#define BONES");
  26441. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26442. defines.push("#define BONES4");
  26443. fallbacks.addFallback(0, "BONES4");
  26444. }
  26445. // Alpha test
  26446. if (engine.getAlphaTesting()) {
  26447. defines.push("#define ALPHATEST");
  26448. }
  26449. var previousEffect = this._effect;
  26450. var join = defines.join("\n");
  26451. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  26452. if (!this._effect.isReady()) {
  26453. return false;
  26454. }
  26455. if (previousEffect !== this._effect) {
  26456. scene.resetCachedMaterial();
  26457. }
  26458. this._renderId = scene.getRenderId();
  26459. return true;
  26460. };
  26461. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26462. var scene = this.getScene();
  26463. if (this._options.uniforms.indexOf("world") !== -1) {
  26464. this._effect.setMatrix("world", world);
  26465. }
  26466. if (this._options.uniforms.indexOf("worldView") !== -1) {
  26467. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  26468. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  26469. }
  26470. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  26471. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  26472. }
  26473. };
  26474. ShaderMaterial.prototype.bind = function (world, mesh) {
  26475. // Std values
  26476. this.bindOnlyWorldMatrix(world);
  26477. if (this.getScene().getCachedMaterial() !== this) {
  26478. if (this._options.uniforms.indexOf("view") !== -1) {
  26479. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  26480. }
  26481. if (this._options.uniforms.indexOf("projection") !== -1) {
  26482. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  26483. }
  26484. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  26485. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  26486. }
  26487. // Bones
  26488. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26489. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26490. }
  26491. // Texture
  26492. for (var name in this._textures) {
  26493. this._effect.setTexture(name, this._textures[name]);
  26494. }
  26495. // Float
  26496. for (name in this._floats) {
  26497. this._effect.setFloat(name, this._floats[name]);
  26498. }
  26499. // Float s
  26500. for (name in this._floatsArrays) {
  26501. this._effect.setArray(name, this._floatsArrays[name]);
  26502. }
  26503. // Color3
  26504. for (name in this._colors3) {
  26505. this._effect.setColor3(name, this._colors3[name]);
  26506. }
  26507. // Color4
  26508. for (name in this._colors4) {
  26509. var color = this._colors4[name];
  26510. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  26511. }
  26512. // Vector2
  26513. for (name in this._vectors2) {
  26514. this._effect.setVector2(name, this._vectors2[name]);
  26515. }
  26516. // Vector3
  26517. for (name in this._vectors3) {
  26518. this._effect.setVector3(name, this._vectors3[name]);
  26519. }
  26520. // Vector4
  26521. for (name in this._vectors4) {
  26522. this._effect.setVector4(name, this._vectors4[name]);
  26523. }
  26524. // Matrix
  26525. for (name in this._matrices) {
  26526. this._effect.setMatrix(name, this._matrices[name]);
  26527. }
  26528. // Matrix 3x3
  26529. for (name in this._matrices3x3) {
  26530. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  26531. }
  26532. // Matrix 2x2
  26533. for (name in this._matrices2x2) {
  26534. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  26535. }
  26536. }
  26537. _super.prototype.bind.call(this, world, mesh);
  26538. };
  26539. ShaderMaterial.prototype.clone = function (name) {
  26540. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  26541. return newShaderMaterial;
  26542. };
  26543. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  26544. for (var name in this._textures) {
  26545. this._textures[name].dispose();
  26546. }
  26547. this._textures = [];
  26548. _super.prototype.dispose.call(this, forceDisposeEffect);
  26549. };
  26550. return ShaderMaterial;
  26551. })(BABYLON.Material);
  26552. BABYLON.ShaderMaterial = ShaderMaterial;
  26553. })(BABYLON || (BABYLON = {}));
  26554. var BABYLON;
  26555. (function (BABYLON) {
  26556. var VertexData = (function () {
  26557. function VertexData() {
  26558. }
  26559. VertexData.prototype.set = function (data, kind) {
  26560. switch (kind) {
  26561. case BABYLON.VertexBuffer.PositionKind:
  26562. this.positions = data;
  26563. break;
  26564. case BABYLON.VertexBuffer.NormalKind:
  26565. this.normals = data;
  26566. break;
  26567. case BABYLON.VertexBuffer.UVKind:
  26568. this.uvs = data;
  26569. break;
  26570. case BABYLON.VertexBuffer.UV2Kind:
  26571. this.uvs2 = data;
  26572. break;
  26573. case BABYLON.VertexBuffer.UV3Kind:
  26574. this.uvs3 = data;
  26575. break;
  26576. case BABYLON.VertexBuffer.UV4Kind:
  26577. this.uvs4 = data;
  26578. break;
  26579. case BABYLON.VertexBuffer.UV5Kind:
  26580. this.uvs5 = data;
  26581. break;
  26582. case BABYLON.VertexBuffer.UV6Kind:
  26583. this.uvs6 = data;
  26584. break;
  26585. case BABYLON.VertexBuffer.ColorKind:
  26586. this.colors = data;
  26587. break;
  26588. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26589. this.matricesIndices = data;
  26590. break;
  26591. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26592. this.matricesWeights = data;
  26593. break;
  26594. }
  26595. };
  26596. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26597. this._applyTo(mesh, updatable);
  26598. };
  26599. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26600. this._applyTo(geometry, updatable);
  26601. };
  26602. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26603. this._update(mesh);
  26604. };
  26605. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26606. this._update(geometry);
  26607. };
  26608. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26609. if (this.positions) {
  26610. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26611. }
  26612. if (this.normals) {
  26613. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26614. }
  26615. if (this.uvs) {
  26616. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26617. }
  26618. if (this.uvs2) {
  26619. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26620. }
  26621. if (this.uvs3) {
  26622. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26623. }
  26624. if (this.uvs4) {
  26625. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26626. }
  26627. if (this.uvs5) {
  26628. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26629. }
  26630. if (this.uvs6) {
  26631. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26632. }
  26633. if (this.colors) {
  26634. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26635. }
  26636. if (this.matricesIndices) {
  26637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26638. }
  26639. if (this.matricesWeights) {
  26640. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26641. }
  26642. if (this.indices) {
  26643. meshOrGeometry.setIndices(this.indices);
  26644. }
  26645. };
  26646. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26647. if (this.positions) {
  26648. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26649. }
  26650. if (this.normals) {
  26651. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26652. }
  26653. if (this.uvs) {
  26654. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26655. }
  26656. if (this.uvs2) {
  26657. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26658. }
  26659. if (this.uvs3) {
  26660. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26661. }
  26662. if (this.uvs4) {
  26663. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26664. }
  26665. if (this.uvs5) {
  26666. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26667. }
  26668. if (this.uvs6) {
  26669. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26670. }
  26671. if (this.colors) {
  26672. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26673. }
  26674. if (this.matricesIndices) {
  26675. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26676. }
  26677. if (this.matricesWeights) {
  26678. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26679. }
  26680. if (this.indices) {
  26681. meshOrGeometry.setIndices(this.indices);
  26682. }
  26683. };
  26684. VertexData.prototype.transform = function (matrix) {
  26685. var transformed = BABYLON.Vector3.Zero();
  26686. var index;
  26687. if (this.positions) {
  26688. var position = BABYLON.Vector3.Zero();
  26689. for (index = 0; index < this.positions.length; index += 3) {
  26690. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26691. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26692. this.positions[index] = transformed.x;
  26693. this.positions[index + 1] = transformed.y;
  26694. this.positions[index + 2] = transformed.z;
  26695. }
  26696. }
  26697. if (this.normals) {
  26698. var normal = BABYLON.Vector3.Zero();
  26699. for (index = 0; index < this.normals.length; index += 3) {
  26700. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26701. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26702. this.normals[index] = transformed.x;
  26703. this.normals[index + 1] = transformed.y;
  26704. this.normals[index + 2] = transformed.z;
  26705. }
  26706. }
  26707. };
  26708. VertexData.prototype.merge = function (other) {
  26709. var index;
  26710. if (other.indices) {
  26711. if (!this.indices) {
  26712. this.indices = [];
  26713. }
  26714. var offset = this.positions ? this.positions.length / 3 : 0;
  26715. for (index = 0; index < other.indices.length; index++) {
  26716. this.indices.push(other.indices[index] + offset);
  26717. }
  26718. }
  26719. if (other.positions) {
  26720. if (!this.positions) {
  26721. this.positions = [];
  26722. }
  26723. for (index = 0; index < other.positions.length; index++) {
  26724. this.positions.push(other.positions[index]);
  26725. }
  26726. }
  26727. if (other.normals) {
  26728. if (!this.normals) {
  26729. this.normals = [];
  26730. }
  26731. for (index = 0; index < other.normals.length; index++) {
  26732. this.normals.push(other.normals[index]);
  26733. }
  26734. }
  26735. if (other.uvs) {
  26736. if (!this.uvs) {
  26737. this.uvs = [];
  26738. }
  26739. for (index = 0; index < other.uvs.length; index++) {
  26740. this.uvs.push(other.uvs[index]);
  26741. }
  26742. }
  26743. if (other.uvs2) {
  26744. if (!this.uvs2) {
  26745. this.uvs2 = [];
  26746. }
  26747. for (index = 0; index < other.uvs2.length; index++) {
  26748. this.uvs2.push(other.uvs2[index]);
  26749. }
  26750. }
  26751. if (other.uvs3) {
  26752. if (!this.uvs3) {
  26753. this.uvs3 = [];
  26754. }
  26755. for (index = 0; index < other.uvs3.length; index++) {
  26756. this.uvs3.push(other.uvs3[index]);
  26757. }
  26758. }
  26759. if (other.uvs4) {
  26760. if (!this.uvs4) {
  26761. this.uvs4 = [];
  26762. }
  26763. for (index = 0; index < other.uvs4.length; index++) {
  26764. this.uvs4.push(other.uvs4[index]);
  26765. }
  26766. }
  26767. if (other.uvs5) {
  26768. if (!this.uvs5) {
  26769. this.uvs5 = [];
  26770. }
  26771. for (index = 0; index < other.uvs5.length; index++) {
  26772. this.uvs5.push(other.uvs5[index]);
  26773. }
  26774. }
  26775. if (other.uvs6) {
  26776. if (!this.uvs6) {
  26777. this.uvs6 = [];
  26778. }
  26779. for (index = 0; index < other.uvs6.length; index++) {
  26780. this.uvs6.push(other.uvs6[index]);
  26781. }
  26782. }
  26783. if (other.matricesIndices) {
  26784. if (!this.matricesIndices) {
  26785. this.matricesIndices = [];
  26786. }
  26787. for (index = 0; index < other.matricesIndices.length; index++) {
  26788. this.matricesIndices.push(other.matricesIndices[index]);
  26789. }
  26790. }
  26791. if (other.matricesWeights) {
  26792. if (!this.matricesWeights) {
  26793. this.matricesWeights = [];
  26794. }
  26795. for (index = 0; index < other.matricesWeights.length; index++) {
  26796. this.matricesWeights.push(other.matricesWeights[index]);
  26797. }
  26798. }
  26799. if (other.colors) {
  26800. if (!this.colors) {
  26801. this.colors = [];
  26802. }
  26803. for (index = 0; index < other.colors.length; index++) {
  26804. this.colors.push(other.colors[index]);
  26805. }
  26806. }
  26807. };
  26808. // Statics
  26809. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26810. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26811. };
  26812. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26813. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26814. };
  26815. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26816. var result = new VertexData();
  26817. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26818. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26819. }
  26820. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26821. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26822. }
  26823. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26824. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26825. }
  26826. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26827. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26828. }
  26829. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26830. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26831. }
  26832. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26833. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26834. }
  26835. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26836. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26837. }
  26838. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26839. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26840. }
  26841. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26842. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26843. }
  26844. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26845. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26846. }
  26847. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26848. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26849. }
  26850. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26851. return result;
  26852. };
  26853. VertexData.CreateRibbon = function (options) {
  26854. var pathArray = options.pathArray;
  26855. var closeArray = options.closeArray || false;
  26856. var closePath = options.closePath || false;
  26857. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26858. var offset = options.offset || defaultOffset;
  26859. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26860. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26861. var positions = [];
  26862. var indices = [];
  26863. var normals = [];
  26864. var uvs = [];
  26865. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26866. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26867. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26868. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26869. var minlg; // minimal length among all paths from pathArray
  26870. var lg = []; // array of path lengths : nb of vertex per path
  26871. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26872. var p; // path iterator
  26873. var i; // point iterator
  26874. var j; // point iterator
  26875. // if single path in pathArray
  26876. if (pathArray.length < 2) {
  26877. var ar1 = [];
  26878. var ar2 = [];
  26879. for (i = 0; i < pathArray[0].length - offset; i++) {
  26880. ar1.push(pathArray[0][i]);
  26881. ar2.push(pathArray[0][i + offset]);
  26882. }
  26883. pathArray = [ar1, ar2];
  26884. }
  26885. // positions and horizontal distances (u)
  26886. var idc = 0;
  26887. var closePathCorr = (closePath) ? 1 : 0;
  26888. var path;
  26889. var l;
  26890. minlg = pathArray[0].length;
  26891. var vectlg;
  26892. var dist;
  26893. for (p = 0; p < pathArray.length; p++) {
  26894. uTotalDistance[p] = 0;
  26895. us[p] = [0];
  26896. path = pathArray[p];
  26897. l = path.length;
  26898. minlg = (minlg < l) ? minlg : l;
  26899. j = 0;
  26900. while (j < l) {
  26901. positions.push(path[j].x, path[j].y, path[j].z);
  26902. if (j > 0) {
  26903. vectlg = path[j].subtract(path[j - 1]).length();
  26904. dist = vectlg + uTotalDistance[p];
  26905. us[p].push(dist);
  26906. uTotalDistance[p] = dist;
  26907. }
  26908. j++;
  26909. }
  26910. if (closePath) {
  26911. j--;
  26912. positions.push(path[0].x, path[0].y, path[0].z);
  26913. vectlg = path[j].subtract(path[0]).length();
  26914. dist = vectlg + uTotalDistance[p];
  26915. us[p].push(dist);
  26916. uTotalDistance[p] = dist;
  26917. }
  26918. lg[p] = l + closePathCorr;
  26919. idx[p] = idc;
  26920. idc += (l + closePathCorr);
  26921. }
  26922. // vertical distances (v)
  26923. var path1;
  26924. var path2;
  26925. var vertex1;
  26926. var vertex2;
  26927. for (i = 0; i < minlg + closePathCorr; i++) {
  26928. vTotalDistance[i] = 0;
  26929. vs[i] = [0];
  26930. for (p = 0; p < pathArray.length - 1; p++) {
  26931. path1 = pathArray[p];
  26932. path2 = pathArray[p + 1];
  26933. if (i === minlg) {
  26934. vertex1 = path1[0];
  26935. vertex2 = path2[0];
  26936. }
  26937. else {
  26938. vertex1 = path1[i];
  26939. vertex2 = path2[i];
  26940. }
  26941. vectlg = vertex2.subtract(vertex1).length();
  26942. dist = vectlg + vTotalDistance[i];
  26943. vs[i].push(dist);
  26944. vTotalDistance[i] = dist;
  26945. }
  26946. if (closeArray) {
  26947. path1 = pathArray[p];
  26948. path2 = pathArray[0];
  26949. if (i === minlg) {
  26950. vertex2 = path2[0];
  26951. }
  26952. vectlg = vertex2.subtract(vertex1).length();
  26953. dist = vectlg + vTotalDistance[i];
  26954. vTotalDistance[i] = dist;
  26955. }
  26956. }
  26957. // uvs
  26958. var u;
  26959. var v;
  26960. for (p = 0; p < pathArray.length; p++) {
  26961. for (i = 0; i < minlg + closePathCorr; i++) {
  26962. u = us[p][i] / uTotalDistance[p];
  26963. v = vs[i][p] / vTotalDistance[i];
  26964. uvs.push(u, v);
  26965. }
  26966. }
  26967. // indices
  26968. p = 0; // path index
  26969. var pi = 0; // positions array index
  26970. var l1 = lg[p] - 1; // path1 length
  26971. var l2 = lg[p + 1] - 1; // path2 length
  26972. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26973. var shft = idx[1] - idx[0]; // shift
  26974. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26975. while (pi <= min && p < path1nb) {
  26976. // 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
  26977. indices.push(pi, pi + shft, pi + 1);
  26978. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26979. pi += 1;
  26980. if (pi === min) {
  26981. p++;
  26982. if (p === lg.length - 1) {
  26983. shft = idx[0] - idx[p];
  26984. l1 = lg[p] - 1;
  26985. l2 = lg[0] - 1;
  26986. }
  26987. else {
  26988. shft = idx[p + 1] - idx[p];
  26989. l1 = lg[p] - 1;
  26990. l2 = lg[p + 1] - 1;
  26991. }
  26992. pi = idx[p];
  26993. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26994. }
  26995. }
  26996. // normals
  26997. VertexData.ComputeNormals(positions, indices, normals);
  26998. if (closePath) {
  26999. var indexFirst = 0;
  27000. var indexLast = 0;
  27001. for (p = 0; p < pathArray.length; p++) {
  27002. indexFirst = idx[p] * 3;
  27003. if (p + 1 < pathArray.length) {
  27004. indexLast = (idx[p + 1] - 1) * 3;
  27005. }
  27006. else {
  27007. indexLast = normals.length - 3;
  27008. }
  27009. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27010. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27011. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27012. normals[indexLast] = normals[indexFirst];
  27013. normals[indexLast + 1] = normals[indexFirst + 1];
  27014. normals[indexLast + 2] = normals[indexFirst + 2];
  27015. }
  27016. }
  27017. // sides
  27018. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27019. // Result
  27020. var vertexData = new VertexData();
  27021. vertexData.indices = indices;
  27022. vertexData.positions = positions;
  27023. vertexData.normals = normals;
  27024. vertexData.uvs = uvs;
  27025. if (closePath) {
  27026. vertexData._idx = idx;
  27027. }
  27028. return vertexData;
  27029. };
  27030. VertexData.CreateBox = function (options) {
  27031. var normalsSource = [
  27032. new BABYLON.Vector3(0, 0, 1),
  27033. new BABYLON.Vector3(0, 0, -1),
  27034. new BABYLON.Vector3(1, 0, 0),
  27035. new BABYLON.Vector3(-1, 0, 0),
  27036. new BABYLON.Vector3(0, 1, 0),
  27037. new BABYLON.Vector3(0, -1, 0)
  27038. ];
  27039. var indices = [];
  27040. var positions = [];
  27041. var normals = [];
  27042. var uvs = [];
  27043. var width = options.width || options.size || 1;
  27044. var height = options.height || options.size || 1;
  27045. var depth = options.depth || options.size || 1;
  27046. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27047. var faceUV = options.faceUV || new Array(6);
  27048. var faceColors = options.faceColors;
  27049. var colors = [];
  27050. // default face colors and UV if undefined
  27051. for (var f = 0; f < 6; f++) {
  27052. if (faceUV[f] === undefined) {
  27053. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27054. }
  27055. if (faceColors && faceColors[f] === undefined) {
  27056. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27057. }
  27058. }
  27059. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27060. // Create each face in turn.
  27061. for (var index = 0; index < normalsSource.length; index++) {
  27062. var normal = normalsSource[index];
  27063. // Get two vectors perpendicular to the face normal and to each other.
  27064. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27065. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27066. // Six indices (two triangles) per face.
  27067. var verticesLength = positions.length / 3;
  27068. indices.push(verticesLength);
  27069. indices.push(verticesLength + 1);
  27070. indices.push(verticesLength + 2);
  27071. indices.push(verticesLength);
  27072. indices.push(verticesLength + 2);
  27073. indices.push(verticesLength + 3);
  27074. // Four vertices per face.
  27075. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27076. positions.push(vertex.x, vertex.y, vertex.z);
  27077. normals.push(normal.x, normal.y, normal.z);
  27078. uvs.push(faceUV[index].z, faceUV[index].w);
  27079. if (faceColors) {
  27080. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27081. }
  27082. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27083. positions.push(vertex.x, vertex.y, vertex.z);
  27084. normals.push(normal.x, normal.y, normal.z);
  27085. uvs.push(faceUV[index].x, faceUV[index].w);
  27086. if (faceColors) {
  27087. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27088. }
  27089. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27090. positions.push(vertex.x, vertex.y, vertex.z);
  27091. normals.push(normal.x, normal.y, normal.z);
  27092. uvs.push(faceUV[index].x, faceUV[index].y);
  27093. if (faceColors) {
  27094. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27095. }
  27096. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27097. positions.push(vertex.x, vertex.y, vertex.z);
  27098. normals.push(normal.x, normal.y, normal.z);
  27099. uvs.push(faceUV[index].z, faceUV[index].y);
  27100. if (faceColors) {
  27101. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27102. }
  27103. }
  27104. // sides
  27105. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27106. // Result
  27107. var vertexData = new VertexData();
  27108. vertexData.indices = indices;
  27109. vertexData.positions = positions;
  27110. vertexData.normals = normals;
  27111. vertexData.uvs = uvs;
  27112. if (faceColors) {
  27113. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27114. vertexData.colors = totalColors;
  27115. }
  27116. return vertexData;
  27117. };
  27118. VertexData.CreateSphere = function (options) {
  27119. var segments = options.segments || 32;
  27120. var diameterX = options.diameterX || options.diameter || 1;
  27121. var diameterY = options.diameterY || options.diameter || 1;
  27122. var diameterZ = options.diameterZ || options.diameter || 1;
  27123. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  27124. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27125. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27126. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27127. var totalZRotationSteps = 2 + segments;
  27128. var totalYRotationSteps = 2 * totalZRotationSteps;
  27129. var indices = [];
  27130. var positions = [];
  27131. var normals = [];
  27132. var uvs = [];
  27133. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27134. var normalizedZ = zRotationStep / totalZRotationSteps;
  27135. var angleZ = normalizedZ * Math.PI * slice;
  27136. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27137. var normalizedY = yRotationStep / totalYRotationSteps;
  27138. var angleY = normalizedY * Math.PI * 2 * arc;
  27139. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27140. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27141. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27142. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27143. var vertex = complete.multiply(radius);
  27144. var normal = BABYLON.Vector3.Normalize(vertex);
  27145. positions.push(vertex.x, vertex.y, vertex.z);
  27146. normals.push(normal.x, normal.y, normal.z);
  27147. uvs.push(normalizedY, normalizedZ);
  27148. }
  27149. if (zRotationStep > 0) {
  27150. var verticesCount = positions.length / 3;
  27151. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27152. indices.push((firstIndex));
  27153. indices.push((firstIndex + 1));
  27154. indices.push(firstIndex + totalYRotationSteps + 1);
  27155. indices.push((firstIndex + totalYRotationSteps + 1));
  27156. indices.push((firstIndex + 1));
  27157. indices.push((firstIndex + totalYRotationSteps + 2));
  27158. }
  27159. }
  27160. }
  27161. // Sides
  27162. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27163. // Result
  27164. var vertexData = new VertexData();
  27165. vertexData.indices = indices;
  27166. vertexData.positions = positions;
  27167. vertexData.normals = normals;
  27168. vertexData.uvs = uvs;
  27169. return vertexData;
  27170. };
  27171. // Cylinder and cone
  27172. VertexData.CreateCylinder = function (options) {
  27173. var height = options.height || 2;
  27174. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27175. var diameterBottom = options.diameterBottom || options.diameter || 1;
  27176. var tessellation = options.tessellation || 24;
  27177. var subdivisions = options.subdivisions || 1;
  27178. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  27179. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27180. var faceUV = options.faceUV || new Array(3);
  27181. var faceColors = options.faceColors;
  27182. // default face colors and UV if undefined
  27183. for (var f = 0; f < 3; f++) {
  27184. if (faceColors && faceColors[f] === undefined) {
  27185. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27186. }
  27187. if (faceUV && faceUV[f] === undefined) {
  27188. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27189. }
  27190. }
  27191. var indices = [];
  27192. var positions = [];
  27193. var normals = [];
  27194. var uvs = [];
  27195. var colors = [];
  27196. var angle_step = Math.PI * 2 * arc / tessellation;
  27197. var angle;
  27198. var h;
  27199. var radius;
  27200. var tan = (diameterBottom - diameterTop) / 2 / height;
  27201. var ringVertex = BABYLON.Vector3.Zero();
  27202. var ringNormal = BABYLON.Vector3.Zero();
  27203. // positions, normals, uvs
  27204. var i;
  27205. var j;
  27206. for (i = 0; i <= subdivisions; i++) {
  27207. h = i / subdivisions;
  27208. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27209. for (j = 0; j <= tessellation; j++) {
  27210. angle = j * angle_step;
  27211. ringVertex.x = Math.cos(-angle) * radius;
  27212. ringVertex.y = -height / 2 + h * height;
  27213. ringVertex.z = Math.sin(-angle) * radius;
  27214. if (diameterTop === 0 && i === subdivisions) {
  27215. // if no top cap, reuse former normals
  27216. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27217. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27218. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27219. }
  27220. else {
  27221. ringNormal.x = ringVertex.x;
  27222. ringNormal.z = ringVertex.z;
  27223. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27224. ringNormal.normalize();
  27225. }
  27226. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27227. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27228. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  27229. if (faceColors) {
  27230. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  27231. }
  27232. }
  27233. }
  27234. // indices
  27235. for (i = 0; i < subdivisions; i++) {
  27236. for (j = 0; j < tessellation; j++) {
  27237. var i0 = i * (tessellation + 1) + j;
  27238. var i1 = (i + 1) * (tessellation + 1) + j;
  27239. var i2 = i * (tessellation + 1) + (j + 1);
  27240. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  27241. indices.push(i0, i1, i2);
  27242. indices.push(i3, i2, i1);
  27243. }
  27244. }
  27245. // Caps
  27246. var createCylinderCap = function (isTop) {
  27247. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27248. if (radius === 0) {
  27249. return;
  27250. }
  27251. // Cap positions, normals & uvs
  27252. var angle;
  27253. var circleVector;
  27254. var i;
  27255. var u = (isTop) ? faceUV[2] : faceUV[0];
  27256. var c;
  27257. if (faceColors) {
  27258. c = (isTop) ? faceColors[2] : faceColors[0];
  27259. }
  27260. // cap center
  27261. var vbase = positions.length / 3;
  27262. var offset = isTop ? height / 2 : -height / 2;
  27263. var center = new BABYLON.Vector3(0, offset, 0);
  27264. positions.push(center.x, center.y, center.z);
  27265. normals.push(0, isTop ? 1 : -1, 0);
  27266. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27267. if (faceColors) {
  27268. colors.push(c.r, c.g, c.b, c.a);
  27269. }
  27270. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27271. for (i = 0; i <= tessellation; i++) {
  27272. angle = Math.PI * 2 * i * arc / tessellation;
  27273. var cos = Math.cos(-angle);
  27274. var sin = Math.sin(-angle);
  27275. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27276. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27277. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27278. normals.push(0, isTop ? 1 : -1, 0);
  27279. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27280. if (faceColors) {
  27281. colors.push(c.r, c.g, c.b, c.a);
  27282. }
  27283. }
  27284. // Cap indices
  27285. for (i = 0; i < tessellation; i++) {
  27286. if (!isTop) {
  27287. indices.push(vbase);
  27288. indices.push(vbase + (i + 1));
  27289. indices.push(vbase + (i + 2));
  27290. }
  27291. else {
  27292. indices.push(vbase);
  27293. indices.push(vbase + (i + 2));
  27294. indices.push(vbase + (i + 1));
  27295. }
  27296. }
  27297. };
  27298. // add caps to geometry
  27299. createCylinderCap(false);
  27300. createCylinderCap(true);
  27301. // Sides
  27302. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27303. var vertexData = new VertexData();
  27304. vertexData.indices = indices;
  27305. vertexData.positions = positions;
  27306. vertexData.normals = normals;
  27307. vertexData.uvs = uvs;
  27308. if (faceColors) {
  27309. vertexData.colors = colors;
  27310. }
  27311. return vertexData;
  27312. };
  27313. VertexData.CreateTorus = function (options) {
  27314. var indices = [];
  27315. var positions = [];
  27316. var normals = [];
  27317. var uvs = [];
  27318. var diameter = options.diameter || 1;
  27319. var thickness = options.thickness || 0.5;
  27320. var tessellation = options.tessellation || 16;
  27321. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27322. var stride = tessellation + 1;
  27323. for (var i = 0; i <= tessellation; i++) {
  27324. var u = i / tessellation;
  27325. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27326. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27327. for (var j = 0; j <= tessellation; j++) {
  27328. var v = 1 - j / tessellation;
  27329. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27330. var dx = Math.cos(innerAngle);
  27331. var dy = Math.sin(innerAngle);
  27332. // Create a vertex.
  27333. var normal = new BABYLON.Vector3(dx, dy, 0);
  27334. var position = normal.scale(thickness / 2);
  27335. var textureCoordinate = new BABYLON.Vector2(u, v);
  27336. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27337. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27338. positions.push(position.x, position.y, position.z);
  27339. normals.push(normal.x, normal.y, normal.z);
  27340. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27341. // And create indices for two triangles.
  27342. var nextI = (i + 1) % stride;
  27343. var nextJ = (j + 1) % stride;
  27344. indices.push(i * stride + j);
  27345. indices.push(i * stride + nextJ);
  27346. indices.push(nextI * stride + j);
  27347. indices.push(i * stride + nextJ);
  27348. indices.push(nextI * stride + nextJ);
  27349. indices.push(nextI * stride + j);
  27350. }
  27351. }
  27352. // Sides
  27353. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27354. // Result
  27355. var vertexData = new VertexData();
  27356. vertexData.indices = indices;
  27357. vertexData.positions = positions;
  27358. vertexData.normals = normals;
  27359. vertexData.uvs = uvs;
  27360. return vertexData;
  27361. };
  27362. VertexData.CreateLines = function (options) {
  27363. var indices = [];
  27364. var positions = [];
  27365. var points = options.points;
  27366. for (var index = 0; index < points.length; index++) {
  27367. positions.push(points[index].x, points[index].y, points[index].z);
  27368. if (index > 0) {
  27369. indices.push(index - 1);
  27370. indices.push(index);
  27371. }
  27372. }
  27373. // Result
  27374. var vertexData = new VertexData();
  27375. vertexData.indices = indices;
  27376. vertexData.positions = positions;
  27377. return vertexData;
  27378. };
  27379. VertexData.CreateDashedLines = function (options) {
  27380. var dashSize = options.dashSize || 3;
  27381. var gapSize = options.gapSize || 1;
  27382. var dashNb = options.dashNb || 200;
  27383. var points = options.points;
  27384. var positions = new Array();
  27385. var indices = new Array();
  27386. var curvect = BABYLON.Vector3.Zero();
  27387. var lg = 0;
  27388. var nb = 0;
  27389. var shft = 0;
  27390. var dashshft = 0;
  27391. var curshft = 0;
  27392. var idx = 0;
  27393. var i = 0;
  27394. for (i = 0; i < points.length - 1; i++) {
  27395. points[i + 1].subtractToRef(points[i], curvect);
  27396. lg += curvect.length();
  27397. }
  27398. shft = lg / dashNb;
  27399. dashshft = dashSize * shft / (dashSize + gapSize);
  27400. for (i = 0; i < points.length - 1; i++) {
  27401. points[i + 1].subtractToRef(points[i], curvect);
  27402. nb = Math.floor(curvect.length() / shft);
  27403. curvect.normalize();
  27404. for (var j = 0; j < nb; j++) {
  27405. curshft = shft * j;
  27406. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27407. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27408. indices.push(idx, idx + 1);
  27409. idx += 2;
  27410. }
  27411. }
  27412. // Result
  27413. var vertexData = new VertexData();
  27414. vertexData.positions = positions;
  27415. vertexData.indices = indices;
  27416. return vertexData;
  27417. };
  27418. VertexData.CreateGround = function (options) {
  27419. var indices = [];
  27420. var positions = [];
  27421. var normals = [];
  27422. var uvs = [];
  27423. var row, col;
  27424. var width = options.width || 1;
  27425. var height = options.height || 1;
  27426. var subdivisions = options.subdivisions || 1;
  27427. for (row = 0; row <= subdivisions; row++) {
  27428. for (col = 0; col <= subdivisions; col++) {
  27429. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  27430. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27431. positions.push(position.x, position.y, position.z);
  27432. normals.push(normal.x, normal.y, normal.z);
  27433. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  27434. }
  27435. }
  27436. for (row = 0; row < subdivisions; row++) {
  27437. for (col = 0; col < subdivisions; col++) {
  27438. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27439. indices.push(col + 1 + row * (subdivisions + 1));
  27440. indices.push(col + row * (subdivisions + 1));
  27441. indices.push(col + (row + 1) * (subdivisions + 1));
  27442. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27443. indices.push(col + row * (subdivisions + 1));
  27444. }
  27445. }
  27446. // Result
  27447. var vertexData = new VertexData();
  27448. vertexData.indices = indices;
  27449. vertexData.positions = positions;
  27450. vertexData.normals = normals;
  27451. vertexData.uvs = uvs;
  27452. return vertexData;
  27453. };
  27454. VertexData.CreateTiledGround = function (options) {
  27455. var xmin = options.xmin;
  27456. var zmin = options.zmin;
  27457. var xmax = options.xmax;
  27458. var zmax = options.zmax;
  27459. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27460. var precision = options.precision || { w: 1, h: 1 };
  27461. var indices = [];
  27462. var positions = [];
  27463. var normals = [];
  27464. var uvs = [];
  27465. var row, col, tileRow, tileCol;
  27466. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  27467. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27468. precision.w = (precision.w < 1) ? 1 : precision.w;
  27469. precision.h = (precision.h < 1) ? 1 : precision.h;
  27470. var tileSize = {
  27471. 'w': (xmax - xmin) / subdivisions.w,
  27472. 'h': (zmax - zmin) / subdivisions.h
  27473. };
  27474. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27475. // Indices
  27476. var base = positions.length / 3;
  27477. var rowLength = precision.w + 1;
  27478. for (row = 0; row < precision.h; row++) {
  27479. for (col = 0; col < precision.w; col++) {
  27480. var square = [
  27481. base + col + row * rowLength,
  27482. base + (col + 1) + row * rowLength,
  27483. base + (col + 1) + (row + 1) * rowLength,
  27484. base + col + (row + 1) * rowLength
  27485. ];
  27486. indices.push(square[1]);
  27487. indices.push(square[2]);
  27488. indices.push(square[3]);
  27489. indices.push(square[0]);
  27490. indices.push(square[1]);
  27491. indices.push(square[3]);
  27492. }
  27493. }
  27494. // Position, normals and uvs
  27495. var position = BABYLON.Vector3.Zero();
  27496. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27497. for (row = 0; row <= precision.h; row++) {
  27498. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27499. for (col = 0; col <= precision.w; col++) {
  27500. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27501. position.y = 0;
  27502. positions.push(position.x, position.y, position.z);
  27503. normals.push(normal.x, normal.y, normal.z);
  27504. uvs.push(col / precision.w, row / precision.h);
  27505. }
  27506. }
  27507. }
  27508. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27509. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27510. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27511. }
  27512. }
  27513. // Result
  27514. var vertexData = new VertexData();
  27515. vertexData.indices = indices;
  27516. vertexData.positions = positions;
  27517. vertexData.normals = normals;
  27518. vertexData.uvs = uvs;
  27519. return vertexData;
  27520. };
  27521. VertexData.CreateGroundFromHeightMap = function (options) {
  27522. var indices = [];
  27523. var positions = [];
  27524. var normals = [];
  27525. var uvs = [];
  27526. var row, col;
  27527. // Vertices
  27528. for (row = 0; row <= options.subdivisions; row++) {
  27529. for (col = 0; col <= options.subdivisions; col++) {
  27530. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  27531. // Compute height
  27532. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27533. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27534. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27535. var r = options.buffer[pos] / 255.0;
  27536. var g = options.buffer[pos + 1] / 255.0;
  27537. var b = options.buffer[pos + 2] / 255.0;
  27538. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27539. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27540. // Add vertex
  27541. positions.push(position.x, position.y, position.z);
  27542. normals.push(0, 0, 0);
  27543. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27544. }
  27545. }
  27546. // Indices
  27547. for (row = 0; row < options.subdivisions; row++) {
  27548. for (col = 0; col < options.subdivisions; col++) {
  27549. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27550. indices.push(col + 1 + row * (options.subdivisions + 1));
  27551. indices.push(col + row * (options.subdivisions + 1));
  27552. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27553. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27554. indices.push(col + row * (options.subdivisions + 1));
  27555. }
  27556. }
  27557. // Normals
  27558. VertexData.ComputeNormals(positions, indices, normals);
  27559. // Result
  27560. var vertexData = new VertexData();
  27561. vertexData.indices = indices;
  27562. vertexData.positions = positions;
  27563. vertexData.normals = normals;
  27564. vertexData.uvs = uvs;
  27565. return vertexData;
  27566. };
  27567. VertexData.CreatePlane = function (options) {
  27568. var indices = [];
  27569. var positions = [];
  27570. var normals = [];
  27571. var uvs = [];
  27572. var width = options.width || options.size || 1;
  27573. var height = options.height || options.size || 1;
  27574. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27575. // Vertices
  27576. var halfWidth = width / 2.0;
  27577. var halfHeight = height / 2.0;
  27578. positions.push(-halfWidth, -halfHeight, 0);
  27579. normals.push(0, 0, -1.0);
  27580. uvs.push(0.0, 0.0);
  27581. positions.push(halfWidth, -halfHeight, 0);
  27582. normals.push(0, 0, -1.0);
  27583. uvs.push(1.0, 0.0);
  27584. positions.push(halfWidth, halfHeight, 0);
  27585. normals.push(0, 0, -1.0);
  27586. uvs.push(1.0, 1.0);
  27587. positions.push(-halfWidth, halfHeight, 0);
  27588. normals.push(0, 0, -1.0);
  27589. uvs.push(0.0, 1.0);
  27590. // Indices
  27591. indices.push(0);
  27592. indices.push(1);
  27593. indices.push(2);
  27594. indices.push(0);
  27595. indices.push(2);
  27596. indices.push(3);
  27597. // Sides
  27598. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27599. // Result
  27600. var vertexData = new VertexData();
  27601. vertexData.indices = indices;
  27602. vertexData.positions = positions;
  27603. vertexData.normals = normals;
  27604. vertexData.uvs = uvs;
  27605. return vertexData;
  27606. };
  27607. VertexData.CreateDisc = function (options) {
  27608. var positions = [];
  27609. var indices = [];
  27610. var normals = [];
  27611. var uvs = [];
  27612. var radius = options.radius || 0.5;
  27613. var tessellation = options.tessellation || 64;
  27614. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27615. // positions and uvs
  27616. positions.push(0, 0, 0); // disc center first
  27617. uvs.push(0.5, 0.5);
  27618. var step = Math.PI * 2 / tessellation;
  27619. for (var a = 0; a < Math.PI * 2; a += step) {
  27620. var x = Math.cos(a);
  27621. var y = Math.sin(a);
  27622. var u = (x + 1) / 2;
  27623. var v = (1 - y) / 2;
  27624. positions.push(radius * x, radius * y, 0);
  27625. uvs.push(u, v);
  27626. }
  27627. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27628. uvs.push(uvs[2], uvs[3]);
  27629. //indices
  27630. var vertexNb = positions.length / 3;
  27631. for (var i = 1; i < vertexNb - 1; i++) {
  27632. indices.push(i + 1, 0, i);
  27633. }
  27634. // result
  27635. VertexData.ComputeNormals(positions, indices, normals);
  27636. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27637. var vertexData = new VertexData();
  27638. vertexData.indices = indices;
  27639. vertexData.positions = positions;
  27640. vertexData.normals = normals;
  27641. vertexData.uvs = uvs;
  27642. return vertexData;
  27643. };
  27644. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27645. VertexData.CreateTorusKnot = function (options) {
  27646. var indices = [];
  27647. var positions = [];
  27648. var normals = [];
  27649. var uvs = [];
  27650. var radius = options.radius || 2;
  27651. var tube = options.tube || 0.5;
  27652. var radialSegments = options.radialSegments || 32;
  27653. var tubularSegments = options.tubularSegments || 32;
  27654. var p = options.p || 2;
  27655. var q = options.q || 3;
  27656. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27657. // Helper
  27658. var getPos = function (angle) {
  27659. var cu = Math.cos(angle);
  27660. var su = Math.sin(angle);
  27661. var quOverP = q / p * angle;
  27662. var cs = Math.cos(quOverP);
  27663. var tx = radius * (2 + cs) * 0.5 * cu;
  27664. var ty = radius * (2 + cs) * su * 0.5;
  27665. var tz = radius * Math.sin(quOverP) * 0.5;
  27666. return new BABYLON.Vector3(tx, ty, tz);
  27667. };
  27668. // Vertices
  27669. var i;
  27670. var j;
  27671. for (i = 0; i <= radialSegments; i++) {
  27672. var modI = i % radialSegments;
  27673. var u = modI / radialSegments * 2 * p * Math.PI;
  27674. var p1 = getPos(u);
  27675. var p2 = getPos(u + 0.01);
  27676. var tang = p2.subtract(p1);
  27677. var n = p2.add(p1);
  27678. var bitan = BABYLON.Vector3.Cross(tang, n);
  27679. n = BABYLON.Vector3.Cross(bitan, tang);
  27680. bitan.normalize();
  27681. n.normalize();
  27682. for (j = 0; j < tubularSegments; j++) {
  27683. var modJ = j % tubularSegments;
  27684. var v = modJ / tubularSegments * 2 * Math.PI;
  27685. var cx = -tube * Math.cos(v);
  27686. var cy = tube * Math.sin(v);
  27687. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27688. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27689. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27690. uvs.push(i / radialSegments);
  27691. uvs.push(j / tubularSegments);
  27692. }
  27693. }
  27694. for (i = 0; i < radialSegments; i++) {
  27695. for (j = 0; j < tubularSegments; j++) {
  27696. var jNext = (j + 1) % tubularSegments;
  27697. var a = i * tubularSegments + j;
  27698. var b = (i + 1) * tubularSegments + j;
  27699. var c = (i + 1) * tubularSegments + jNext;
  27700. var d = i * tubularSegments + jNext;
  27701. indices.push(d);
  27702. indices.push(b);
  27703. indices.push(a);
  27704. indices.push(d);
  27705. indices.push(c);
  27706. indices.push(b);
  27707. }
  27708. }
  27709. // Normals
  27710. VertexData.ComputeNormals(positions, indices, normals);
  27711. // Sides
  27712. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27713. // Result
  27714. var vertexData = new VertexData();
  27715. vertexData.indices = indices;
  27716. vertexData.positions = positions;
  27717. vertexData.normals = normals;
  27718. vertexData.uvs = uvs;
  27719. return vertexData;
  27720. };
  27721. // Tools
  27722. /**
  27723. * @param {any} - positions (number[] or Float32Array)
  27724. * @param {any} - indices (number[] or Uint16Array)
  27725. * @param {any} - normals (number[] or Float32Array)
  27726. */
  27727. VertexData.ComputeNormals = function (positions, indices, normals) {
  27728. var index = 0;
  27729. // temp Vector3
  27730. var p1p2 = BABYLON.Vector3.Zero();
  27731. var p3p2 = BABYLON.Vector3.Zero();
  27732. var faceNormal = BABYLON.Vector3.Zero();
  27733. var vertexNormali1 = BABYLON.Vector3.Zero();
  27734. for (index = 0; index < positions.length; index++) {
  27735. normals[index] = 0.0;
  27736. }
  27737. // indice triplet = 1 face
  27738. var nbFaces = indices.length / 3;
  27739. for (index = 0; index < nbFaces; index++) {
  27740. var i1 = indices[index * 3];
  27741. var i2 = indices[index * 3 + 1];
  27742. var i3 = indices[index * 3 + 2];
  27743. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  27744. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27745. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27746. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  27747. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27748. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27749. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  27750. faceNormal.normalize();
  27751. normals[i1 * 3] += faceNormal.x;
  27752. normals[i1 * 3 + 1] += faceNormal.y;
  27753. normals[i1 * 3 + 2] += faceNormal.z;
  27754. normals[i2 * 3] += faceNormal.x;
  27755. normals[i2 * 3 + 1] += faceNormal.y;
  27756. normals[i2 * 3 + 2] += faceNormal.z;
  27757. normals[i3 * 3] += faceNormal.x;
  27758. normals[i3 * 3 + 1] += faceNormal.y;
  27759. normals[i3 * 3 + 2] += faceNormal.z;
  27760. }
  27761. // last normalization
  27762. for (index = 0; index < normals.length / 3; index++) {
  27763. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  27764. vertexNormali1.normalize();
  27765. normals[index * 3] = vertexNormali1.x;
  27766. normals[index * 3 + 1] = vertexNormali1.y;
  27767. normals[index * 3 + 2] = vertexNormali1.z;
  27768. }
  27769. };
  27770. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27771. var li = indices.length;
  27772. var ln = normals.length;
  27773. var i;
  27774. var n;
  27775. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27776. switch (sideOrientation) {
  27777. case BABYLON.Mesh.FRONTSIDE:
  27778. // nothing changed
  27779. break;
  27780. case BABYLON.Mesh.BACKSIDE:
  27781. var tmp;
  27782. // indices
  27783. for (i = 0; i < li; i += 3) {
  27784. tmp = indices[i];
  27785. indices[i] = indices[i + 2];
  27786. indices[i + 2] = tmp;
  27787. }
  27788. // normals
  27789. for (n = 0; n < ln; n++) {
  27790. normals[n] = -normals[n];
  27791. }
  27792. break;
  27793. case BABYLON.Mesh.DOUBLESIDE:
  27794. // positions
  27795. var lp = positions.length;
  27796. var l = lp / 3;
  27797. for (var p = 0; p < lp; p++) {
  27798. positions[lp + p] = positions[p];
  27799. }
  27800. // indices
  27801. for (i = 0; i < li; i += 3) {
  27802. indices[i + li] = indices[i + 2] + l;
  27803. indices[i + 1 + li] = indices[i + 1] + l;
  27804. indices[i + 2 + li] = indices[i] + l;
  27805. }
  27806. // normals
  27807. for (n = 0; n < ln; n++) {
  27808. normals[ln + n] = -normals[n];
  27809. }
  27810. // uvs
  27811. var lu = uvs.length;
  27812. for (var u = 0; u < lu; u++) {
  27813. uvs[u + lu] = uvs[u];
  27814. }
  27815. break;
  27816. }
  27817. };
  27818. return VertexData;
  27819. })();
  27820. BABYLON.VertexData = VertexData;
  27821. })(BABYLON || (BABYLON = {}));
  27822. var BABYLON;
  27823. (function (BABYLON) {
  27824. var AnaglyphPostProcess = (function (_super) {
  27825. __extends(AnaglyphPostProcess, _super);
  27826. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27827. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  27828. }
  27829. return AnaglyphPostProcess;
  27830. })(BABYLON.PostProcess);
  27831. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  27832. })(BABYLON || (BABYLON = {}));
  27833. var BABYLON;
  27834. (function (BABYLON) {
  27835. var Tags = (function () {
  27836. function Tags() {
  27837. }
  27838. Tags.EnableFor = function (obj) {
  27839. obj._tags = obj._tags || {};
  27840. obj.hasTags = function () {
  27841. return Tags.HasTags(obj);
  27842. };
  27843. obj.addTags = function (tagsString) {
  27844. return Tags.AddTagsTo(obj, tagsString);
  27845. };
  27846. obj.removeTags = function (tagsString) {
  27847. return Tags.RemoveTagsFrom(obj, tagsString);
  27848. };
  27849. obj.matchesTagsQuery = function (tagsQuery) {
  27850. return Tags.MatchesQuery(obj, tagsQuery);
  27851. };
  27852. };
  27853. Tags.DisableFor = function (obj) {
  27854. delete obj._tags;
  27855. delete obj.hasTags;
  27856. delete obj.addTags;
  27857. delete obj.removeTags;
  27858. delete obj.matchesTagsQuery;
  27859. };
  27860. Tags.HasTags = function (obj) {
  27861. if (!obj._tags) {
  27862. return false;
  27863. }
  27864. return !BABYLON.Tools.IsEmpty(obj._tags);
  27865. };
  27866. Tags.GetTags = function (obj) {
  27867. if (!obj._tags) {
  27868. return null;
  27869. }
  27870. return obj._tags;
  27871. };
  27872. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27873. // a tag cannot start with '||', '&&', and '!'
  27874. // it cannot contain whitespaces
  27875. Tags.AddTagsTo = function (obj, tagsString) {
  27876. if (!tagsString) {
  27877. return;
  27878. }
  27879. var tags = tagsString.split(" ");
  27880. for (var t in tags) {
  27881. Tags._AddTagTo(obj, tags[t]);
  27882. }
  27883. };
  27884. Tags._AddTagTo = function (obj, tag) {
  27885. tag = tag.trim();
  27886. if (tag === "" || tag === "true" || tag === "false") {
  27887. return;
  27888. }
  27889. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27890. return;
  27891. }
  27892. Tags.EnableFor(obj);
  27893. obj._tags[tag] = true;
  27894. };
  27895. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27896. if (!Tags.HasTags(obj)) {
  27897. return;
  27898. }
  27899. var tags = tagsString.split(" ");
  27900. for (var t in tags) {
  27901. Tags._RemoveTagFrom(obj, tags[t]);
  27902. }
  27903. };
  27904. Tags._RemoveTagFrom = function (obj, tag) {
  27905. delete obj._tags[tag];
  27906. };
  27907. Tags.MatchesQuery = function (obj, tagsQuery) {
  27908. if (tagsQuery === undefined) {
  27909. return true;
  27910. }
  27911. if (tagsQuery === "") {
  27912. return Tags.HasTags(obj);
  27913. }
  27914. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27915. };
  27916. return Tags;
  27917. })();
  27918. BABYLON.Tags = Tags;
  27919. })(BABYLON || (BABYLON = {}));
  27920. var BABYLON;
  27921. (function (BABYLON) {
  27922. var Internals;
  27923. (function (Internals) {
  27924. var AndOrNotEvaluator = (function () {
  27925. function AndOrNotEvaluator() {
  27926. }
  27927. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27928. if (!query.match(/\([^\(\)]*\)/g)) {
  27929. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27930. }
  27931. else {
  27932. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27933. // remove parenthesis
  27934. r = r.slice(1, r.length - 1);
  27935. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27936. });
  27937. }
  27938. if (query === "true") {
  27939. return true;
  27940. }
  27941. if (query === "false") {
  27942. return false;
  27943. }
  27944. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27945. };
  27946. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27947. evaluateCallback = evaluateCallback || (function (r) {
  27948. return r === "true" ? true : false;
  27949. });
  27950. var result;
  27951. var or = parenthesisContent.split("||");
  27952. for (var i in or) {
  27953. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27954. var and = ori.split("&&");
  27955. if (and.length > 1) {
  27956. for (var j = 0; j < and.length; ++j) {
  27957. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27958. if (andj !== "true" && andj !== "false") {
  27959. if (andj[0] === "!") {
  27960. result = !evaluateCallback(andj.substring(1));
  27961. }
  27962. else {
  27963. result = evaluateCallback(andj);
  27964. }
  27965. }
  27966. else {
  27967. result = andj === "true" ? true : false;
  27968. }
  27969. if (!result) {
  27970. ori = "false";
  27971. break;
  27972. }
  27973. }
  27974. }
  27975. if (result || ori === "true") {
  27976. result = true;
  27977. break;
  27978. }
  27979. // result equals false (or undefined)
  27980. if (ori !== "true" && ori !== "false") {
  27981. if (ori[0] === "!") {
  27982. result = !evaluateCallback(ori.substring(1));
  27983. }
  27984. else {
  27985. result = evaluateCallback(ori);
  27986. }
  27987. }
  27988. else {
  27989. result = ori === "true" ? true : false;
  27990. }
  27991. }
  27992. // the whole parenthesis scope is replaced by 'true' or 'false'
  27993. return result ? "true" : "false";
  27994. };
  27995. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27996. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27997. // remove whitespaces
  27998. r = r.replace(/[\s]/g, function () { return ""; });
  27999. return r.length % 2 ? "!" : "";
  28000. });
  28001. booleanString = booleanString.trim();
  28002. if (booleanString === "!true") {
  28003. booleanString = "false";
  28004. }
  28005. else if (booleanString === "!false") {
  28006. booleanString = "true";
  28007. }
  28008. return booleanString;
  28009. };
  28010. return AndOrNotEvaluator;
  28011. })();
  28012. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  28013. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28014. })(BABYLON || (BABYLON = {}));
  28015. var BABYLON;
  28016. (function (BABYLON) {
  28017. var PostProcessRenderPass = (function () {
  28018. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  28019. this._enabled = true;
  28020. this._refCount = 0;
  28021. this._name = name;
  28022. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  28023. this.setRenderList(renderList);
  28024. this._renderTexture.onBeforeRender = beforeRender;
  28025. this._renderTexture.onAfterRender = afterRender;
  28026. this._scene = scene;
  28027. this._renderList = renderList;
  28028. }
  28029. // private
  28030. PostProcessRenderPass.prototype._incRefCount = function () {
  28031. if (this._refCount === 0) {
  28032. this._scene.customRenderTargets.push(this._renderTexture);
  28033. }
  28034. return ++this._refCount;
  28035. };
  28036. PostProcessRenderPass.prototype._decRefCount = function () {
  28037. this._refCount--;
  28038. if (this._refCount <= 0) {
  28039. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  28040. }
  28041. return this._refCount;
  28042. };
  28043. PostProcessRenderPass.prototype._update = function () {
  28044. this.setRenderList(this._renderList);
  28045. };
  28046. // public
  28047. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  28048. this._renderTexture.renderList = renderList;
  28049. };
  28050. PostProcessRenderPass.prototype.getRenderTexture = function () {
  28051. return this._renderTexture;
  28052. };
  28053. return PostProcessRenderPass;
  28054. })();
  28055. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  28056. })(BABYLON || (BABYLON = {}));
  28057. var BABYLON;
  28058. (function (BABYLON) {
  28059. var PostProcessRenderEffect = (function () {
  28060. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  28061. this._engine = engine;
  28062. this._name = name;
  28063. this._singleInstance = singleInstance || true;
  28064. this._getPostProcess = getPostProcess;
  28065. this._cameras = [];
  28066. this._indicesForCamera = [];
  28067. this._postProcesses = {};
  28068. this._renderPasses = {};
  28069. this._renderEffectAsPasses = {};
  28070. }
  28071. PostProcessRenderEffect.prototype._update = function () {
  28072. for (var renderPassName in this._renderPasses) {
  28073. this._renderPasses[renderPassName]._update();
  28074. }
  28075. };
  28076. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  28077. this._renderPasses[renderPass._name] = renderPass;
  28078. this._linkParameters();
  28079. };
  28080. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  28081. delete this._renderPasses[renderPass._name];
  28082. this._linkParameters();
  28083. };
  28084. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  28085. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  28086. this._linkParameters();
  28087. };
  28088. PostProcessRenderEffect.prototype.getPass = function (passName) {
  28089. for (var renderPassName in this._renderPasses) {
  28090. if (renderPassName === passName) {
  28091. return this._renderPasses[passName];
  28092. }
  28093. }
  28094. };
  28095. PostProcessRenderEffect.prototype.emptyPasses = function () {
  28096. this._renderPasses = {};
  28097. this._linkParameters();
  28098. };
  28099. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  28100. var cameraKey;
  28101. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28102. for (var i = 0; i < _cam.length; i++) {
  28103. var camera = _cam[i];
  28104. var cameraName = camera.name;
  28105. if (this._singleInstance) {
  28106. cameraKey = 0;
  28107. }
  28108. else {
  28109. cameraKey = cameraName;
  28110. }
  28111. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  28112. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  28113. if (!this._indicesForCamera[cameraName]) {
  28114. this._indicesForCamera[cameraName] = [];
  28115. }
  28116. this._indicesForCamera[cameraName].push(index);
  28117. if (this._cameras.indexOf(camera) === -1) {
  28118. this._cameras[cameraName] = camera;
  28119. }
  28120. for (var passName in this._renderPasses) {
  28121. this._renderPasses[passName]._incRefCount();
  28122. }
  28123. }
  28124. this._linkParameters();
  28125. };
  28126. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  28127. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28128. for (var i = 0; i < _cam.length; i++) {
  28129. var camera = _cam[i];
  28130. var cameraName = camera.name;
  28131. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  28132. var index = this._cameras.indexOf(cameraName);
  28133. this._indicesForCamera.splice(index, 1);
  28134. this._cameras.splice(index, 1);
  28135. for (var passName in this._renderPasses) {
  28136. this._renderPasses[passName]._decRefCount();
  28137. }
  28138. }
  28139. };
  28140. PostProcessRenderEffect.prototype._enable = function (cameras) {
  28141. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28142. for (var i = 0; i < _cam.length; i++) {
  28143. var camera = _cam[i];
  28144. var cameraName = camera.name;
  28145. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  28146. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  28147. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  28148. }
  28149. }
  28150. for (var passName in this._renderPasses) {
  28151. this._renderPasses[passName]._incRefCount();
  28152. }
  28153. }
  28154. };
  28155. PostProcessRenderEffect.prototype._disable = function (cameras) {
  28156. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28157. for (var i = 0; i < _cam.length; i++) {
  28158. var camera = _cam[i];
  28159. var cameraName = camera.Name;
  28160. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  28161. for (var passName in this._renderPasses) {
  28162. this._renderPasses[passName]._decRefCount();
  28163. }
  28164. }
  28165. };
  28166. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  28167. if (this._singleInstance) {
  28168. return this._postProcesses[0];
  28169. }
  28170. else {
  28171. return this._postProcesses[camera.name];
  28172. }
  28173. };
  28174. PostProcessRenderEffect.prototype._linkParameters = function () {
  28175. var _this = this;
  28176. for (var index in this._postProcesses) {
  28177. if (this.applyParameters) {
  28178. this.applyParameters(this._postProcesses[index]);
  28179. }
  28180. this._postProcesses[index].onBeforeRender = function (effect) {
  28181. _this._linkTextures(effect);
  28182. };
  28183. }
  28184. };
  28185. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  28186. for (var renderPassName in this._renderPasses) {
  28187. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  28188. }
  28189. for (var renderEffectName in this._renderEffectAsPasses) {
  28190. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  28191. }
  28192. };
  28193. return PostProcessRenderEffect;
  28194. })();
  28195. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  28196. })(BABYLON || (BABYLON = {}));
  28197. var BABYLON;
  28198. (function (BABYLON) {
  28199. var PostProcessRenderPipeline = (function () {
  28200. function PostProcessRenderPipeline(engine, name) {
  28201. this._engine = engine;
  28202. this._name = name;
  28203. this._renderEffects = {};
  28204. this._renderEffectsForIsolatedPass = {};
  28205. this._cameras = [];
  28206. }
  28207. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  28208. this._renderEffects[renderEffect._name] = renderEffect;
  28209. };
  28210. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  28211. var renderEffects = this._renderEffects[renderEffectName];
  28212. if (!renderEffects) {
  28213. return;
  28214. }
  28215. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28216. };
  28217. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  28218. var renderEffects = this._renderEffects[renderEffectName];
  28219. if (!renderEffects) {
  28220. return;
  28221. }
  28222. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28223. };
  28224. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  28225. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28226. var indicesToDelete = [];
  28227. for (var i = 0; i < _cam.length; i++) {
  28228. var camera = _cam[i];
  28229. var cameraName = camera.name;
  28230. if (this._cameras.indexOf(camera) === -1) {
  28231. this._cameras[cameraName] = camera;
  28232. }
  28233. else if (unique) {
  28234. indicesToDelete.push(i);
  28235. }
  28236. }
  28237. for (var i = 0; i < indicesToDelete.length; i++) {
  28238. cameras.splice(indicesToDelete[i], 1);
  28239. }
  28240. for (var renderEffectName in this._renderEffects) {
  28241. this._renderEffects[renderEffectName]._attachCameras(_cam);
  28242. }
  28243. };
  28244. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  28245. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28246. for (var renderEffectName in this._renderEffects) {
  28247. this._renderEffects[renderEffectName]._detachCameras(_cam);
  28248. }
  28249. for (var i = 0; i < _cam.length; i++) {
  28250. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  28251. }
  28252. };
  28253. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  28254. var _this = this;
  28255. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28256. var pass = null;
  28257. for (var renderEffectName in this._renderEffects) {
  28258. pass = this._renderEffects[renderEffectName].getPass(passName);
  28259. if (pass != null) {
  28260. break;
  28261. }
  28262. }
  28263. if (pass === null) {
  28264. return;
  28265. }
  28266. for (var renderEffectName in this._renderEffects) {
  28267. this._renderEffects[renderEffectName]._disable(_cam);
  28268. }
  28269. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  28270. for (var i = 0; i < _cam.length; i++) {
  28271. var camera = _cam[i];
  28272. var cameraName = camera.name;
  28273. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  28274. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  28275. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  28276. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  28277. }
  28278. };
  28279. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  28280. var _this = this;
  28281. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28282. for (var i = 0; i < _cam.length; i++) {
  28283. var camera = _cam[i];
  28284. var cameraName = camera.name;
  28285. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  28286. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  28287. }
  28288. for (var renderEffectName in this._renderEffects) {
  28289. this._renderEffects[renderEffectName]._enable(_cam);
  28290. }
  28291. };
  28292. PostProcessRenderPipeline.prototype._update = function () {
  28293. for (var renderEffectName in this._renderEffects) {
  28294. this._renderEffects[renderEffectName]._update();
  28295. }
  28296. for (var i = 0; i < this._cameras.length; i++) {
  28297. var cameraName = this._cameras[i].name;
  28298. if (this._renderEffectsForIsolatedPass[cameraName]) {
  28299. this._renderEffectsForIsolatedPass[cameraName]._update();
  28300. }
  28301. }
  28302. };
  28303. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  28304. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  28305. return PostProcessRenderPipeline;
  28306. })();
  28307. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  28308. })(BABYLON || (BABYLON = {}));
  28309. var BABYLON;
  28310. (function (BABYLON) {
  28311. var PostProcessRenderPipelineManager = (function () {
  28312. function PostProcessRenderPipelineManager() {
  28313. this._renderPipelines = {};
  28314. }
  28315. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  28316. this._renderPipelines[renderPipeline._name] = renderPipeline;
  28317. };
  28318. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  28319. var renderPipeline = this._renderPipelines[renderPipelineName];
  28320. if (!renderPipeline) {
  28321. return;
  28322. }
  28323. renderPipeline._attachCameras(cameras, unique);
  28324. };
  28325. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  28326. var renderPipeline = this._renderPipelines[renderPipelineName];
  28327. if (!renderPipeline) {
  28328. return;
  28329. }
  28330. renderPipeline._detachCameras(cameras);
  28331. };
  28332. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28333. var renderPipeline = this._renderPipelines[renderPipelineName];
  28334. if (!renderPipeline) {
  28335. return;
  28336. }
  28337. renderPipeline._enableEffect(renderEffectName, cameras);
  28338. };
  28339. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28340. var renderPipeline = this._renderPipelines[renderPipelineName];
  28341. if (!renderPipeline) {
  28342. return;
  28343. }
  28344. renderPipeline._disableEffect(renderEffectName, cameras);
  28345. };
  28346. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  28347. var renderPipeline = this._renderPipelines[renderPipelineName];
  28348. if (!renderPipeline) {
  28349. return;
  28350. }
  28351. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  28352. };
  28353. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  28354. var renderPipeline = this._renderPipelines[renderPipelineName];
  28355. if (!renderPipeline) {
  28356. return;
  28357. }
  28358. renderPipeline._disableDisplayOnlyPass(cameras);
  28359. };
  28360. PostProcessRenderPipelineManager.prototype.update = function () {
  28361. for (var renderPipelineName in this._renderPipelines) {
  28362. this._renderPipelines[renderPipelineName]._update();
  28363. }
  28364. };
  28365. return PostProcessRenderPipelineManager;
  28366. })();
  28367. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  28368. })(BABYLON || (BABYLON = {}));
  28369. var BABYLON;
  28370. (function (BABYLON) {
  28371. var DisplayPassPostProcess = (function (_super) {
  28372. __extends(DisplayPassPostProcess, _super);
  28373. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28374. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28375. }
  28376. return DisplayPassPostProcess;
  28377. })(BABYLON.PostProcess);
  28378. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28379. })(BABYLON || (BABYLON = {}));
  28380. var BABYLON;
  28381. (function (BABYLON) {
  28382. var BoundingBoxRenderer = (function () {
  28383. function BoundingBoxRenderer(scene) {
  28384. this.frontColor = new BABYLON.Color3(1, 1, 1);
  28385. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  28386. this.showBackLines = true;
  28387. this.renderList = new BABYLON.SmartArray(32);
  28388. this._scene = scene;
  28389. }
  28390. BoundingBoxRenderer.prototype._prepareRessources = function () {
  28391. if (this._colorShader) {
  28392. return;
  28393. }
  28394. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  28395. attributes: ["position"],
  28396. uniforms: ["worldViewProjection", "color"]
  28397. });
  28398. var engine = this._scene.getEngine();
  28399. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  28400. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  28401. 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]);
  28402. };
  28403. BoundingBoxRenderer.prototype.reset = function () {
  28404. this.renderList.reset();
  28405. };
  28406. BoundingBoxRenderer.prototype.render = function () {
  28407. if (this.renderList.length === 0) {
  28408. return;
  28409. }
  28410. this._prepareRessources();
  28411. if (!this._colorShader.isReady()) {
  28412. return;
  28413. }
  28414. var engine = this._scene.getEngine();
  28415. engine.setDepthWrite(false);
  28416. this._colorShader._preBind();
  28417. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  28418. var boundingBox = this.renderList.data[boundingBoxIndex];
  28419. var min = boundingBox.minimum;
  28420. var max = boundingBox.maximum;
  28421. var diff = max.subtract(min);
  28422. var median = min.add(diff.scale(0.5));
  28423. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  28424. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  28425. .multiply(boundingBox.getWorldMatrix());
  28426. // VBOs
  28427. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  28428. if (this.showBackLines) {
  28429. // Back
  28430. engine.setDepthFunctionToGreaterOrEqual();
  28431. this._scene.resetCachedMaterial();
  28432. this._colorShader.setColor4("color", this.backColor.toColor4());
  28433. this._colorShader.bind(worldMatrix);
  28434. // Draw order
  28435. engine.draw(false, 0, 24);
  28436. }
  28437. // Front
  28438. engine.setDepthFunctionToLess();
  28439. this._scene.resetCachedMaterial();
  28440. this._colorShader.setColor4("color", this.frontColor.toColor4());
  28441. this._colorShader.bind(worldMatrix);
  28442. // Draw order
  28443. engine.draw(false, 0, 24);
  28444. }
  28445. this._colorShader.unbind();
  28446. engine.setDepthFunctionToLessOrEqual();
  28447. engine.setDepthWrite(true);
  28448. };
  28449. BoundingBoxRenderer.prototype.dispose = function () {
  28450. if (!this._colorShader) {
  28451. return;
  28452. }
  28453. this._colorShader.dispose();
  28454. this._vb.dispose();
  28455. this._scene.getEngine()._releaseBuffer(this._ib);
  28456. };
  28457. return BoundingBoxRenderer;
  28458. })();
  28459. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  28460. })(BABYLON || (BABYLON = {}));
  28461. var BABYLON;
  28462. (function (BABYLON) {
  28463. var Condition = (function () {
  28464. function Condition(actionManager) {
  28465. this._actionManager = actionManager;
  28466. }
  28467. Condition.prototype.isValid = function () {
  28468. return true;
  28469. };
  28470. Condition.prototype._getProperty = function (propertyPath) {
  28471. return this._actionManager._getProperty(propertyPath);
  28472. };
  28473. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  28474. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28475. };
  28476. return Condition;
  28477. })();
  28478. BABYLON.Condition = Condition;
  28479. var ValueCondition = (function (_super) {
  28480. __extends(ValueCondition, _super);
  28481. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  28482. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  28483. _super.call(this, actionManager);
  28484. this.propertyPath = propertyPath;
  28485. this.value = value;
  28486. this.operator = operator;
  28487. this._target = this._getEffectiveTarget(target, this.propertyPath);
  28488. this._property = this._getProperty(this.propertyPath);
  28489. }
  28490. Object.defineProperty(ValueCondition, "IsEqual", {
  28491. get: function () {
  28492. return ValueCondition._IsEqual;
  28493. },
  28494. enumerable: true,
  28495. configurable: true
  28496. });
  28497. Object.defineProperty(ValueCondition, "IsDifferent", {
  28498. get: function () {
  28499. return ValueCondition._IsDifferent;
  28500. },
  28501. enumerable: true,
  28502. configurable: true
  28503. });
  28504. Object.defineProperty(ValueCondition, "IsGreater", {
  28505. get: function () {
  28506. return ValueCondition._IsGreater;
  28507. },
  28508. enumerable: true,
  28509. configurable: true
  28510. });
  28511. Object.defineProperty(ValueCondition, "IsLesser", {
  28512. get: function () {
  28513. return ValueCondition._IsLesser;
  28514. },
  28515. enumerable: true,
  28516. configurable: true
  28517. });
  28518. // Methods
  28519. ValueCondition.prototype.isValid = function () {
  28520. switch (this.operator) {
  28521. case ValueCondition.IsGreater:
  28522. return this._target[this._property] > this.value;
  28523. case ValueCondition.IsLesser:
  28524. return this._target[this._property] < this.value;
  28525. case ValueCondition.IsEqual:
  28526. case ValueCondition.IsDifferent:
  28527. var check;
  28528. if (this.value.equals) {
  28529. check = this.value.equals(this._target[this._property]);
  28530. }
  28531. else {
  28532. check = this.value === this._target[this._property];
  28533. }
  28534. return this.operator === ValueCondition.IsEqual ? check : !check;
  28535. }
  28536. return false;
  28537. };
  28538. // Statics
  28539. ValueCondition._IsEqual = 0;
  28540. ValueCondition._IsDifferent = 1;
  28541. ValueCondition._IsGreater = 2;
  28542. ValueCondition._IsLesser = 3;
  28543. return ValueCondition;
  28544. })(Condition);
  28545. BABYLON.ValueCondition = ValueCondition;
  28546. var PredicateCondition = (function (_super) {
  28547. __extends(PredicateCondition, _super);
  28548. function PredicateCondition(actionManager, predicate) {
  28549. _super.call(this, actionManager);
  28550. this.predicate = predicate;
  28551. }
  28552. PredicateCondition.prototype.isValid = function () {
  28553. return this.predicate();
  28554. };
  28555. return PredicateCondition;
  28556. })(Condition);
  28557. BABYLON.PredicateCondition = PredicateCondition;
  28558. var StateCondition = (function (_super) {
  28559. __extends(StateCondition, _super);
  28560. function StateCondition(actionManager, target, value) {
  28561. _super.call(this, actionManager);
  28562. this.value = value;
  28563. this._target = target;
  28564. }
  28565. // Methods
  28566. StateCondition.prototype.isValid = function () {
  28567. return this._target.state === this.value;
  28568. };
  28569. return StateCondition;
  28570. })(Condition);
  28571. BABYLON.StateCondition = StateCondition;
  28572. })(BABYLON || (BABYLON = {}));
  28573. var BABYLON;
  28574. (function (BABYLON) {
  28575. var Action = (function () {
  28576. function Action(triggerOptions, condition) {
  28577. this.triggerOptions = triggerOptions;
  28578. if (triggerOptions.parameter) {
  28579. this.trigger = triggerOptions.trigger;
  28580. this._triggerParameter = triggerOptions.parameter;
  28581. }
  28582. else {
  28583. this.trigger = triggerOptions;
  28584. }
  28585. this._nextActiveAction = this;
  28586. this._condition = condition;
  28587. }
  28588. // Methods
  28589. Action.prototype._prepare = function () {
  28590. };
  28591. Action.prototype.getTriggerParameter = function () {
  28592. return this._triggerParameter;
  28593. };
  28594. Action.prototype._executeCurrent = function (evt) {
  28595. if (this._nextActiveAction._condition) {
  28596. var condition = this._nextActiveAction._condition;
  28597. var currentRenderId = this._actionManager.getScene().getRenderId();
  28598. // We cache the current evaluation for the current frame
  28599. if (condition._evaluationId === currentRenderId) {
  28600. if (!condition._currentResult) {
  28601. return;
  28602. }
  28603. }
  28604. else {
  28605. condition._evaluationId = currentRenderId;
  28606. if (!condition.isValid()) {
  28607. condition._currentResult = false;
  28608. return;
  28609. }
  28610. condition._currentResult = true;
  28611. }
  28612. }
  28613. this._nextActiveAction.execute(evt);
  28614. if (this._nextActiveAction._child) {
  28615. if (!this._nextActiveAction._child._actionManager) {
  28616. this._nextActiveAction._child._actionManager = this._actionManager;
  28617. }
  28618. this._nextActiveAction = this._nextActiveAction._child;
  28619. }
  28620. else {
  28621. this._nextActiveAction = this;
  28622. }
  28623. };
  28624. Action.prototype.execute = function (evt) {
  28625. };
  28626. Action.prototype.then = function (action) {
  28627. this._child = action;
  28628. action._actionManager = this._actionManager;
  28629. action._prepare();
  28630. return action;
  28631. };
  28632. Action.prototype._getProperty = function (propertyPath) {
  28633. return this._actionManager._getProperty(propertyPath);
  28634. };
  28635. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  28636. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28637. };
  28638. return Action;
  28639. })();
  28640. BABYLON.Action = Action;
  28641. })(BABYLON || (BABYLON = {}));
  28642. var BABYLON;
  28643. (function (BABYLON) {
  28644. /**
  28645. * ActionEvent is the event beint sent when an action is triggered.
  28646. */
  28647. var ActionEvent = (function () {
  28648. /**
  28649. * @constructor
  28650. * @param source The mesh or sprite that triggered the action.
  28651. * @param pointerX The X mouse cursor position at the time of the event
  28652. * @param pointerY The Y mouse cursor position at the time of the event
  28653. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  28654. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  28655. */
  28656. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  28657. this.source = source;
  28658. this.pointerX = pointerX;
  28659. this.pointerY = pointerY;
  28660. this.meshUnderPointer = meshUnderPointer;
  28661. this.sourceEvent = sourceEvent;
  28662. this.additionalData = additionalData;
  28663. }
  28664. /**
  28665. * Helper function to auto-create an ActionEvent from a source mesh.
  28666. * @param source The source mesh that triggered the event
  28667. * @param evt {Event} The original (browser) event
  28668. */
  28669. ActionEvent.CreateNew = function (source, evt, additionalData) {
  28670. var scene = source.getScene();
  28671. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28672. };
  28673. /**
  28674. * Helper function to auto-create an ActionEvent from a source mesh.
  28675. * @param source The source sprite that triggered the event
  28676. * @param scene Scene associated with the sprite
  28677. * @param evt {Event} The original (browser) event
  28678. */
  28679. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  28680. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28681. };
  28682. /**
  28683. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28684. * @param scene the scene where the event occurred
  28685. * @param evt {Event} The original (browser) event
  28686. */
  28687. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28688. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28689. };
  28690. return ActionEvent;
  28691. })();
  28692. BABYLON.ActionEvent = ActionEvent;
  28693. /**
  28694. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28695. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28696. */
  28697. var ActionManager = (function () {
  28698. function ActionManager(scene) {
  28699. // Members
  28700. this.actions = new Array();
  28701. this._scene = scene;
  28702. scene._actionManagers.push(this);
  28703. }
  28704. Object.defineProperty(ActionManager, "NothingTrigger", {
  28705. get: function () {
  28706. return ActionManager._NothingTrigger;
  28707. },
  28708. enumerable: true,
  28709. configurable: true
  28710. });
  28711. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28712. get: function () {
  28713. return ActionManager._OnPickTrigger;
  28714. },
  28715. enumerable: true,
  28716. configurable: true
  28717. });
  28718. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28719. get: function () {
  28720. return ActionManager._OnLeftPickTrigger;
  28721. },
  28722. enumerable: true,
  28723. configurable: true
  28724. });
  28725. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28726. get: function () {
  28727. return ActionManager._OnRightPickTrigger;
  28728. },
  28729. enumerable: true,
  28730. configurable: true
  28731. });
  28732. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28733. get: function () {
  28734. return ActionManager._OnCenterPickTrigger;
  28735. },
  28736. enumerable: true,
  28737. configurable: true
  28738. });
  28739. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28740. get: function () {
  28741. return ActionManager._OnPointerOverTrigger;
  28742. },
  28743. enumerable: true,
  28744. configurable: true
  28745. });
  28746. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28747. get: function () {
  28748. return ActionManager._OnPointerOutTrigger;
  28749. },
  28750. enumerable: true,
  28751. configurable: true
  28752. });
  28753. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28754. get: function () {
  28755. return ActionManager._OnEveryFrameTrigger;
  28756. },
  28757. enumerable: true,
  28758. configurable: true
  28759. });
  28760. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28761. get: function () {
  28762. return ActionManager._OnIntersectionEnterTrigger;
  28763. },
  28764. enumerable: true,
  28765. configurable: true
  28766. });
  28767. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28768. get: function () {
  28769. return ActionManager._OnIntersectionExitTrigger;
  28770. },
  28771. enumerable: true,
  28772. configurable: true
  28773. });
  28774. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28775. get: function () {
  28776. return ActionManager._OnKeyDownTrigger;
  28777. },
  28778. enumerable: true,
  28779. configurable: true
  28780. });
  28781. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28782. get: function () {
  28783. return ActionManager._OnKeyUpTrigger;
  28784. },
  28785. enumerable: true,
  28786. configurable: true
  28787. });
  28788. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28789. get: function () {
  28790. return ActionManager._OnPickUpTrigger;
  28791. },
  28792. enumerable: true,
  28793. configurable: true
  28794. });
  28795. // Methods
  28796. ActionManager.prototype.dispose = function () {
  28797. var index = this._scene._actionManagers.indexOf(this);
  28798. if (index > -1) {
  28799. this._scene._actionManagers.splice(index, 1);
  28800. }
  28801. };
  28802. ActionManager.prototype.getScene = function () {
  28803. return this._scene;
  28804. };
  28805. /**
  28806. * Does this action manager handles actions of any of the given triggers
  28807. * @param {number[]} triggers - the triggers to be tested
  28808. * @return {boolean} whether one (or more) of the triggers is handeled
  28809. */
  28810. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28811. for (var index = 0; index < this.actions.length; index++) {
  28812. var action = this.actions[index];
  28813. if (triggers.indexOf(action.trigger) > -1) {
  28814. return true;
  28815. }
  28816. }
  28817. return false;
  28818. };
  28819. /**
  28820. * Does this action manager handles actions of a given trigger
  28821. * @param {number} trigger - the trigger to be tested
  28822. * @return {boolean} whether the trigger is handeled
  28823. */
  28824. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28825. for (var index = 0; index < this.actions.length; index++) {
  28826. var action = this.actions[index];
  28827. if (action.trigger === trigger) {
  28828. return true;
  28829. }
  28830. }
  28831. return false;
  28832. };
  28833. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28834. /**
  28835. * Does this action manager has pointer triggers
  28836. * @return {boolean} whether or not it has pointer triggers
  28837. */
  28838. get: function () {
  28839. for (var index = 0; index < this.actions.length; index++) {
  28840. var action = this.actions[index];
  28841. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28842. return true;
  28843. }
  28844. if (action.trigger === ActionManager._OnPickUpTrigger) {
  28845. return true;
  28846. }
  28847. }
  28848. return false;
  28849. },
  28850. enumerable: true,
  28851. configurable: true
  28852. });
  28853. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28854. /**
  28855. * Does this action manager has pick triggers
  28856. * @return {boolean} whether or not it has pick triggers
  28857. */
  28858. get: function () {
  28859. for (var index = 0; index < this.actions.length; index++) {
  28860. var action = this.actions[index];
  28861. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  28862. return true;
  28863. }
  28864. if (action.trigger === ActionManager._OnPickUpTrigger) {
  28865. return true;
  28866. }
  28867. }
  28868. return false;
  28869. },
  28870. enumerable: true,
  28871. configurable: true
  28872. });
  28873. /**
  28874. * Registers an action to this action manager
  28875. * @param {BABYLON.Action} action - the action to be registered
  28876. * @return {BABYLON.Action} the action amended (prepared) after registration
  28877. */
  28878. ActionManager.prototype.registerAction = function (action) {
  28879. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28880. if (this.getScene().actionManager !== this) {
  28881. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28882. return null;
  28883. }
  28884. }
  28885. this.actions.push(action);
  28886. action._actionManager = this;
  28887. action._prepare();
  28888. return action;
  28889. };
  28890. /**
  28891. * Process a specific trigger
  28892. * @param {number} trigger - the trigger to process
  28893. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28894. */
  28895. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28896. for (var index = 0; index < this.actions.length; index++) {
  28897. var action = this.actions[index];
  28898. if (action.trigger === trigger) {
  28899. if (trigger === ActionManager.OnKeyUpTrigger
  28900. || trigger === ActionManager.OnKeyDownTrigger) {
  28901. var parameter = action.getTriggerParameter();
  28902. if (parameter) {
  28903. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28904. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28905. if (actualkey !== parameter.toLowerCase()) {
  28906. continue;
  28907. }
  28908. }
  28909. }
  28910. action._executeCurrent(evt);
  28911. }
  28912. }
  28913. };
  28914. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28915. var properties = propertyPath.split(".");
  28916. for (var index = 0; index < properties.length - 1; index++) {
  28917. target = target[properties[index]];
  28918. }
  28919. return target;
  28920. };
  28921. ActionManager.prototype._getProperty = function (propertyPath) {
  28922. var properties = propertyPath.split(".");
  28923. return properties[properties.length - 1];
  28924. };
  28925. // Statics
  28926. ActionManager._NothingTrigger = 0;
  28927. ActionManager._OnPickTrigger = 1;
  28928. ActionManager._OnLeftPickTrigger = 2;
  28929. ActionManager._OnRightPickTrigger = 3;
  28930. ActionManager._OnCenterPickTrigger = 4;
  28931. ActionManager._OnPointerOverTrigger = 5;
  28932. ActionManager._OnPointerOutTrigger = 6;
  28933. ActionManager._OnEveryFrameTrigger = 7;
  28934. ActionManager._OnIntersectionEnterTrigger = 8;
  28935. ActionManager._OnIntersectionExitTrigger = 9;
  28936. ActionManager._OnKeyDownTrigger = 10;
  28937. ActionManager._OnKeyUpTrigger = 11;
  28938. ActionManager._OnPickUpTrigger = 12;
  28939. return ActionManager;
  28940. })();
  28941. BABYLON.ActionManager = ActionManager;
  28942. })(BABYLON || (BABYLON = {}));
  28943. var BABYLON;
  28944. (function (BABYLON) {
  28945. var InterpolateValueAction = (function (_super) {
  28946. __extends(InterpolateValueAction, _super);
  28947. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  28948. if (duration === void 0) { duration = 1000; }
  28949. _super.call(this, triggerOptions, condition);
  28950. this.propertyPath = propertyPath;
  28951. this.value = value;
  28952. this.duration = duration;
  28953. this.stopOtherAnimations = stopOtherAnimations;
  28954. this.onInterpolationDone = onInterpolationDone;
  28955. this._target = target;
  28956. }
  28957. InterpolateValueAction.prototype._prepare = function () {
  28958. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28959. this._property = this._getProperty(this.propertyPath);
  28960. };
  28961. InterpolateValueAction.prototype.execute = function () {
  28962. var scene = this._actionManager.getScene();
  28963. var keys = [
  28964. {
  28965. frame: 0,
  28966. value: this._target[this._property]
  28967. }, {
  28968. frame: 100,
  28969. value: this.value
  28970. }
  28971. ];
  28972. var dataType;
  28973. if (typeof this.value === "number") {
  28974. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28975. }
  28976. else if (this.value instanceof BABYLON.Color3) {
  28977. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28978. }
  28979. else if (this.value instanceof BABYLON.Vector3) {
  28980. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28981. }
  28982. else if (this.value instanceof BABYLON.Matrix) {
  28983. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28984. }
  28985. else if (this.value instanceof BABYLON.Quaternion) {
  28986. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28987. }
  28988. else {
  28989. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28990. return;
  28991. }
  28992. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28993. animation.setKeys(keys);
  28994. if (this.stopOtherAnimations) {
  28995. scene.stopAnimation(this._target);
  28996. }
  28997. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  28998. };
  28999. return InterpolateValueAction;
  29000. })(BABYLON.Action);
  29001. BABYLON.InterpolateValueAction = InterpolateValueAction;
  29002. })(BABYLON || (BABYLON = {}));
  29003. var BABYLON;
  29004. (function (BABYLON) {
  29005. var SwitchBooleanAction = (function (_super) {
  29006. __extends(SwitchBooleanAction, _super);
  29007. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  29008. _super.call(this, triggerOptions, condition);
  29009. this.propertyPath = propertyPath;
  29010. this._target = target;
  29011. }
  29012. SwitchBooleanAction.prototype._prepare = function () {
  29013. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29014. this._property = this._getProperty(this.propertyPath);
  29015. };
  29016. SwitchBooleanAction.prototype.execute = function () {
  29017. this._target[this._property] = !this._target[this._property];
  29018. };
  29019. return SwitchBooleanAction;
  29020. })(BABYLON.Action);
  29021. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  29022. var SetStateAction = (function (_super) {
  29023. __extends(SetStateAction, _super);
  29024. function SetStateAction(triggerOptions, target, value, condition) {
  29025. _super.call(this, triggerOptions, condition);
  29026. this.value = value;
  29027. this._target = target;
  29028. }
  29029. SetStateAction.prototype.execute = function () {
  29030. this._target.state = this.value;
  29031. };
  29032. return SetStateAction;
  29033. })(BABYLON.Action);
  29034. BABYLON.SetStateAction = SetStateAction;
  29035. var SetValueAction = (function (_super) {
  29036. __extends(SetValueAction, _super);
  29037. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  29038. _super.call(this, triggerOptions, condition);
  29039. this.propertyPath = propertyPath;
  29040. this.value = value;
  29041. this._target = target;
  29042. }
  29043. SetValueAction.prototype._prepare = function () {
  29044. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29045. this._property = this._getProperty(this.propertyPath);
  29046. };
  29047. SetValueAction.prototype.execute = function () {
  29048. this._target[this._property] = this.value;
  29049. };
  29050. return SetValueAction;
  29051. })(BABYLON.Action);
  29052. BABYLON.SetValueAction = SetValueAction;
  29053. var IncrementValueAction = (function (_super) {
  29054. __extends(IncrementValueAction, _super);
  29055. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  29056. _super.call(this, triggerOptions, condition);
  29057. this.propertyPath = propertyPath;
  29058. this.value = value;
  29059. this._target = target;
  29060. }
  29061. IncrementValueAction.prototype._prepare = function () {
  29062. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  29063. this._property = this._getProperty(this.propertyPath);
  29064. if (typeof this._target[this._property] !== "number") {
  29065. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  29066. }
  29067. };
  29068. IncrementValueAction.prototype.execute = function () {
  29069. this._target[this._property] += this.value;
  29070. };
  29071. return IncrementValueAction;
  29072. })(BABYLON.Action);
  29073. BABYLON.IncrementValueAction = IncrementValueAction;
  29074. var PlayAnimationAction = (function (_super) {
  29075. __extends(PlayAnimationAction, _super);
  29076. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  29077. _super.call(this, triggerOptions, condition);
  29078. this.from = from;
  29079. this.to = to;
  29080. this.loop = loop;
  29081. this._target = target;
  29082. }
  29083. PlayAnimationAction.prototype._prepare = function () {
  29084. };
  29085. PlayAnimationAction.prototype.execute = function () {
  29086. var scene = this._actionManager.getScene();
  29087. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  29088. };
  29089. return PlayAnimationAction;
  29090. })(BABYLON.Action);
  29091. BABYLON.PlayAnimationAction = PlayAnimationAction;
  29092. var StopAnimationAction = (function (_super) {
  29093. __extends(StopAnimationAction, _super);
  29094. function StopAnimationAction(triggerOptions, target, condition) {
  29095. _super.call(this, triggerOptions, condition);
  29096. this._target = target;
  29097. }
  29098. StopAnimationAction.prototype._prepare = function () {
  29099. };
  29100. StopAnimationAction.prototype.execute = function () {
  29101. var scene = this._actionManager.getScene();
  29102. scene.stopAnimation(this._target);
  29103. };
  29104. return StopAnimationAction;
  29105. })(BABYLON.Action);
  29106. BABYLON.StopAnimationAction = StopAnimationAction;
  29107. var DoNothingAction = (function (_super) {
  29108. __extends(DoNothingAction, _super);
  29109. function DoNothingAction(triggerOptions, condition) {
  29110. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  29111. _super.call(this, triggerOptions, condition);
  29112. }
  29113. DoNothingAction.prototype.execute = function () {
  29114. };
  29115. return DoNothingAction;
  29116. })(BABYLON.Action);
  29117. BABYLON.DoNothingAction = DoNothingAction;
  29118. var CombineAction = (function (_super) {
  29119. __extends(CombineAction, _super);
  29120. function CombineAction(triggerOptions, children, condition) {
  29121. _super.call(this, triggerOptions, condition);
  29122. this.children = children;
  29123. }
  29124. CombineAction.prototype._prepare = function () {
  29125. for (var index = 0; index < this.children.length; index++) {
  29126. this.children[index]._actionManager = this._actionManager;
  29127. this.children[index]._prepare();
  29128. }
  29129. };
  29130. CombineAction.prototype.execute = function (evt) {
  29131. for (var index = 0; index < this.children.length; index++) {
  29132. this.children[index].execute(evt);
  29133. }
  29134. };
  29135. return CombineAction;
  29136. })(BABYLON.Action);
  29137. BABYLON.CombineAction = CombineAction;
  29138. var ExecuteCodeAction = (function (_super) {
  29139. __extends(ExecuteCodeAction, _super);
  29140. function ExecuteCodeAction(triggerOptions, func, condition) {
  29141. _super.call(this, triggerOptions, condition);
  29142. this.func = func;
  29143. }
  29144. ExecuteCodeAction.prototype.execute = function (evt) {
  29145. this.func(evt);
  29146. };
  29147. return ExecuteCodeAction;
  29148. })(BABYLON.Action);
  29149. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  29150. var SetParentAction = (function (_super) {
  29151. __extends(SetParentAction, _super);
  29152. function SetParentAction(triggerOptions, target, parent, condition) {
  29153. _super.call(this, triggerOptions, condition);
  29154. this._target = target;
  29155. this._parent = parent;
  29156. }
  29157. SetParentAction.prototype._prepare = function () {
  29158. };
  29159. SetParentAction.prototype.execute = function () {
  29160. if (this._target.parent === this._parent) {
  29161. return;
  29162. }
  29163. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  29164. invertParentWorldMatrix.invert();
  29165. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  29166. this._target.parent = this._parent;
  29167. };
  29168. return SetParentAction;
  29169. })(BABYLON.Action);
  29170. BABYLON.SetParentAction = SetParentAction;
  29171. var PlaySoundAction = (function (_super) {
  29172. __extends(PlaySoundAction, _super);
  29173. function PlaySoundAction(triggerOptions, sound, condition) {
  29174. _super.call(this, triggerOptions, condition);
  29175. this._sound = sound;
  29176. }
  29177. PlaySoundAction.prototype._prepare = function () {
  29178. };
  29179. PlaySoundAction.prototype.execute = function () {
  29180. if (this._sound !== undefined)
  29181. this._sound.play();
  29182. };
  29183. return PlaySoundAction;
  29184. })(BABYLON.Action);
  29185. BABYLON.PlaySoundAction = PlaySoundAction;
  29186. var StopSoundAction = (function (_super) {
  29187. __extends(StopSoundAction, _super);
  29188. function StopSoundAction(triggerOptions, sound, condition) {
  29189. _super.call(this, triggerOptions, condition);
  29190. this._sound = sound;
  29191. }
  29192. StopSoundAction.prototype._prepare = function () {
  29193. };
  29194. StopSoundAction.prototype.execute = function () {
  29195. if (this._sound !== undefined)
  29196. this._sound.stop();
  29197. };
  29198. return StopSoundAction;
  29199. })(BABYLON.Action);
  29200. BABYLON.StopSoundAction = StopSoundAction;
  29201. })(BABYLON || (BABYLON = {}));
  29202. var BABYLON;
  29203. (function (BABYLON) {
  29204. var Geometry = (function () {
  29205. function Geometry(id, scene, vertexData, updatable, mesh) {
  29206. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29207. this._totalVertices = 0;
  29208. this._indices = [];
  29209. this._isDisposed = false;
  29210. this.id = id;
  29211. this._engine = scene.getEngine();
  29212. this._meshes = [];
  29213. this._scene = scene;
  29214. // vertexData
  29215. if (vertexData) {
  29216. this.setAllVerticesData(vertexData, updatable);
  29217. }
  29218. else {
  29219. this._totalVertices = 0;
  29220. this._indices = [];
  29221. }
  29222. // applyToMesh
  29223. if (mesh) {
  29224. this.applyToMesh(mesh);
  29225. mesh.computeWorldMatrix(true);
  29226. }
  29227. }
  29228. Geometry.prototype.getScene = function () {
  29229. return this._scene;
  29230. };
  29231. Geometry.prototype.getEngine = function () {
  29232. return this._engine;
  29233. };
  29234. Geometry.prototype.isReady = function () {
  29235. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29236. };
  29237. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29238. vertexData.applyToGeometry(this, updatable);
  29239. this.notifyUpdate();
  29240. };
  29241. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29242. this._vertexBuffers = this._vertexBuffers || {};
  29243. if (this._vertexBuffers[kind]) {
  29244. this._vertexBuffers[kind].dispose();
  29245. }
  29246. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29247. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29248. stride = this._vertexBuffers[kind].getStrideSize();
  29249. this._totalVertices = data.length / stride;
  29250. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29251. var meshes = this._meshes;
  29252. var numOfMeshes = meshes.length;
  29253. for (var index = 0; index < numOfMeshes; index++) {
  29254. var mesh = meshes[index];
  29255. mesh._resetPointsArrayCache();
  29256. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29257. mesh._createGlobalSubMesh();
  29258. mesh.computeWorldMatrix(true);
  29259. }
  29260. }
  29261. this.notifyUpdate(kind);
  29262. };
  29263. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29264. var vertexBuffer = this.getVertexBuffer(kind);
  29265. if (!vertexBuffer) {
  29266. return;
  29267. }
  29268. vertexBuffer.updateDirectly(data, offset);
  29269. this.notifyUpdate(kind);
  29270. };
  29271. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29272. var vertexBuffer = this.getVertexBuffer(kind);
  29273. if (!vertexBuffer) {
  29274. return;
  29275. }
  29276. vertexBuffer.update(data);
  29277. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29278. var extend;
  29279. var stride = vertexBuffer.getStrideSize();
  29280. this._totalVertices = data.length / stride;
  29281. if (updateExtends) {
  29282. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29283. }
  29284. var meshes = this._meshes;
  29285. var numOfMeshes = meshes.length;
  29286. for (var index = 0; index < numOfMeshes; index++) {
  29287. var mesh = meshes[index];
  29288. mesh._resetPointsArrayCache();
  29289. if (updateExtends) {
  29290. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29291. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29292. var subMesh = mesh.subMeshes[subIndex];
  29293. subMesh.refreshBoundingInfo();
  29294. }
  29295. }
  29296. }
  29297. }
  29298. this.notifyUpdate(kind);
  29299. };
  29300. Geometry.prototype.getTotalVertices = function () {
  29301. if (!this.isReady()) {
  29302. return 0;
  29303. }
  29304. return this._totalVertices;
  29305. };
  29306. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  29307. var vertexBuffer = this.getVertexBuffer(kind);
  29308. if (!vertexBuffer) {
  29309. return null;
  29310. }
  29311. var orig = vertexBuffer.getData();
  29312. if (!copyWhenShared || this._meshes.length === 1) {
  29313. return orig;
  29314. }
  29315. else {
  29316. var len = orig.length;
  29317. var copy = [];
  29318. for (var i = 0; i < len; i++) {
  29319. copy.push(orig[i]);
  29320. }
  29321. return copy;
  29322. }
  29323. };
  29324. Geometry.prototype.getVertexBuffer = function (kind) {
  29325. if (!this.isReady()) {
  29326. return null;
  29327. }
  29328. return this._vertexBuffers[kind];
  29329. };
  29330. Geometry.prototype.getVertexBuffers = function () {
  29331. if (!this.isReady()) {
  29332. return null;
  29333. }
  29334. return this._vertexBuffers;
  29335. };
  29336. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29337. if (!this._vertexBuffers) {
  29338. if (this._delayInfo) {
  29339. return this._delayInfo.indexOf(kind) !== -1;
  29340. }
  29341. return false;
  29342. }
  29343. return this._vertexBuffers[kind] !== undefined;
  29344. };
  29345. Geometry.prototype.getVerticesDataKinds = function () {
  29346. var result = [];
  29347. if (!this._vertexBuffers && this._delayInfo) {
  29348. for (var kind in this._delayInfo) {
  29349. result.push(kind);
  29350. }
  29351. }
  29352. else {
  29353. for (kind in this._vertexBuffers) {
  29354. result.push(kind);
  29355. }
  29356. }
  29357. return result;
  29358. };
  29359. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29360. if (this._indexBuffer) {
  29361. this._engine._releaseBuffer(this._indexBuffer);
  29362. }
  29363. this._indices = indices;
  29364. if (this._meshes.length !== 0 && this._indices) {
  29365. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29366. }
  29367. if (totalVertices !== undefined) {
  29368. this._totalVertices = totalVertices;
  29369. }
  29370. var meshes = this._meshes;
  29371. var numOfMeshes = meshes.length;
  29372. for (var index = 0; index < numOfMeshes; index++) {
  29373. meshes[index]._createGlobalSubMesh();
  29374. }
  29375. this.notifyUpdate();
  29376. };
  29377. Geometry.prototype.getTotalIndices = function () {
  29378. if (!this.isReady()) {
  29379. return 0;
  29380. }
  29381. return this._indices.length;
  29382. };
  29383. Geometry.prototype.getIndices = function (copyWhenShared) {
  29384. if (!this.isReady()) {
  29385. return null;
  29386. }
  29387. var orig = this._indices;
  29388. if (!copyWhenShared || this._meshes.length === 1) {
  29389. return orig;
  29390. }
  29391. else {
  29392. var len = orig.length;
  29393. var copy = [];
  29394. for (var i = 0; i < len; i++) {
  29395. copy.push(orig[i]);
  29396. }
  29397. return copy;
  29398. }
  29399. };
  29400. Geometry.prototype.getIndexBuffer = function () {
  29401. if (!this.isReady()) {
  29402. return null;
  29403. }
  29404. return this._indexBuffer;
  29405. };
  29406. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29407. var meshes = this._meshes;
  29408. var index = meshes.indexOf(mesh);
  29409. if (index === -1) {
  29410. return;
  29411. }
  29412. for (var kind in this._vertexBuffers) {
  29413. this._vertexBuffers[kind].dispose();
  29414. }
  29415. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  29416. this._indexBuffer = null;
  29417. }
  29418. meshes.splice(index, 1);
  29419. mesh._geometry = null;
  29420. if (meshes.length === 0 && shouldDispose) {
  29421. this.dispose();
  29422. }
  29423. };
  29424. Geometry.prototype.applyToMesh = function (mesh) {
  29425. if (mesh._geometry === this) {
  29426. return;
  29427. }
  29428. var previousGeometry = mesh._geometry;
  29429. if (previousGeometry) {
  29430. previousGeometry.releaseForMesh(mesh);
  29431. }
  29432. var meshes = this._meshes;
  29433. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29434. mesh._geometry = this;
  29435. this._scene.pushGeometry(this);
  29436. meshes.push(mesh);
  29437. if (this.isReady()) {
  29438. this._applyToMesh(mesh);
  29439. }
  29440. else {
  29441. mesh._boundingInfo = this._boundingInfo;
  29442. }
  29443. };
  29444. Geometry.prototype._applyToMesh = function (mesh) {
  29445. var numOfMeshes = this._meshes.length;
  29446. // vertexBuffers
  29447. for (var kind in this._vertexBuffers) {
  29448. if (numOfMeshes === 1) {
  29449. this._vertexBuffers[kind].create();
  29450. }
  29451. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  29452. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29453. mesh._resetPointsArrayCache();
  29454. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  29455. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29456. mesh._createGlobalSubMesh();
  29457. //bounding info was just created again, world matrix should be applied again.
  29458. mesh._updateBoundingInfo();
  29459. }
  29460. }
  29461. // indexBuffer
  29462. if (numOfMeshes === 1 && this._indices) {
  29463. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29464. }
  29465. if (this._indexBuffer) {
  29466. this._indexBuffer.references = numOfMeshes;
  29467. }
  29468. };
  29469. Geometry.prototype.notifyUpdate = function (kind) {
  29470. if (this.onGeometryUpdated) {
  29471. this.onGeometryUpdated(this, kind);
  29472. }
  29473. };
  29474. Geometry.prototype.load = function (scene, onLoaded) {
  29475. var _this = this;
  29476. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29477. return;
  29478. }
  29479. if (this.isReady()) {
  29480. if (onLoaded) {
  29481. onLoaded();
  29482. }
  29483. return;
  29484. }
  29485. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29486. scene._addPendingData(this);
  29487. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29488. _this._delayLoadingFunction(JSON.parse(data), _this);
  29489. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29490. _this._delayInfo = [];
  29491. scene._removePendingData(_this);
  29492. var meshes = _this._meshes;
  29493. var numOfMeshes = meshes.length;
  29494. for (var index = 0; index < numOfMeshes; index++) {
  29495. _this._applyToMesh(meshes[index]);
  29496. }
  29497. if (onLoaded) {
  29498. onLoaded();
  29499. }
  29500. }, function () { }, scene.database);
  29501. };
  29502. Geometry.prototype.isDisposed = function () {
  29503. return this._isDisposed;
  29504. };
  29505. Geometry.prototype.dispose = function () {
  29506. var meshes = this._meshes;
  29507. var numOfMeshes = meshes.length;
  29508. var index;
  29509. for (index = 0; index < numOfMeshes; index++) {
  29510. this.releaseForMesh(meshes[index]);
  29511. }
  29512. this._meshes = [];
  29513. for (var kind in this._vertexBuffers) {
  29514. this._vertexBuffers[kind].dispose();
  29515. }
  29516. this._vertexBuffers = [];
  29517. this._totalVertices = 0;
  29518. if (this._indexBuffer) {
  29519. this._engine._releaseBuffer(this._indexBuffer);
  29520. }
  29521. this._indexBuffer = null;
  29522. this._indices = [];
  29523. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29524. this.delayLoadingFile = null;
  29525. this._delayLoadingFunction = null;
  29526. this._delayInfo = [];
  29527. this._boundingInfo = null; // todo: .dispose()
  29528. this._scene.removeGeometry(this);
  29529. this._isDisposed = true;
  29530. };
  29531. Geometry.prototype.copy = function (id) {
  29532. var vertexData = new BABYLON.VertexData();
  29533. vertexData.indices = [];
  29534. var indices = this.getIndices();
  29535. for (var index = 0; index < indices.length; index++) {
  29536. vertexData.indices.push(indices[index]);
  29537. }
  29538. var updatable = false;
  29539. var stopChecking = false;
  29540. var kind;
  29541. for (kind in this._vertexBuffers) {
  29542. // using slice() to make a copy of the array and not just reference it
  29543. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  29544. if (!stopChecking) {
  29545. updatable = this.getVertexBuffer(kind).isUpdatable();
  29546. stopChecking = !updatable;
  29547. }
  29548. }
  29549. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29550. geometry.delayLoadState = this.delayLoadState;
  29551. geometry.delayLoadingFile = this.delayLoadingFile;
  29552. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29553. for (kind in this._delayInfo) {
  29554. geometry._delayInfo = geometry._delayInfo || [];
  29555. geometry._delayInfo.push(kind);
  29556. }
  29557. // Bounding info
  29558. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  29559. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29560. return geometry;
  29561. };
  29562. // Statics
  29563. Geometry.ExtractFromMesh = function (mesh, id) {
  29564. var geometry = mesh._geometry;
  29565. if (!geometry) {
  29566. return null;
  29567. }
  29568. return geometry.copy(id);
  29569. };
  29570. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29571. // be aware Math.random() could cause collisions
  29572. Geometry.RandomId = function () {
  29573. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  29574. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  29575. return v.toString(16);
  29576. });
  29577. };
  29578. return Geometry;
  29579. })();
  29580. BABYLON.Geometry = Geometry;
  29581. /////// Primitives //////////////////////////////////////////////
  29582. var Geometry;
  29583. (function (Geometry) {
  29584. var Primitives;
  29585. (function (Primitives) {
  29586. /// Abstract class
  29587. var _Primitive = (function (_super) {
  29588. __extends(_Primitive, _super);
  29589. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  29590. this._beingRegenerated = true;
  29591. this._canBeRegenerated = canBeRegenerated;
  29592. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  29593. this._beingRegenerated = false;
  29594. }
  29595. _Primitive.prototype.canBeRegenerated = function () {
  29596. return this._canBeRegenerated;
  29597. };
  29598. _Primitive.prototype.regenerate = function () {
  29599. if (!this._canBeRegenerated) {
  29600. return;
  29601. }
  29602. this._beingRegenerated = true;
  29603. this.setAllVerticesData(this._regenerateVertexData(), false);
  29604. this._beingRegenerated = false;
  29605. };
  29606. _Primitive.prototype.asNewGeometry = function (id) {
  29607. return _super.prototype.copy.call(this, id);
  29608. };
  29609. // overrides
  29610. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29611. if (!this._beingRegenerated) {
  29612. return;
  29613. }
  29614. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29615. };
  29616. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29617. if (!this._beingRegenerated) {
  29618. return;
  29619. }
  29620. _super.prototype.setVerticesData.call(this, kind, data, false);
  29621. };
  29622. // to override
  29623. // protected
  29624. _Primitive.prototype._regenerateVertexData = function () {
  29625. throw new Error("Abstract method");
  29626. };
  29627. _Primitive.prototype.copy = function (id) {
  29628. throw new Error("Must be overriden in sub-classes.");
  29629. };
  29630. return _Primitive;
  29631. })(Geometry);
  29632. Primitives._Primitive = _Primitive;
  29633. var Ribbon = (function (_super) {
  29634. __extends(Ribbon, _super);
  29635. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29636. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29637. this.pathArray = pathArray;
  29638. this.closeArray = closeArray;
  29639. this.closePath = closePath;
  29640. this.offset = offset;
  29641. this.side = side;
  29642. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29643. }
  29644. Ribbon.prototype._regenerateVertexData = function () {
  29645. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29646. };
  29647. Ribbon.prototype.copy = function (id) {
  29648. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29649. };
  29650. return Ribbon;
  29651. })(_Primitive);
  29652. Primitives.Ribbon = Ribbon;
  29653. var Box = (function (_super) {
  29654. __extends(Box, _super);
  29655. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29656. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29657. this.size = size;
  29658. this.side = side;
  29659. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29660. }
  29661. Box.prototype._regenerateVertexData = function () {
  29662. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29663. };
  29664. Box.prototype.copy = function (id) {
  29665. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29666. };
  29667. return Box;
  29668. })(_Primitive);
  29669. Primitives.Box = Box;
  29670. var Sphere = (function (_super) {
  29671. __extends(Sphere, _super);
  29672. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29673. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29674. this.segments = segments;
  29675. this.diameter = diameter;
  29676. this.side = side;
  29677. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29678. }
  29679. Sphere.prototype._regenerateVertexData = function () {
  29680. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29681. };
  29682. Sphere.prototype.copy = function (id) {
  29683. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29684. };
  29685. return Sphere;
  29686. })(_Primitive);
  29687. Primitives.Sphere = Sphere;
  29688. var Disc = (function (_super) {
  29689. __extends(Disc, _super);
  29690. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29691. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29692. this.radius = radius;
  29693. this.tessellation = tessellation;
  29694. this.side = side;
  29695. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29696. }
  29697. Disc.prototype._regenerateVertexData = function () {
  29698. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29699. };
  29700. Disc.prototype.copy = function (id) {
  29701. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29702. };
  29703. return Disc;
  29704. })(_Primitive);
  29705. Primitives.Disc = Disc;
  29706. var Cylinder = (function (_super) {
  29707. __extends(Cylinder, _super);
  29708. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29709. if (subdivisions === void 0) { subdivisions = 1; }
  29710. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29711. this.height = height;
  29712. this.diameterTop = diameterTop;
  29713. this.diameterBottom = diameterBottom;
  29714. this.tessellation = tessellation;
  29715. this.subdivisions = subdivisions;
  29716. this.side = side;
  29717. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29718. }
  29719. Cylinder.prototype._regenerateVertexData = function () {
  29720. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29721. };
  29722. Cylinder.prototype.copy = function (id) {
  29723. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29724. };
  29725. return Cylinder;
  29726. })(_Primitive);
  29727. Primitives.Cylinder = Cylinder;
  29728. var Torus = (function (_super) {
  29729. __extends(Torus, _super);
  29730. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29731. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29732. this.diameter = diameter;
  29733. this.thickness = thickness;
  29734. this.tessellation = tessellation;
  29735. this.side = side;
  29736. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29737. }
  29738. Torus.prototype._regenerateVertexData = function () {
  29739. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29740. };
  29741. Torus.prototype.copy = function (id) {
  29742. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29743. };
  29744. return Torus;
  29745. })(_Primitive);
  29746. Primitives.Torus = Torus;
  29747. var Ground = (function (_super) {
  29748. __extends(Ground, _super);
  29749. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29750. this.width = width;
  29751. this.height = height;
  29752. this.subdivisions = subdivisions;
  29753. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29754. }
  29755. Ground.prototype._regenerateVertexData = function () {
  29756. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29757. };
  29758. Ground.prototype.copy = function (id) {
  29759. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29760. };
  29761. return Ground;
  29762. })(_Primitive);
  29763. Primitives.Ground = Ground;
  29764. var TiledGround = (function (_super) {
  29765. __extends(TiledGround, _super);
  29766. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29767. this.xmin = xmin;
  29768. this.zmin = zmin;
  29769. this.xmax = xmax;
  29770. this.zmax = zmax;
  29771. this.subdivisions = subdivisions;
  29772. this.precision = precision;
  29773. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29774. }
  29775. TiledGround.prototype._regenerateVertexData = function () {
  29776. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29777. };
  29778. TiledGround.prototype.copy = function (id) {
  29779. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29780. };
  29781. return TiledGround;
  29782. })(_Primitive);
  29783. Primitives.TiledGround = TiledGround;
  29784. var Plane = (function (_super) {
  29785. __extends(Plane, _super);
  29786. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29787. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29788. this.size = size;
  29789. this.side = side;
  29790. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29791. }
  29792. Plane.prototype._regenerateVertexData = function () {
  29793. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29794. };
  29795. Plane.prototype.copy = function (id) {
  29796. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29797. };
  29798. return Plane;
  29799. })(_Primitive);
  29800. Primitives.Plane = Plane;
  29801. var TorusKnot = (function (_super) {
  29802. __extends(TorusKnot, _super);
  29803. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29804. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29805. this.radius = radius;
  29806. this.tube = tube;
  29807. this.radialSegments = radialSegments;
  29808. this.tubularSegments = tubularSegments;
  29809. this.p = p;
  29810. this.q = q;
  29811. this.side = side;
  29812. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29813. }
  29814. TorusKnot.prototype._regenerateVertexData = function () {
  29815. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  29816. };
  29817. TorusKnot.prototype.copy = function (id) {
  29818. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29819. };
  29820. return TorusKnot;
  29821. })(_Primitive);
  29822. Primitives.TorusKnot = TorusKnot;
  29823. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29824. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29825. })(BABYLON || (BABYLON = {}));
  29826. var BABYLON;
  29827. (function (BABYLON) {
  29828. var GroundMesh = (function (_super) {
  29829. __extends(GroundMesh, _super);
  29830. function GroundMesh(name, scene) {
  29831. _super.call(this, name, scene);
  29832. this.generateOctree = false;
  29833. this._worldInverse = new BABYLON.Matrix();
  29834. }
  29835. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  29836. get: function () {
  29837. return this._subdivisions;
  29838. },
  29839. enumerable: true,
  29840. configurable: true
  29841. });
  29842. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  29843. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  29844. this._subdivisions = chunksCount;
  29845. this.subdivide(this._subdivisions);
  29846. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  29847. };
  29848. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29849. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  29850. this.getWorldMatrix().invertToRef(this._worldInverse);
  29851. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  29852. var pickInfo = this.intersects(ray);
  29853. if (pickInfo.hit) {
  29854. return pickInfo.pickedPoint.y;
  29855. }
  29856. return 0;
  29857. };
  29858. return GroundMesh;
  29859. })(BABYLON.Mesh);
  29860. BABYLON.GroundMesh = GroundMesh;
  29861. })(BABYLON || (BABYLON = {}));
  29862. var BABYLON;
  29863. (function (BABYLON) {
  29864. var LinesMesh = (function (_super) {
  29865. __extends(LinesMesh, _super);
  29866. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29867. if (parent === void 0) { parent = null; }
  29868. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29869. this.color = new BABYLON.Color3(1, 1, 1);
  29870. this.alpha = 1;
  29871. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29872. attributes: ["position"],
  29873. uniforms: ["worldViewProjection", "color"],
  29874. needAlphaBlending: true
  29875. });
  29876. }
  29877. Object.defineProperty(LinesMesh.prototype, "material", {
  29878. get: function () {
  29879. return this._colorShader;
  29880. },
  29881. enumerable: true,
  29882. configurable: true
  29883. });
  29884. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29885. get: function () {
  29886. return false;
  29887. },
  29888. enumerable: true,
  29889. configurable: true
  29890. });
  29891. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29892. get: function () {
  29893. return false;
  29894. },
  29895. enumerable: true,
  29896. configurable: true
  29897. });
  29898. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29899. var engine = this.getScene().getEngine();
  29900. var indexToBind = this._geometry.getIndexBuffer();
  29901. // VBOs
  29902. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29903. // Color
  29904. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29905. };
  29906. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29907. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29908. return;
  29909. }
  29910. var engine = this.getScene().getEngine();
  29911. // Draw order
  29912. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29913. };
  29914. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29915. return null;
  29916. };
  29917. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29918. this._colorShader.dispose();
  29919. _super.prototype.dispose.call(this, doNotRecurse);
  29920. };
  29921. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29922. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29923. };
  29924. return LinesMesh;
  29925. })(BABYLON.Mesh);
  29926. BABYLON.LinesMesh = LinesMesh;
  29927. })(BABYLON || (BABYLON = {}));
  29928. var BABYLON;
  29929. (function (BABYLON) {
  29930. var OutlineRenderer = (function () {
  29931. function OutlineRenderer(scene) {
  29932. this._scene = scene;
  29933. }
  29934. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  29935. var _this = this;
  29936. if (useOverlay === void 0) { useOverlay = false; }
  29937. var scene = this._scene;
  29938. var engine = this._scene.getEngine();
  29939. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29940. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29941. return;
  29942. }
  29943. var mesh = subMesh.getRenderingMesh();
  29944. var material = subMesh.getMaterial();
  29945. engine.enableEffect(this._effect);
  29946. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29947. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29948. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29949. // Bones
  29950. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29951. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29952. }
  29953. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29954. // Alpha test
  29955. if (material && material.needAlphaTesting()) {
  29956. var alphaTexture = material.getAlphaTestTexture();
  29957. this._effect.setTexture("diffuseSampler", alphaTexture);
  29958. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29959. }
  29960. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29961. };
  29962. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29963. var defines = [];
  29964. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29965. var mesh = subMesh.getMesh();
  29966. var material = subMesh.getMaterial();
  29967. // Alpha test
  29968. if (material && material.needAlphaTesting()) {
  29969. defines.push("#define ALPHATEST");
  29970. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29971. attribs.push(BABYLON.VertexBuffer.UVKind);
  29972. defines.push("#define UV1");
  29973. }
  29974. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29975. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29976. defines.push("#define UV2");
  29977. }
  29978. }
  29979. // Bones
  29980. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29981. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29982. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29983. defines.push("#define BONES");
  29984. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29985. }
  29986. // Instances
  29987. if (useInstances) {
  29988. defines.push("#define INSTANCES");
  29989. attribs.push("world0");
  29990. attribs.push("world1");
  29991. attribs.push("world2");
  29992. attribs.push("world3");
  29993. }
  29994. // Get correct effect
  29995. var join = defines.join("\n");
  29996. if (this._cachedDefines !== join) {
  29997. this._cachedDefines = join;
  29998. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29999. }
  30000. return this._effect.isReady();
  30001. };
  30002. return OutlineRenderer;
  30003. })();
  30004. BABYLON.OutlineRenderer = OutlineRenderer;
  30005. })(BABYLON || (BABYLON = {}));
  30006. var BABYLON;
  30007. (function (BABYLON) {
  30008. var MeshAssetTask = (function () {
  30009. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  30010. this.name = name;
  30011. this.meshesNames = meshesNames;
  30012. this.rootUrl = rootUrl;
  30013. this.sceneFilename = sceneFilename;
  30014. this.isCompleted = false;
  30015. }
  30016. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30017. var _this = this;
  30018. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  30019. _this.loadedMeshes = meshes;
  30020. _this.loadedParticleSystems = particleSystems;
  30021. _this.loadedSkeletons = skeletons;
  30022. _this.isCompleted = true;
  30023. if (_this.onSuccess) {
  30024. _this.onSuccess(_this);
  30025. }
  30026. onSuccess();
  30027. }, null, function () {
  30028. if (_this.onError) {
  30029. _this.onError(_this);
  30030. }
  30031. onError();
  30032. });
  30033. };
  30034. return MeshAssetTask;
  30035. })();
  30036. BABYLON.MeshAssetTask = MeshAssetTask;
  30037. var TextFileAssetTask = (function () {
  30038. function TextFileAssetTask(name, url) {
  30039. this.name = name;
  30040. this.url = url;
  30041. this.isCompleted = false;
  30042. }
  30043. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30044. var _this = this;
  30045. BABYLON.Tools.LoadFile(this.url, function (data) {
  30046. _this.text = data;
  30047. _this.isCompleted = true;
  30048. if (_this.onSuccess) {
  30049. _this.onSuccess(_this);
  30050. }
  30051. onSuccess();
  30052. }, null, scene.database, false, function () {
  30053. if (_this.onError) {
  30054. _this.onError(_this);
  30055. }
  30056. onError();
  30057. });
  30058. };
  30059. return TextFileAssetTask;
  30060. })();
  30061. BABYLON.TextFileAssetTask = TextFileAssetTask;
  30062. var BinaryFileAssetTask = (function () {
  30063. function BinaryFileAssetTask(name, url) {
  30064. this.name = name;
  30065. this.url = url;
  30066. this.isCompleted = false;
  30067. }
  30068. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30069. var _this = this;
  30070. BABYLON.Tools.LoadFile(this.url, function (data) {
  30071. _this.data = data;
  30072. _this.isCompleted = true;
  30073. if (_this.onSuccess) {
  30074. _this.onSuccess(_this);
  30075. }
  30076. onSuccess();
  30077. }, null, scene.database, true, function () {
  30078. if (_this.onError) {
  30079. _this.onError(_this);
  30080. }
  30081. onError();
  30082. });
  30083. };
  30084. return BinaryFileAssetTask;
  30085. })();
  30086. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  30087. var ImageAssetTask = (function () {
  30088. function ImageAssetTask(name, url) {
  30089. this.name = name;
  30090. this.url = url;
  30091. this.isCompleted = false;
  30092. }
  30093. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30094. var _this = this;
  30095. var img = new Image();
  30096. img.onload = function () {
  30097. _this.image = img;
  30098. _this.isCompleted = true;
  30099. if (_this.onSuccess) {
  30100. _this.onSuccess(_this);
  30101. }
  30102. onSuccess();
  30103. };
  30104. img.onerror = function () {
  30105. if (_this.onError) {
  30106. _this.onError(_this);
  30107. }
  30108. onError();
  30109. };
  30110. img.src = this.url;
  30111. };
  30112. return ImageAssetTask;
  30113. })();
  30114. BABYLON.ImageAssetTask = ImageAssetTask;
  30115. var TextureAssetTask = (function () {
  30116. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  30117. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30118. this.name = name;
  30119. this.url = url;
  30120. this.noMipmap = noMipmap;
  30121. this.invertY = invertY;
  30122. this.samplingMode = samplingMode;
  30123. this.isCompleted = false;
  30124. }
  30125. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30126. var _this = this;
  30127. var onload = function () {
  30128. _this.isCompleted = true;
  30129. if (_this.onSuccess) {
  30130. _this.onSuccess(_this);
  30131. }
  30132. onSuccess();
  30133. };
  30134. var onerror = function () {
  30135. if (_this.onError) {
  30136. _this.onError(_this);
  30137. }
  30138. onError();
  30139. };
  30140. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  30141. };
  30142. return TextureAssetTask;
  30143. })();
  30144. BABYLON.TextureAssetTask = TextureAssetTask;
  30145. var AssetsManager = (function () {
  30146. function AssetsManager(scene) {
  30147. this._tasks = new Array();
  30148. this._waitingTasksCount = 0;
  30149. this.useDefaultLoadingScreen = true;
  30150. this._scene = scene;
  30151. }
  30152. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  30153. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  30154. this._tasks.push(task);
  30155. return task;
  30156. };
  30157. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  30158. var task = new TextFileAssetTask(taskName, url);
  30159. this._tasks.push(task);
  30160. return task;
  30161. };
  30162. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  30163. var task = new BinaryFileAssetTask(taskName, url);
  30164. this._tasks.push(task);
  30165. return task;
  30166. };
  30167. AssetsManager.prototype.addImageTask = function (taskName, url) {
  30168. var task = new ImageAssetTask(taskName, url);
  30169. this._tasks.push(task);
  30170. return task;
  30171. };
  30172. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  30173. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30174. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  30175. this._tasks.push(task);
  30176. return task;
  30177. };
  30178. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  30179. this._waitingTasksCount--;
  30180. if (this._waitingTasksCount === 0) {
  30181. if (this.onFinish) {
  30182. this.onFinish(this._tasks);
  30183. }
  30184. this._scene.getEngine().hideLoadingUI();
  30185. }
  30186. };
  30187. AssetsManager.prototype._runTask = function (task) {
  30188. var _this = this;
  30189. task.run(this._scene, function () {
  30190. if (_this.onTaskSuccess) {
  30191. _this.onTaskSuccess(task);
  30192. }
  30193. _this._decreaseWaitingTasksCount();
  30194. }, function () {
  30195. if (_this.onTaskError) {
  30196. _this.onTaskError(task);
  30197. }
  30198. _this._decreaseWaitingTasksCount();
  30199. });
  30200. };
  30201. AssetsManager.prototype.reset = function () {
  30202. this._tasks = new Array();
  30203. return this;
  30204. };
  30205. AssetsManager.prototype.load = function () {
  30206. this._waitingTasksCount = this._tasks.length;
  30207. if (this._waitingTasksCount === 0) {
  30208. if (this.onFinish) {
  30209. this.onFinish(this._tasks);
  30210. }
  30211. return this;
  30212. }
  30213. if (this.useDefaultLoadingScreen) {
  30214. this._scene.getEngine().displayLoadingUI();
  30215. }
  30216. for (var index = 0; index < this._tasks.length; index++) {
  30217. var task = this._tasks[index];
  30218. this._runTask(task);
  30219. }
  30220. return this;
  30221. };
  30222. return AssetsManager;
  30223. })();
  30224. BABYLON.AssetsManager = AssetsManager;
  30225. })(BABYLON || (BABYLON = {}));
  30226. var BABYLON;
  30227. (function (BABYLON) {
  30228. var VRDeviceOrientationFreeCamera = (function (_super) {
  30229. __extends(VRDeviceOrientationFreeCamera, _super);
  30230. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  30231. if (compensateDistortion === void 0) { compensateDistortion = true; }
  30232. _super.call(this, name, position, scene);
  30233. this._alpha = 0;
  30234. this._beta = 0;
  30235. this._gamma = 0;
  30236. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30237. metrics.compensateDistortion = compensateDistortion;
  30238. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30239. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  30240. }
  30241. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  30242. this._alpha = +evt.alpha | 0;
  30243. this._beta = +evt.beta | 0;
  30244. this._gamma = +evt.gamma | 0;
  30245. if (this._gamma < 0) {
  30246. this._gamma = 90 + this._gamma;
  30247. }
  30248. else {
  30249. // Incline it in the correct angle.
  30250. this._gamma = 270 - this._gamma;
  30251. }
  30252. this.rotation.x = this._gamma / 180.0 * Math.PI;
  30253. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  30254. this.rotation.z = this._beta / 180.0 * Math.PI;
  30255. };
  30256. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30257. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30258. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  30259. };
  30260. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  30261. _super.prototype.detachControl.call(this, element);
  30262. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  30263. };
  30264. return VRDeviceOrientationFreeCamera;
  30265. })(BABYLON.FreeCamera);
  30266. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  30267. })(BABYLON || (BABYLON = {}));
  30268. var BABYLON;
  30269. (function (BABYLON) {
  30270. var WebVRFreeCamera = (function (_super) {
  30271. __extends(WebVRFreeCamera, _super);
  30272. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  30273. if (compensateDistortion === void 0) { compensateDistortion = true; }
  30274. _super.call(this, name, position, scene);
  30275. this._hmdDevice = null;
  30276. this._sensorDevice = null;
  30277. this._cacheState = null;
  30278. this._cacheQuaternion = new BABYLON.Quaternion();
  30279. this._cacheRotation = BABYLON.Vector3.Zero();
  30280. this._vrEnabled = false;
  30281. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30282. metrics.compensateDistortion = compensateDistortion;
  30283. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30284. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  30285. }
  30286. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  30287. var size = devices.length;
  30288. var i = 0;
  30289. // Reset devices.
  30290. this._sensorDevice = null;
  30291. this._hmdDevice = null;
  30292. // Search for a HmdDevice.
  30293. while (i < size && this._hmdDevice === null) {
  30294. if (devices[i] instanceof HMDVRDevice) {
  30295. this._hmdDevice = devices[i];
  30296. }
  30297. i++;
  30298. }
  30299. i = 0;
  30300. while (i < size && this._sensorDevice === null) {
  30301. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  30302. this._sensorDevice = devices[i];
  30303. }
  30304. i++;
  30305. }
  30306. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  30307. };
  30308. WebVRFreeCamera.prototype._checkInputs = function () {
  30309. if (this._vrEnabled) {
  30310. this._cacheState = this._sensorDevice.getState();
  30311. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  30312. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  30313. this.rotation.x = -this._cacheRotation.z;
  30314. this.rotation.y = -this._cacheRotation.y;
  30315. this.rotation.z = this._cacheRotation.x;
  30316. }
  30317. _super.prototype._checkInputs.call(this);
  30318. };
  30319. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30320. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30321. if (navigator.getVRDevices) {
  30322. navigator.getVRDevices().then(this._getWebVRDevices);
  30323. }
  30324. else if (navigator.mozGetVRDevices) {
  30325. navigator.mozGetVRDevices(this._getWebVRDevices);
  30326. }
  30327. };
  30328. WebVRFreeCamera.prototype.detachControl = function (element) {
  30329. _super.prototype.detachControl.call(this, element);
  30330. this._vrEnabled = false;
  30331. };
  30332. return WebVRFreeCamera;
  30333. })(BABYLON.FreeCamera);
  30334. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  30335. })(BABYLON || (BABYLON = {}));
  30336. var BABYLON;
  30337. (function (BABYLON) {
  30338. // Standard optimizations
  30339. var SceneOptimization = (function () {
  30340. function SceneOptimization(priority) {
  30341. if (priority === void 0) { priority = 0; }
  30342. this.priority = priority;
  30343. this.apply = function (scene) {
  30344. return true; // Return true if everything that can be done was applied
  30345. };
  30346. }
  30347. return SceneOptimization;
  30348. })();
  30349. BABYLON.SceneOptimization = SceneOptimization;
  30350. var TextureOptimization = (function (_super) {
  30351. __extends(TextureOptimization, _super);
  30352. function TextureOptimization(priority, maximumSize) {
  30353. var _this = this;
  30354. if (priority === void 0) { priority = 0; }
  30355. if (maximumSize === void 0) { maximumSize = 1024; }
  30356. _super.call(this, priority);
  30357. this.priority = priority;
  30358. this.maximumSize = maximumSize;
  30359. this.apply = function (scene) {
  30360. var allDone = true;
  30361. for (var index = 0; index < scene.textures.length; index++) {
  30362. var texture = scene.textures[index];
  30363. if (!texture.canRescale) {
  30364. continue;
  30365. }
  30366. var currentSize = texture.getSize();
  30367. var maxDimension = Math.max(currentSize.width, currentSize.height);
  30368. if (maxDimension > _this.maximumSize) {
  30369. texture.scale(0.5);
  30370. allDone = false;
  30371. }
  30372. }
  30373. return allDone;
  30374. };
  30375. }
  30376. return TextureOptimization;
  30377. })(SceneOptimization);
  30378. BABYLON.TextureOptimization = TextureOptimization;
  30379. var HardwareScalingOptimization = (function (_super) {
  30380. __extends(HardwareScalingOptimization, _super);
  30381. function HardwareScalingOptimization(priority, maximumScale) {
  30382. var _this = this;
  30383. if (priority === void 0) { priority = 0; }
  30384. if (maximumScale === void 0) { maximumScale = 2; }
  30385. _super.call(this, priority);
  30386. this.priority = priority;
  30387. this.maximumScale = maximumScale;
  30388. this._currentScale = 1;
  30389. this.apply = function (scene) {
  30390. _this._currentScale++;
  30391. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  30392. return _this._currentScale >= _this.maximumScale;
  30393. };
  30394. }
  30395. return HardwareScalingOptimization;
  30396. })(SceneOptimization);
  30397. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  30398. var ShadowsOptimization = (function (_super) {
  30399. __extends(ShadowsOptimization, _super);
  30400. function ShadowsOptimization() {
  30401. _super.apply(this, arguments);
  30402. this.apply = function (scene) {
  30403. scene.shadowsEnabled = false;
  30404. return true;
  30405. };
  30406. }
  30407. return ShadowsOptimization;
  30408. })(SceneOptimization);
  30409. BABYLON.ShadowsOptimization = ShadowsOptimization;
  30410. var PostProcessesOptimization = (function (_super) {
  30411. __extends(PostProcessesOptimization, _super);
  30412. function PostProcessesOptimization() {
  30413. _super.apply(this, arguments);
  30414. this.apply = function (scene) {
  30415. scene.postProcessesEnabled = false;
  30416. return true;
  30417. };
  30418. }
  30419. return PostProcessesOptimization;
  30420. })(SceneOptimization);
  30421. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  30422. var LensFlaresOptimization = (function (_super) {
  30423. __extends(LensFlaresOptimization, _super);
  30424. function LensFlaresOptimization() {
  30425. _super.apply(this, arguments);
  30426. this.apply = function (scene) {
  30427. scene.lensFlaresEnabled = false;
  30428. return true;
  30429. };
  30430. }
  30431. return LensFlaresOptimization;
  30432. })(SceneOptimization);
  30433. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  30434. var ParticlesOptimization = (function (_super) {
  30435. __extends(ParticlesOptimization, _super);
  30436. function ParticlesOptimization() {
  30437. _super.apply(this, arguments);
  30438. this.apply = function (scene) {
  30439. scene.particlesEnabled = false;
  30440. return true;
  30441. };
  30442. }
  30443. return ParticlesOptimization;
  30444. })(SceneOptimization);
  30445. BABYLON.ParticlesOptimization = ParticlesOptimization;
  30446. var RenderTargetsOptimization = (function (_super) {
  30447. __extends(RenderTargetsOptimization, _super);
  30448. function RenderTargetsOptimization() {
  30449. _super.apply(this, arguments);
  30450. this.apply = function (scene) {
  30451. scene.renderTargetsEnabled = false;
  30452. return true;
  30453. };
  30454. }
  30455. return RenderTargetsOptimization;
  30456. })(SceneOptimization);
  30457. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  30458. var MergeMeshesOptimization = (function (_super) {
  30459. __extends(MergeMeshesOptimization, _super);
  30460. function MergeMeshesOptimization() {
  30461. var _this = this;
  30462. _super.apply(this, arguments);
  30463. this._canBeMerged = function (abstractMesh) {
  30464. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  30465. return false;
  30466. }
  30467. var mesh = abstractMesh;
  30468. if (!mesh.isVisible || !mesh.isEnabled()) {
  30469. return false;
  30470. }
  30471. if (mesh.instances.length > 0) {
  30472. return false;
  30473. }
  30474. if (mesh.skeleton || mesh.hasLODLevels) {
  30475. return false;
  30476. }
  30477. return true;
  30478. };
  30479. this.apply = function (scene, updateSelectionTree) {
  30480. var globalPool = scene.meshes.slice(0);
  30481. var globalLength = globalPool.length;
  30482. for (var index = 0; index < globalLength; index++) {
  30483. var currentPool = new Array();
  30484. var current = globalPool[index];
  30485. // Checks
  30486. if (!_this._canBeMerged(current)) {
  30487. continue;
  30488. }
  30489. currentPool.push(current);
  30490. // Find compatible meshes
  30491. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  30492. var otherMesh = globalPool[subIndex];
  30493. if (!_this._canBeMerged(otherMesh)) {
  30494. continue;
  30495. }
  30496. if (otherMesh.material !== current.material) {
  30497. continue;
  30498. }
  30499. if (otherMesh.checkCollisions !== current.checkCollisions) {
  30500. continue;
  30501. }
  30502. currentPool.push(otherMesh);
  30503. globalLength--;
  30504. globalPool.splice(subIndex, 1);
  30505. subIndex--;
  30506. }
  30507. if (currentPool.length < 2) {
  30508. continue;
  30509. }
  30510. // Merge meshes
  30511. BABYLON.Mesh.MergeMeshes(currentPool);
  30512. }
  30513. if (updateSelectionTree != undefined) {
  30514. if (updateSelectionTree) {
  30515. scene.createOrUpdateSelectionOctree();
  30516. }
  30517. }
  30518. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  30519. scene.createOrUpdateSelectionOctree();
  30520. }
  30521. return true;
  30522. };
  30523. }
  30524. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  30525. get: function () {
  30526. return MergeMeshesOptimization._UpdateSelectionTree;
  30527. },
  30528. set: function (value) {
  30529. MergeMeshesOptimization._UpdateSelectionTree = value;
  30530. },
  30531. enumerable: true,
  30532. configurable: true
  30533. });
  30534. MergeMeshesOptimization._UpdateSelectionTree = false;
  30535. return MergeMeshesOptimization;
  30536. })(SceneOptimization);
  30537. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  30538. // Options
  30539. var SceneOptimizerOptions = (function () {
  30540. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  30541. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  30542. if (trackerDuration === void 0) { trackerDuration = 2000; }
  30543. this.targetFrameRate = targetFrameRate;
  30544. this.trackerDuration = trackerDuration;
  30545. this.optimizations = new Array();
  30546. }
  30547. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  30548. var result = new SceneOptimizerOptions(targetFrameRate);
  30549. var priority = 0;
  30550. result.optimizations.push(new MergeMeshesOptimization(priority));
  30551. result.optimizations.push(new ShadowsOptimization(priority));
  30552. result.optimizations.push(new LensFlaresOptimization(priority));
  30553. // Next priority
  30554. priority++;
  30555. result.optimizations.push(new PostProcessesOptimization(priority));
  30556. result.optimizations.push(new ParticlesOptimization(priority));
  30557. // Next priority
  30558. priority++;
  30559. result.optimizations.push(new TextureOptimization(priority, 1024));
  30560. return result;
  30561. };
  30562. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  30563. var result = new SceneOptimizerOptions(targetFrameRate);
  30564. var priority = 0;
  30565. result.optimizations.push(new MergeMeshesOptimization(priority));
  30566. result.optimizations.push(new ShadowsOptimization(priority));
  30567. result.optimizations.push(new LensFlaresOptimization(priority));
  30568. // Next priority
  30569. priority++;
  30570. result.optimizations.push(new PostProcessesOptimization(priority));
  30571. result.optimizations.push(new ParticlesOptimization(priority));
  30572. // Next priority
  30573. priority++;
  30574. result.optimizations.push(new TextureOptimization(priority, 512));
  30575. // Next priority
  30576. priority++;
  30577. result.optimizations.push(new RenderTargetsOptimization(priority));
  30578. // Next priority
  30579. priority++;
  30580. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  30581. return result;
  30582. };
  30583. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  30584. var result = new SceneOptimizerOptions(targetFrameRate);
  30585. var priority = 0;
  30586. result.optimizations.push(new MergeMeshesOptimization(priority));
  30587. result.optimizations.push(new ShadowsOptimization(priority));
  30588. result.optimizations.push(new LensFlaresOptimization(priority));
  30589. // Next priority
  30590. priority++;
  30591. result.optimizations.push(new PostProcessesOptimization(priority));
  30592. result.optimizations.push(new ParticlesOptimization(priority));
  30593. // Next priority
  30594. priority++;
  30595. result.optimizations.push(new TextureOptimization(priority, 256));
  30596. // Next priority
  30597. priority++;
  30598. result.optimizations.push(new RenderTargetsOptimization(priority));
  30599. // Next priority
  30600. priority++;
  30601. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  30602. return result;
  30603. };
  30604. return SceneOptimizerOptions;
  30605. })();
  30606. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  30607. // Scene optimizer tool
  30608. var SceneOptimizer = (function () {
  30609. function SceneOptimizer() {
  30610. }
  30611. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  30612. // TODO: add an epsilon
  30613. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  30614. if (onSuccess) {
  30615. onSuccess();
  30616. }
  30617. return;
  30618. }
  30619. // Apply current level of optimizations
  30620. var allDone = true;
  30621. var noOptimizationApplied = true;
  30622. for (var index = 0; index < options.optimizations.length; index++) {
  30623. var optimization = options.optimizations[index];
  30624. if (optimization.priority === currentPriorityLevel) {
  30625. noOptimizationApplied = false;
  30626. allDone = allDone && optimization.apply(scene);
  30627. }
  30628. }
  30629. // If no optimization was applied, this is a failure :(
  30630. if (noOptimizationApplied) {
  30631. if (onFailure) {
  30632. onFailure();
  30633. }
  30634. return;
  30635. }
  30636. // If all optimizations were done, move to next level
  30637. if (allDone) {
  30638. currentPriorityLevel++;
  30639. }
  30640. // Let's the system running for a specific amount of time before checking FPS
  30641. scene.executeWhenReady(function () {
  30642. setTimeout(function () {
  30643. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  30644. }, options.trackerDuration);
  30645. });
  30646. };
  30647. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  30648. if (!options) {
  30649. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  30650. }
  30651. // Let's the system running for a specific amount of time before checking FPS
  30652. scene.executeWhenReady(function () {
  30653. setTimeout(function () {
  30654. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  30655. }, options.trackerDuration);
  30656. });
  30657. };
  30658. return SceneOptimizer;
  30659. })();
  30660. BABYLON.SceneOptimizer = SceneOptimizer;
  30661. })(BABYLON || (BABYLON = {}));
  30662. var BABYLON;
  30663. (function (BABYLON) {
  30664. var Internals;
  30665. (function (Internals) {
  30666. var MeshLODLevel = (function () {
  30667. function MeshLODLevel(distance, mesh) {
  30668. this.distance = distance;
  30669. this.mesh = mesh;
  30670. }
  30671. return MeshLODLevel;
  30672. })();
  30673. Internals.MeshLODLevel = MeshLODLevel;
  30674. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30675. })(BABYLON || (BABYLON = {}));
  30676. var BABYLON;
  30677. (function (BABYLON) {
  30678. var AudioEngine = (function () {
  30679. function AudioEngine() {
  30680. this._audioContext = null;
  30681. this._audioContextInitialized = false;
  30682. this.canUseWebAudio = false;
  30683. this.WarnedWebAudioUnsupported = false;
  30684. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  30685. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  30686. this.canUseWebAudio = true;
  30687. }
  30688. }
  30689. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  30690. get: function () {
  30691. if (!this._audioContextInitialized) {
  30692. this._initializeAudioContext();
  30693. }
  30694. return this._audioContext;
  30695. },
  30696. enumerable: true,
  30697. configurable: true
  30698. });
  30699. AudioEngine.prototype._initializeAudioContext = function () {
  30700. try {
  30701. if (this.canUseWebAudio) {
  30702. this._audioContext = new AudioContext();
  30703. // create a global volume gain node
  30704. this.masterGain = this._audioContext.createGain();
  30705. this.masterGain.gain.value = 1;
  30706. this.masterGain.connect(this._audioContext.destination);
  30707. this._audioContextInitialized = true;
  30708. }
  30709. }
  30710. catch (e) {
  30711. this.canUseWebAudio = false;
  30712. BABYLON.Tools.Error("Web Audio: " + e.message);
  30713. }
  30714. };
  30715. AudioEngine.prototype.dispose = function () {
  30716. if (this.canUseWebAudio && this._audioContextInitialized) {
  30717. if (this._connectedAnalyser) {
  30718. this._connectedAnalyser.stopDebugCanvas();
  30719. this._connectedAnalyser.dispose();
  30720. this.masterGain.disconnect();
  30721. this.masterGain.connect(this._audioContext.destination);
  30722. this._connectedAnalyser = null;
  30723. }
  30724. this.masterGain.gain.value = 1;
  30725. }
  30726. this.WarnedWebAudioUnsupported = false;
  30727. };
  30728. AudioEngine.prototype.getGlobalVolume = function () {
  30729. if (this.canUseWebAudio && this._audioContextInitialized) {
  30730. return this.masterGain.gain.value;
  30731. }
  30732. else {
  30733. return -1;
  30734. }
  30735. };
  30736. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  30737. if (this.canUseWebAudio && this._audioContextInitialized) {
  30738. this.masterGain.gain.value = newVolume;
  30739. }
  30740. };
  30741. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  30742. if (this._connectedAnalyser) {
  30743. this._connectedAnalyser.stopDebugCanvas();
  30744. }
  30745. if (this.canUseWebAudio && this._audioContextInitialized) {
  30746. this._connectedAnalyser = analyser;
  30747. this.masterGain.disconnect();
  30748. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  30749. }
  30750. };
  30751. return AudioEngine;
  30752. })();
  30753. BABYLON.AudioEngine = AudioEngine;
  30754. })(BABYLON || (BABYLON = {}));
  30755. var BABYLON;
  30756. (function (BABYLON) {
  30757. var Sound = (function () {
  30758. /**
  30759. * Create a sound and attach it to a scene
  30760. * @param name Name of your sound
  30761. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  30762. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  30763. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  30764. */
  30765. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  30766. var _this = this;
  30767. this.autoplay = false;
  30768. this.loop = false;
  30769. this.useCustomAttenuation = false;
  30770. this.spatialSound = false;
  30771. this.refDistance = 1;
  30772. this.rolloffFactor = 1;
  30773. this.maxDistance = 100;
  30774. this.distanceModel = "linear";
  30775. this._panningModel = "equalpower";
  30776. this._playbackRate = 1;
  30777. this._startTime = 0;
  30778. this._startOffset = 0;
  30779. this._position = BABYLON.Vector3.Zero();
  30780. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  30781. this._volume = 1;
  30782. this._isLoaded = false;
  30783. this._isReadyToPlay = false;
  30784. this.isPlaying = false;
  30785. this.isPaused = false;
  30786. this._isDirectional = false;
  30787. // Used if you'd like to create a directional sound.
  30788. // If not set, the sound will be omnidirectional
  30789. this._coneInnerAngle = 360;
  30790. this._coneOuterAngle = 360;
  30791. this._coneOuterGain = 0;
  30792. this._isOutputConnected = false;
  30793. this.name = name;
  30794. this._scene = scene;
  30795. this._readyToPlayCallback = readyToPlayCallback;
  30796. // Default custom attenuation function is a linear attenuation
  30797. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  30798. if (currentDistance < maxDistance) {
  30799. return currentVolume * (1 - currentDistance / maxDistance);
  30800. }
  30801. else {
  30802. return 0;
  30803. }
  30804. };
  30805. if (options) {
  30806. this.autoplay = options.autoplay || false;
  30807. this.loop = options.loop || false;
  30808. // if volume === 0, we need another way to check this option
  30809. if (options.volume !== undefined) {
  30810. this._volume = options.volume;
  30811. }
  30812. this.spatialSound = options.spatialSound || false;
  30813. this.maxDistance = options.maxDistance || 100;
  30814. this.useCustomAttenuation = options.useCustomAttenuation || false;
  30815. this.rolloffFactor = options.rolloffFactor || 1;
  30816. this.refDistance = options.refDistance || 1;
  30817. this.distanceModel = options.distanceModel || "linear";
  30818. this._playbackRate = options.playbackRate || 1;
  30819. }
  30820. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30821. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  30822. this._soundGain.gain.value = this._volume;
  30823. this._inputAudioNode = this._soundGain;
  30824. this._ouputAudioNode = this._soundGain;
  30825. if (this.spatialSound) {
  30826. this._createSpatialParameters();
  30827. }
  30828. this._scene.mainSoundTrack.AddSound(this);
  30829. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  30830. if (urlOrArrayBuffer) {
  30831. // If it's an URL
  30832. if (typeof (urlOrArrayBuffer) === "string") {
  30833. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  30834. }
  30835. else {
  30836. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  30837. this._soundLoaded(urlOrArrayBuffer);
  30838. }
  30839. else {
  30840. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  30841. }
  30842. }
  30843. }
  30844. }
  30845. else {
  30846. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  30847. this._scene.mainSoundTrack.AddSound(this);
  30848. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  30849. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  30850. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  30851. }
  30852. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  30853. if (this._readyToPlayCallback) {
  30854. window.setTimeout(function () {
  30855. _this._readyToPlayCallback();
  30856. }, 1000);
  30857. }
  30858. }
  30859. }
  30860. Sound.prototype.dispose = function () {
  30861. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30862. if (this.isPlaying) {
  30863. this.stop();
  30864. }
  30865. this._isReadyToPlay = false;
  30866. if (this.soundTrackId === -1) {
  30867. this._scene.mainSoundTrack.RemoveSound(this);
  30868. }
  30869. else {
  30870. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30871. }
  30872. if (this._soundGain) {
  30873. this._soundGain.disconnect();
  30874. this._soundGain = null;
  30875. }
  30876. if (this._soundPanner) {
  30877. this._soundPanner.disconnect();
  30878. this._soundPanner = null;
  30879. }
  30880. if (this._soundSource) {
  30881. this._soundSource.disconnect();
  30882. this._soundSource = null;
  30883. }
  30884. this._audioBuffer = null;
  30885. if (this._connectedMesh) {
  30886. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30887. this._connectedMesh = null;
  30888. }
  30889. }
  30890. };
  30891. Sound.prototype._soundLoaded = function (audioData) {
  30892. var _this = this;
  30893. this._isLoaded = true;
  30894. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30895. _this._audioBuffer = buffer;
  30896. _this._isReadyToPlay = true;
  30897. if (_this.autoplay) {
  30898. _this.play();
  30899. }
  30900. if (_this._readyToPlayCallback) {
  30901. _this._readyToPlayCallback();
  30902. }
  30903. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30904. };
  30905. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30906. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30907. this._audioBuffer = audioBuffer;
  30908. this._isReadyToPlay = true;
  30909. }
  30910. };
  30911. Sound.prototype.updateOptions = function (options) {
  30912. if (options) {
  30913. this.loop = options.loop || this.loop;
  30914. this.maxDistance = options.maxDistance || this.maxDistance;
  30915. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30916. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30917. this.refDistance = options.refDistance || this.refDistance;
  30918. this.distanceModel = options.distanceModel || this.distanceModel;
  30919. this._playbackRate = options.playbackRate || this._playbackRate;
  30920. this._updateSpatialParameters();
  30921. if (this.isPlaying) {
  30922. this._soundSource.playbackRate.value = this._playbackRate;
  30923. }
  30924. }
  30925. };
  30926. Sound.prototype._createSpatialParameters = function () {
  30927. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30928. if (this._scene.headphone) {
  30929. this._panningModel = "HRTF";
  30930. }
  30931. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30932. this._updateSpatialParameters();
  30933. this._soundPanner.connect(this._ouputAudioNode);
  30934. this._inputAudioNode = this._soundPanner;
  30935. }
  30936. };
  30937. Sound.prototype._updateSpatialParameters = function () {
  30938. if (this.spatialSound) {
  30939. if (this.useCustomAttenuation) {
  30940. // Tricks to disable in a way embedded Web Audio attenuation
  30941. this._soundPanner.distanceModel = "linear";
  30942. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30943. this._soundPanner.refDistance = 1;
  30944. this._soundPanner.rolloffFactor = 1;
  30945. this._soundPanner.panningModel = this._panningModel;
  30946. }
  30947. else {
  30948. this._soundPanner.distanceModel = this.distanceModel;
  30949. this._soundPanner.maxDistance = this.maxDistance;
  30950. this._soundPanner.refDistance = this.refDistance;
  30951. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30952. this._soundPanner.panningModel = this._panningModel;
  30953. }
  30954. }
  30955. };
  30956. Sound.prototype.switchPanningModelToHRTF = function () {
  30957. this._panningModel = "HRTF";
  30958. this._switchPanningModel();
  30959. };
  30960. Sound.prototype.switchPanningModelToEqualPower = function () {
  30961. this._panningModel = "equalpower";
  30962. this._switchPanningModel();
  30963. };
  30964. Sound.prototype._switchPanningModel = function () {
  30965. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30966. this._soundPanner.panningModel = this._panningModel;
  30967. }
  30968. };
  30969. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30970. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30971. if (this._isOutputConnected) {
  30972. this._ouputAudioNode.disconnect();
  30973. }
  30974. this._ouputAudioNode.connect(soundTrackAudioNode);
  30975. this._isOutputConnected = true;
  30976. }
  30977. };
  30978. /**
  30979. * Transform this sound into a directional source
  30980. * @param coneInnerAngle Size of the inner cone in degree
  30981. * @param coneOuterAngle Size of the outer cone in degree
  30982. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30983. */
  30984. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30985. if (coneOuterAngle < coneInnerAngle) {
  30986. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30987. return;
  30988. }
  30989. this._coneInnerAngle = coneInnerAngle;
  30990. this._coneOuterAngle = coneOuterAngle;
  30991. this._coneOuterGain = coneOuterGain;
  30992. this._isDirectional = true;
  30993. if (this.isPlaying && this.loop) {
  30994. this.stop();
  30995. this.play();
  30996. }
  30997. };
  30998. Sound.prototype.setPosition = function (newPosition) {
  30999. this._position = newPosition;
  31000. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  31001. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  31002. }
  31003. };
  31004. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  31005. this._localDirection = newLocalDirection;
  31006. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  31007. this._updateDirection();
  31008. }
  31009. };
  31010. Sound.prototype._updateDirection = function () {
  31011. var mat = this._connectedMesh.getWorldMatrix();
  31012. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  31013. direction.normalize();
  31014. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  31015. };
  31016. Sound.prototype.updateDistanceFromListener = function () {
  31017. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  31018. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  31019. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  31020. }
  31021. };
  31022. Sound.prototype.setAttenuationFunction = function (callback) {
  31023. this._customAttenuationFunction = callback;
  31024. };
  31025. /**
  31026. * Play the sound
  31027. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  31028. */
  31029. Sound.prototype.play = function (time) {
  31030. var _this = this;
  31031. if (this._isReadyToPlay && this._scene.audioEnabled) {
  31032. try {
  31033. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  31034. if (!this._soundSource) {
  31035. if (this.spatialSound) {
  31036. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  31037. if (this._isDirectional) {
  31038. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  31039. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  31040. this._soundPanner.coneOuterGain = this._coneOuterGain;
  31041. if (this._connectedMesh) {
  31042. this._updateDirection();
  31043. }
  31044. else {
  31045. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  31046. }
  31047. }
  31048. }
  31049. }
  31050. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  31051. this._soundSource.buffer = this._audioBuffer;
  31052. this._soundSource.connect(this._inputAudioNode);
  31053. this._soundSource.loop = this.loop;
  31054. this._soundSource.playbackRate.value = this._playbackRate;
  31055. this._startTime = startTime;
  31056. this._soundSource.onended = function () { _this._onended(); };
  31057. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  31058. this.isPlaying = true;
  31059. this.isPaused = false;
  31060. }
  31061. catch (ex) {
  31062. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  31063. }
  31064. }
  31065. };
  31066. Sound.prototype._onended = function () {
  31067. this.isPlaying = false;
  31068. if (this.onended) {
  31069. this.onended();
  31070. }
  31071. };
  31072. /**
  31073. * Stop the sound
  31074. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  31075. */
  31076. Sound.prototype.stop = function (time) {
  31077. if (this.isPlaying) {
  31078. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  31079. this._soundSource.stop(stopTime);
  31080. this.isPlaying = false;
  31081. }
  31082. };
  31083. Sound.prototype.pause = function () {
  31084. if (this.isPlaying) {
  31085. this.stop(0);
  31086. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  31087. this.isPaused = true;
  31088. }
  31089. };
  31090. Sound.prototype.setVolume = function (newVolume, time) {
  31091. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31092. if (time) {
  31093. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  31094. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  31095. }
  31096. else {
  31097. this._soundGain.gain.value = newVolume;
  31098. }
  31099. }
  31100. this._volume = newVolume;
  31101. };
  31102. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  31103. this._playbackRate = newPlaybackRate;
  31104. if (this.isPlaying) {
  31105. this._soundSource.playbackRate.value = this._playbackRate;
  31106. }
  31107. };
  31108. Sound.prototype.getVolume = function () {
  31109. return this._volume;
  31110. };
  31111. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  31112. var _this = this;
  31113. this._connectedMesh = meshToConnectTo;
  31114. if (!this.spatialSound) {
  31115. this.spatialSound = true;
  31116. this._createSpatialParameters();
  31117. if (this.isPlaying && this.loop) {
  31118. this.stop();
  31119. this.play();
  31120. }
  31121. }
  31122. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  31123. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  31124. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  31125. };
  31126. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  31127. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  31128. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  31129. this._updateDirection();
  31130. }
  31131. };
  31132. return Sound;
  31133. })();
  31134. BABYLON.Sound = Sound;
  31135. })(BABYLON || (BABYLON = {}));
  31136. var BABYLON;
  31137. (function (BABYLON) {
  31138. var SoundTrack = (function () {
  31139. function SoundTrack(scene, options) {
  31140. this.id = -1;
  31141. this._isMainTrack = false;
  31142. this._scene = scene;
  31143. this._audioEngine = BABYLON.Engine.audioEngine;
  31144. this.soundCollection = new Array();
  31145. if (this._audioEngine.canUseWebAudio) {
  31146. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  31147. this._outputAudioNode.connect(this._audioEngine.masterGain);
  31148. if (options) {
  31149. if (options.volume) {
  31150. this._outputAudioNode.gain.value = options.volume;
  31151. }
  31152. if (options.mainTrack) {
  31153. this._isMainTrack = options.mainTrack;
  31154. }
  31155. }
  31156. }
  31157. if (!this._isMainTrack) {
  31158. this._scene.soundTracks.push(this);
  31159. this.id = this._scene.soundTracks.length - 1;
  31160. }
  31161. }
  31162. SoundTrack.prototype.dispose = function () {
  31163. if (this._audioEngine.canUseWebAudio) {
  31164. if (this._connectedAnalyser) {
  31165. this._connectedAnalyser.stopDebugCanvas();
  31166. }
  31167. while (this.soundCollection.length) {
  31168. this.soundCollection[0].dispose();
  31169. }
  31170. if (this._outputAudioNode) {
  31171. this._outputAudioNode.disconnect();
  31172. }
  31173. this._outputAudioNode = null;
  31174. }
  31175. };
  31176. SoundTrack.prototype.AddSound = function (sound) {
  31177. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31178. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  31179. }
  31180. if (sound.soundTrackId) {
  31181. if (sound.soundTrackId === -1) {
  31182. this._scene.mainSoundTrack.RemoveSound(sound);
  31183. }
  31184. else {
  31185. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  31186. }
  31187. }
  31188. this.soundCollection.push(sound);
  31189. sound.soundTrackId = this.id;
  31190. };
  31191. SoundTrack.prototype.RemoveSound = function (sound) {
  31192. var index = this.soundCollection.indexOf(sound);
  31193. if (index !== -1) {
  31194. this.soundCollection.splice(index, 1);
  31195. }
  31196. };
  31197. SoundTrack.prototype.setVolume = function (newVolume) {
  31198. if (this._audioEngine.canUseWebAudio) {
  31199. this._outputAudioNode.gain.value = newVolume;
  31200. }
  31201. };
  31202. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  31203. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31204. for (var i = 0; i < this.soundCollection.length; i++) {
  31205. this.soundCollection[i].switchPanningModelToHRTF();
  31206. }
  31207. }
  31208. };
  31209. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  31210. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31211. for (var i = 0; i < this.soundCollection.length; i++) {
  31212. this.soundCollection[i].switchPanningModelToEqualPower();
  31213. }
  31214. }
  31215. };
  31216. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  31217. if (this._connectedAnalyser) {
  31218. this._connectedAnalyser.stopDebugCanvas();
  31219. }
  31220. this._connectedAnalyser = analyser;
  31221. if (this._audioEngine.canUseWebAudio) {
  31222. this._outputAudioNode.disconnect();
  31223. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  31224. }
  31225. };
  31226. return SoundTrack;
  31227. })();
  31228. BABYLON.SoundTrack = SoundTrack;
  31229. })(BABYLON || (BABYLON = {}));
  31230. var BABYLON;
  31231. (function (BABYLON) {
  31232. var DebugLayer = (function () {
  31233. function DebugLayer(scene) {
  31234. var _this = this;
  31235. this._transformationMatrix = BABYLON.Matrix.Identity();
  31236. this._enabled = false;
  31237. this._labelsEnabled = false;
  31238. this._displayStatistics = true;
  31239. this._displayTree = false;
  31240. this._displayLogs = false;
  31241. this._identityMatrix = BABYLON.Matrix.Identity();
  31242. this.axisRatio = 0.02;
  31243. this.accentColor = "orange";
  31244. this._scene = scene;
  31245. this._syncPositions = function () {
  31246. var engine = _this._scene.getEngine();
  31247. var canvasRect = engine.getRenderingCanvasClientRect();
  31248. if (_this._showUI) {
  31249. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  31250. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  31251. _this._statsDiv.style.width = "400px";
  31252. _this._statsDiv.style.height = "auto";
  31253. _this._statsSubsetDiv.style.maxHeight = "240px";
  31254. _this._optionsDiv.style.left = "0px";
  31255. _this._optionsDiv.style.top = "10px";
  31256. _this._optionsDiv.style.width = "200px";
  31257. _this._optionsDiv.style.height = "auto";
  31258. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  31259. _this._logDiv.style.left = "0px";
  31260. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  31261. _this._logDiv.style.width = "600px";
  31262. _this._logDiv.style.height = "160px";
  31263. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  31264. _this._treeDiv.style.top = "10px";
  31265. _this._treeDiv.style.width = "300px";
  31266. _this._treeDiv.style.height = "auto";
  31267. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  31268. }
  31269. _this._globalDiv.style.left = canvasRect.left + "px";
  31270. _this._globalDiv.style.top = canvasRect.top + "px";
  31271. _this._drawingCanvas.style.left = "0px";
  31272. _this._drawingCanvas.style.top = "0px";
  31273. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  31274. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  31275. var devicePixelRatio = window.devicePixelRatio || 1;
  31276. var context = _this._drawingContext;
  31277. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  31278. context.mozBackingStorePixelRatio ||
  31279. context.msBackingStorePixelRatio ||
  31280. context.oBackingStorePixelRatio ||
  31281. context.backingStorePixelRatio || 1;
  31282. _this._ratio = devicePixelRatio / backingStoreRatio;
  31283. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  31284. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  31285. };
  31286. this._onCanvasClick = function (evt) {
  31287. _this._clickPosition = {
  31288. x: evt.clientX * _this._ratio,
  31289. y: evt.clientY * _this._ratio
  31290. };
  31291. };
  31292. this._syncUI = function () {
  31293. if (_this._showUI) {
  31294. if (_this._displayStatistics) {
  31295. _this._displayStats();
  31296. _this._statsDiv.style.display = "";
  31297. }
  31298. else {
  31299. _this._statsDiv.style.display = "none";
  31300. }
  31301. if (_this._displayLogs) {
  31302. _this._logDiv.style.display = "";
  31303. }
  31304. else {
  31305. _this._logDiv.style.display = "none";
  31306. }
  31307. if (_this._displayTree) {
  31308. _this._treeDiv.style.display = "";
  31309. if (_this._needToRefreshMeshesTree) {
  31310. _this._needToRefreshMeshesTree = false;
  31311. _this._refreshMeshesTreeContent();
  31312. }
  31313. }
  31314. else {
  31315. _this._treeDiv.style.display = "none";
  31316. }
  31317. }
  31318. };
  31319. this._syncData = function () {
  31320. if (_this._labelsEnabled || !_this._showUI) {
  31321. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  31322. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  31323. var engine = _this._scene.getEngine();
  31324. var viewport = _this._camera.viewport;
  31325. var globalViewport = viewport.toGlobal(engine);
  31326. // Meshes
  31327. var meshes = _this._camera.getActiveMeshes();
  31328. for (var index = 0; index < meshes.length; index++) {
  31329. var mesh = meshes.data[index];
  31330. var position = mesh.getBoundingInfo().boundingSphere.center;
  31331. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  31332. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  31333. _this._renderAxis(projectedPosition, mesh, globalViewport);
  31334. }
  31335. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  31336. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  31337. }
  31338. }
  31339. // Cameras
  31340. var cameras = _this._scene.cameras;
  31341. for (index = 0; index < cameras.length; index++) {
  31342. var camera = cameras[index];
  31343. if (camera === _this._camera) {
  31344. continue;
  31345. }
  31346. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  31347. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  31348. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  31349. _this._camera.detachControl(engine.getRenderingCanvas());
  31350. _this._camera = camera;
  31351. _this._camera.attachControl(engine.getRenderingCanvas());
  31352. }, function () { return "purple"; });
  31353. }
  31354. }
  31355. // Lights
  31356. var lights = _this._scene.lights;
  31357. for (index = 0; index < lights.length; index++) {
  31358. var light = lights[index];
  31359. if (light.position) {
  31360. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  31361. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  31362. _this._renderLabel(light.name, projectedPosition, -20, function () {
  31363. light.setEnabled(!light.isEnabled());
  31364. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  31365. }
  31366. }
  31367. }
  31368. }
  31369. _this._clickPosition = undefined;
  31370. };
  31371. }
  31372. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  31373. while (this._treeSubsetDiv.hasChildNodes()) {
  31374. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  31375. }
  31376. // Add meshes
  31377. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  31378. sortedArray.sort(function (a, b) {
  31379. if (a.name === b.name) {
  31380. return 0;
  31381. }
  31382. return (a.name > b.name) ? 1 : -1;
  31383. });
  31384. for (var index = 0; index < sortedArray.length; index++) {
  31385. var mesh = sortedArray[index];
  31386. if (!mesh.isEnabled()) {
  31387. continue;
  31388. }
  31389. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  31390. m.isVisible = element.checked;
  31391. }, mesh);
  31392. }
  31393. };
  31394. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  31395. this._drawingContext.beginPath();
  31396. this._drawingContext.moveTo(zero.x, zero.y);
  31397. this._drawingContext.lineTo(unit.x, unit.y);
  31398. this._drawingContext.strokeStyle = color;
  31399. this._drawingContext.lineWidth = 4;
  31400. this._drawingContext.stroke();
  31401. this._drawingContext.font = "normal 14px Segoe UI";
  31402. this._drawingContext.fillStyle = color;
  31403. this._drawingContext.fillText(label, unitText.x, unitText.y);
  31404. };
  31405. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  31406. var position = mesh.getBoundingInfo().boundingSphere.center;
  31407. var worldMatrix = mesh.getWorldMatrix();
  31408. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  31409. var unit = (unprojectedVector.subtract(position)).length();
  31410. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31411. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31412. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  31413. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31414. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31415. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  31416. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  31417. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  31418. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  31419. };
  31420. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  31421. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  31422. this._drawingContext.font = "normal 12px Segoe UI";
  31423. var textMetrics = this._drawingContext.measureText(text);
  31424. var centerX = projectedPosition.x - textMetrics.width / 2;
  31425. var centerY = projectedPosition.y;
  31426. var clientRect = this._drawingCanvas.getBoundingClientRect();
  31427. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  31428. onClick();
  31429. }
  31430. this._drawingContext.beginPath();
  31431. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  31432. this._drawingContext.fillStyle = getFillStyle();
  31433. this._drawingContext.globalAlpha = 0.5;
  31434. this._drawingContext.fill();
  31435. this._drawingContext.globalAlpha = 1.0;
  31436. this._drawingContext.strokeStyle = '#FFFFFF';
  31437. this._drawingContext.lineWidth = 1;
  31438. this._drawingContext.stroke();
  31439. this._drawingContext.fillStyle = "#FFFFFF";
  31440. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  31441. this._drawingContext.beginPath();
  31442. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  31443. this._drawingContext.fill();
  31444. }
  31445. };
  31446. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  31447. if (!this._clickPosition) {
  31448. return false;
  31449. }
  31450. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  31451. return false;
  31452. }
  31453. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  31454. return false;
  31455. }
  31456. return true;
  31457. };
  31458. DebugLayer.prototype.isVisible = function () {
  31459. return this._enabled;
  31460. };
  31461. DebugLayer.prototype.hide = function () {
  31462. if (!this._enabled) {
  31463. return;
  31464. }
  31465. this._enabled = false;
  31466. var engine = this._scene.getEngine();
  31467. this._scene.unregisterBeforeRender(this._syncData);
  31468. this._scene.unregisterAfterRender(this._syncUI);
  31469. document.body.removeChild(this._globalDiv);
  31470. window.removeEventListener("resize", this._syncPositions);
  31471. this._scene.forceShowBoundingBoxes = false;
  31472. this._scene.forceWireframe = false;
  31473. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  31474. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  31475. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  31476. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  31477. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  31478. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  31479. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  31480. BABYLON.StandardMaterial.LightmapEnabled = true;
  31481. this._scene.shadowsEnabled = true;
  31482. this._scene.particlesEnabled = true;
  31483. this._scene.postProcessesEnabled = true;
  31484. this._scene.collisionsEnabled = true;
  31485. this._scene.lightsEnabled = true;
  31486. this._scene.texturesEnabled = true;
  31487. this._scene.lensFlaresEnabled = true;
  31488. this._scene.proceduralTexturesEnabled = true;
  31489. this._scene.renderTargetsEnabled = true;
  31490. this._scene.probesEnabled = true;
  31491. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  31492. };
  31493. DebugLayer.prototype.show = function (showUI, camera) {
  31494. if (showUI === void 0) { showUI = true; }
  31495. if (camera === void 0) { camera = null; }
  31496. if (this._enabled) {
  31497. return;
  31498. }
  31499. this._enabled = true;
  31500. if (camera) {
  31501. this._camera = camera;
  31502. }
  31503. else {
  31504. this._camera = this._scene.activeCamera;
  31505. }
  31506. this._showUI = showUI;
  31507. var engine = this._scene.getEngine();
  31508. this._globalDiv = document.createElement("div");
  31509. document.body.appendChild(this._globalDiv);
  31510. this._generateDOMelements();
  31511. window.addEventListener("resize", this._syncPositions);
  31512. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  31513. this._syncPositions();
  31514. this._scene.registerBeforeRender(this._syncData);
  31515. this._scene.registerAfterRender(this._syncUI);
  31516. };
  31517. DebugLayer.prototype._clearLabels = function () {
  31518. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  31519. for (var index = 0; index < this._scene.meshes.length; index++) {
  31520. var mesh = this._scene.meshes[index];
  31521. mesh.renderOverlay = false;
  31522. }
  31523. };
  31524. DebugLayer.prototype._generateheader = function (root, text) {
  31525. var header = document.createElement("div");
  31526. header.innerHTML = text + "&nbsp;";
  31527. header.style.textAlign = "right";
  31528. header.style.width = "100%";
  31529. header.style.color = "white";
  31530. header.style.backgroundColor = "Black";
  31531. header.style.padding = "5px 5px 4px 0px";
  31532. header.style.marginLeft = "-5px";
  31533. header.style.fontWeight = "bold";
  31534. root.appendChild(header);
  31535. };
  31536. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  31537. var label = document.createElement("label");
  31538. label.innerHTML = title;
  31539. label.style.color = color;
  31540. root.appendChild(label);
  31541. root.appendChild(document.createElement("br"));
  31542. };
  31543. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  31544. if (tag === void 0) { tag = null; }
  31545. var label = document.createElement("label");
  31546. var boundingBoxesCheckbox = document.createElement("input");
  31547. boundingBoxesCheckbox.type = "checkbox";
  31548. boundingBoxesCheckbox.checked = initialState;
  31549. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  31550. task(evt.target, tag);
  31551. });
  31552. label.appendChild(boundingBoxesCheckbox);
  31553. var container = document.createElement("span");
  31554. var leftPart = document.createElement("span");
  31555. var rightPart = document.createElement("span");
  31556. rightPart.style.cssFloat = "right";
  31557. leftPart.innerHTML = leftTitle;
  31558. rightPart.innerHTML = rightTitle;
  31559. rightPart.style.fontSize = "12px";
  31560. rightPart.style.maxWidth = "200px";
  31561. container.appendChild(leftPart);
  31562. container.appendChild(rightPart);
  31563. label.appendChild(container);
  31564. root.appendChild(label);
  31565. root.appendChild(document.createElement("br"));
  31566. };
  31567. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  31568. if (tag === void 0) { tag = null; }
  31569. var label = document.createElement("label");
  31570. var checkBox = document.createElement("input");
  31571. checkBox.type = "checkbox";
  31572. checkBox.checked = initialState;
  31573. checkBox.addEventListener("change", function (evt) {
  31574. task(evt.target, tag);
  31575. });
  31576. label.appendChild(checkBox);
  31577. label.appendChild(document.createTextNode(title));
  31578. root.appendChild(label);
  31579. root.appendChild(document.createElement("br"));
  31580. };
  31581. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  31582. if (tag === void 0) { tag = null; }
  31583. var button = document.createElement("button");
  31584. button.innerHTML = title;
  31585. button.style.height = "24px";
  31586. button.style.color = "#444444";
  31587. button.style.border = "1px solid white";
  31588. button.className = "debugLayerButton";
  31589. button.addEventListener("click", function (evt) {
  31590. task(evt.target, tag);
  31591. });
  31592. root.appendChild(button);
  31593. root.appendChild(document.createElement("br"));
  31594. };
  31595. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  31596. if (tag === void 0) { tag = null; }
  31597. var label = document.createElement("label");
  31598. var boundingBoxesRadio = document.createElement("input");
  31599. boundingBoxesRadio.type = "radio";
  31600. boundingBoxesRadio.name = name;
  31601. boundingBoxesRadio.checked = initialState;
  31602. boundingBoxesRadio.addEventListener("change", function (evt) {
  31603. task(evt.target, tag);
  31604. });
  31605. label.appendChild(boundingBoxesRadio);
  31606. label.appendChild(document.createTextNode(title));
  31607. root.appendChild(label);
  31608. root.appendChild(document.createElement("br"));
  31609. };
  31610. DebugLayer.prototype._generateDOMelements = function () {
  31611. var _this = this;
  31612. this._globalDiv.id = "DebugLayer";
  31613. this._globalDiv.style.position = "absolute";
  31614. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  31615. this._globalDiv.style.fontSize = "14px";
  31616. this._globalDiv.style.color = "white";
  31617. // Drawing canvas
  31618. this._drawingCanvas = document.createElement("canvas");
  31619. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  31620. this._drawingCanvas.style.position = "absolute";
  31621. this._drawingCanvas.style.pointerEvents = "none";
  31622. this._drawingContext = this._drawingCanvas.getContext("2d");
  31623. this._globalDiv.appendChild(this._drawingCanvas);
  31624. if (this._showUI) {
  31625. var background = "rgba(128, 128, 128, 0.4)";
  31626. var border = "rgb(180, 180, 180) solid 1px";
  31627. // Stats
  31628. this._statsDiv = document.createElement("div");
  31629. this._statsDiv.id = "DebugLayerStats";
  31630. this._statsDiv.style.border = border;
  31631. this._statsDiv.style.position = "absolute";
  31632. this._statsDiv.style.background = background;
  31633. this._statsDiv.style.padding = "0px 0px 0px 5px";
  31634. this._generateheader(this._statsDiv, "STATISTICS");
  31635. this._statsSubsetDiv = document.createElement("div");
  31636. this._statsSubsetDiv.style.paddingTop = "5px";
  31637. this._statsSubsetDiv.style.paddingBottom = "5px";
  31638. this._statsSubsetDiv.style.overflowY = "auto";
  31639. this._statsDiv.appendChild(this._statsSubsetDiv);
  31640. // Tree
  31641. this._treeDiv = document.createElement("div");
  31642. this._treeDiv.id = "DebugLayerTree";
  31643. this._treeDiv.style.border = border;
  31644. this._treeDiv.style.position = "absolute";
  31645. this._treeDiv.style.background = background;
  31646. this._treeDiv.style.padding = "0px 0px 0px 5px";
  31647. this._treeDiv.style.display = "none";
  31648. this._generateheader(this._treeDiv, "MESHES TREE");
  31649. this._treeSubsetDiv = document.createElement("div");
  31650. this._treeSubsetDiv.style.paddingTop = "5px";
  31651. this._treeSubsetDiv.style.paddingRight = "5px";
  31652. this._treeSubsetDiv.style.overflowY = "auto";
  31653. this._treeSubsetDiv.style.maxHeight = "300px";
  31654. this._treeDiv.appendChild(this._treeSubsetDiv);
  31655. this._needToRefreshMeshesTree = true;
  31656. // Logs
  31657. this._logDiv = document.createElement("div");
  31658. this._logDiv.style.border = border;
  31659. this._logDiv.id = "DebugLayerLogs";
  31660. this._logDiv.style.position = "absolute";
  31661. this._logDiv.style.background = background;
  31662. this._logDiv.style.padding = "0px 0px 0px 5px";
  31663. this._logDiv.style.display = "none";
  31664. this._generateheader(this._logDiv, "LOGS");
  31665. this._logSubsetDiv = document.createElement("div");
  31666. this._logSubsetDiv.style.height = "127px";
  31667. this._logSubsetDiv.style.paddingTop = "5px";
  31668. this._logSubsetDiv.style.overflowY = "auto";
  31669. this._logSubsetDiv.style.fontSize = "12px";
  31670. this._logSubsetDiv.style.fontFamily = "consolas";
  31671. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  31672. this._logDiv.appendChild(this._logSubsetDiv);
  31673. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  31674. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  31675. };
  31676. // Options
  31677. this._optionsDiv = document.createElement("div");
  31678. this._optionsDiv.id = "DebugLayerOptions";
  31679. this._optionsDiv.style.border = border;
  31680. this._optionsDiv.style.position = "absolute";
  31681. this._optionsDiv.style.background = background;
  31682. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  31683. this._optionsDiv.style.overflowY = "auto";
  31684. this._generateheader(this._optionsDiv, "OPTIONS");
  31685. this._optionsSubsetDiv = document.createElement("div");
  31686. this._optionsSubsetDiv.style.paddingTop = "5px";
  31687. this._optionsSubsetDiv.style.paddingBottom = "5px";
  31688. this._optionsSubsetDiv.style.overflowY = "auto";
  31689. this._optionsSubsetDiv.style.maxHeight = "200px";
  31690. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  31691. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  31692. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  31693. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  31694. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  31695. _this._displayTree = element.checked;
  31696. _this._needToRefreshMeshesTree = true;
  31697. });
  31698. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31699. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  31700. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  31701. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  31702. _this._labelsEnabled = element.checked;
  31703. if (!_this._labelsEnabled) {
  31704. _this._clearLabels();
  31705. }
  31706. });
  31707. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31708. if (element.checked) {
  31709. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31710. }
  31711. else {
  31712. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31713. }
  31714. });
  31715. ;
  31716. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31717. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31718. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31719. if (element.checked) {
  31720. _this._scene.forceWireframe = false;
  31721. _this._scene.forcePointsCloud = false;
  31722. }
  31723. });
  31724. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31725. if (element.checked) {
  31726. _this._scene.forceWireframe = true;
  31727. _this._scene.forcePointsCloud = false;
  31728. }
  31729. });
  31730. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31731. if (element.checked) {
  31732. _this._scene.forceWireframe = false;
  31733. _this._scene.forcePointsCloud = true;
  31734. }
  31735. });
  31736. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31737. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31738. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31739. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31740. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31741. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31742. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31743. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31744. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31745. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31746. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  31747. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31748. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31749. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31750. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31751. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31752. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31753. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31754. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31755. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31756. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  31757. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31758. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31759. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31760. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31761. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31762. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31763. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31764. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31765. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31766. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31767. if (element.checked) {
  31768. _this._scene.headphone = true;
  31769. }
  31770. });
  31771. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31772. if (element.checked) {
  31773. _this._scene.headphone = false;
  31774. }
  31775. });
  31776. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31777. _this._scene.audioEnabled = !element.checked;
  31778. });
  31779. }
  31780. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31781. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31782. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31783. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31784. this._globalDiv.appendChild(this._statsDiv);
  31785. this._globalDiv.appendChild(this._logDiv);
  31786. this._globalDiv.appendChild(this._optionsDiv);
  31787. this._globalDiv.appendChild(this._treeDiv);
  31788. }
  31789. };
  31790. DebugLayer.prototype._displayStats = function () {
  31791. var scene = this._scene;
  31792. var engine = scene.getEngine();
  31793. var glInfo = engine.getGlInfo();
  31794. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31795. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31796. + "<b>Count</b><br>"
  31797. + "Total meshes: " + scene.meshes.length + "<br>"
  31798. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31799. + "Total materials: " + scene.materials.length + "<br>"
  31800. + "Total textures: " + scene.textures.length + "<br>"
  31801. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31802. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31803. + "Active bones: " + scene.getActiveBones() + "<br>"
  31804. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31805. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  31806. + "<b>Duration</b><br>"
  31807. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31808. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31809. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31810. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31811. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31812. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31813. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  31814. + "</div>"
  31815. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31816. + "<b>Extensions</b><br>"
  31817. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31818. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31819. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31820. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  31821. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31822. + "<b>Caps.</b><br>"
  31823. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31824. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31825. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  31826. + "</div><br>"
  31827. + "<b>Info</b><br>"
  31828. + glInfo.version + "<br>"
  31829. + glInfo.renderer + "<br>";
  31830. if (this.customStatsFunction) {
  31831. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31832. }
  31833. };
  31834. return DebugLayer;
  31835. })();
  31836. BABYLON.DebugLayer = DebugLayer;
  31837. })(BABYLON || (BABYLON = {}));
  31838. var BABYLON;
  31839. (function (BABYLON) {
  31840. var RawTexture = (function (_super) {
  31841. __extends(RawTexture, _super);
  31842. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31843. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31844. if (invertY === void 0) { invertY = false; }
  31845. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31846. _super.call(this, null, scene, !generateMipMaps, invertY);
  31847. this.format = format;
  31848. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31849. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31850. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31851. }
  31852. RawTexture.prototype.update = function (data) {
  31853. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31854. };
  31855. // Statics
  31856. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31857. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31858. if (invertY === void 0) { invertY = false; }
  31859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31860. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31861. };
  31862. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31863. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31864. if (invertY === void 0) { invertY = false; }
  31865. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31866. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31867. };
  31868. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31869. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31870. if (invertY === void 0) { invertY = false; }
  31871. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31872. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31873. };
  31874. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31875. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31876. if (invertY === void 0) { invertY = false; }
  31877. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31878. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31879. };
  31880. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31881. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31882. if (invertY === void 0) { invertY = false; }
  31883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31884. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31885. };
  31886. return RawTexture;
  31887. })(BABYLON.Texture);
  31888. BABYLON.RawTexture = RawTexture;
  31889. })(BABYLON || (BABYLON = {}));
  31890. var BABYLON;
  31891. (function (BABYLON) {
  31892. var IndexedVector2 = (function (_super) {
  31893. __extends(IndexedVector2, _super);
  31894. function IndexedVector2(original, index) {
  31895. _super.call(this, original.x, original.y);
  31896. this.index = index;
  31897. }
  31898. return IndexedVector2;
  31899. })(BABYLON.Vector2);
  31900. var PolygonPoints = (function () {
  31901. function PolygonPoints() {
  31902. this.elements = new Array();
  31903. }
  31904. PolygonPoints.prototype.add = function (originalPoints) {
  31905. var _this = this;
  31906. var result = new Array();
  31907. originalPoints.forEach(function (point) {
  31908. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31909. var newPoint = new IndexedVector2(point, _this.elements.length);
  31910. result.push(newPoint);
  31911. _this.elements.push(newPoint);
  31912. }
  31913. });
  31914. return result;
  31915. };
  31916. PolygonPoints.prototype.computeBounds = function () {
  31917. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31918. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31919. this.elements.forEach(function (point) {
  31920. // x
  31921. if (point.x < lmin.x) {
  31922. lmin.x = point.x;
  31923. }
  31924. else if (point.x > lmax.x) {
  31925. lmax.x = point.x;
  31926. }
  31927. // y
  31928. if (point.y < lmin.y) {
  31929. lmin.y = point.y;
  31930. }
  31931. else if (point.y > lmax.y) {
  31932. lmax.y = point.y;
  31933. }
  31934. });
  31935. return {
  31936. min: lmin,
  31937. max: lmax,
  31938. width: lmax.x - lmin.x,
  31939. height: lmax.y - lmin.y
  31940. };
  31941. };
  31942. return PolygonPoints;
  31943. })();
  31944. var Polygon = (function () {
  31945. function Polygon() {
  31946. }
  31947. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31948. return [
  31949. new BABYLON.Vector2(xmin, ymin),
  31950. new BABYLON.Vector2(xmax, ymin),
  31951. new BABYLON.Vector2(xmax, ymax),
  31952. new BABYLON.Vector2(xmin, ymax)
  31953. ];
  31954. };
  31955. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31956. if (cx === void 0) { cx = 0; }
  31957. if (cy === void 0) { cy = 0; }
  31958. if (numberOfSides === void 0) { numberOfSides = 32; }
  31959. var result = new Array();
  31960. var angle = 0;
  31961. var increment = (Math.PI * 2) / numberOfSides;
  31962. for (var i = 0; i < numberOfSides; i++) {
  31963. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31964. angle -= increment;
  31965. }
  31966. return result;
  31967. };
  31968. Polygon.Parse = function (input) {
  31969. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31970. var i, result = [];
  31971. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31972. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31973. }
  31974. return result;
  31975. };
  31976. Polygon.StartingAt = function (x, y) {
  31977. return BABYLON.Path2.StartingAt(x, y);
  31978. };
  31979. return Polygon;
  31980. })();
  31981. BABYLON.Polygon = Polygon;
  31982. var PolygonMeshBuilder = (function () {
  31983. function PolygonMeshBuilder(name, contours, scene) {
  31984. this._points = new PolygonPoints();
  31985. this._outlinepoints = new PolygonPoints();
  31986. this._holes = [];
  31987. if (!("poly2tri" in window)) {
  31988. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31989. }
  31990. this._name = name;
  31991. this._scene = scene;
  31992. var points;
  31993. if (contours instanceof BABYLON.Path2) {
  31994. points = contours.getPoints();
  31995. }
  31996. else {
  31997. points = contours;
  31998. }
  31999. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32000. this._outlinepoints.add(points);
  32001. }
  32002. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32003. this._swctx.addHole(this._points.add(hole));
  32004. var holepoints = new PolygonPoints();
  32005. holepoints.add(hole);
  32006. this._holes.push(holepoints);
  32007. return this;
  32008. };
  32009. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32010. var _this = this;
  32011. if (updatable === void 0) { updatable = false; }
  32012. var result = new BABYLON.Mesh(this._name, this._scene);
  32013. var normals = [];
  32014. var positions = [];
  32015. var uvs = [];
  32016. var bounds = this._points.computeBounds();
  32017. this._points.elements.forEach(function (p) {
  32018. normals.push(0, 1.0, 0);
  32019. positions.push(p.x, 0, p.y);
  32020. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32021. });
  32022. var indices = [];
  32023. this._swctx.triangulate();
  32024. this._swctx.getTriangles().forEach(function (triangle) {
  32025. triangle.getPoints().forEach(function (point) {
  32026. indices.push(point.index);
  32027. });
  32028. });
  32029. if (depth > 0) {
  32030. var positionscount = (positions.length / 3); //get the current pointcount
  32031. this._points.elements.forEach(function (p) {
  32032. normals.push(0, -1.0, 0);
  32033. positions.push(p.x, -depth, p.y);
  32034. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32035. });
  32036. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32037. var p2;
  32038. var poscounter = 0;
  32039. this._swctx.getTriangles().forEach(function (triangle) {
  32040. triangle.getPoints().forEach(function (point) {
  32041. switch (poscounter) {
  32042. case 0:
  32043. p1 = point;
  32044. break;
  32045. case 1:
  32046. p2 = point;
  32047. break;
  32048. case 2:
  32049. indices.push(point.index + positionscount);
  32050. indices.push(p2.index + positionscount);
  32051. indices.push(p1.index + positionscount);
  32052. poscounter = -1;
  32053. break;
  32054. }
  32055. poscounter++;
  32056. //indices.push((<IndexedVector2>point).index + positionscount);
  32057. });
  32058. });
  32059. //Add the sides
  32060. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32061. this._holes.forEach(function (hole) {
  32062. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32063. });
  32064. }
  32065. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32066. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32067. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32068. result.setIndices(indices);
  32069. return result;
  32070. };
  32071. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32072. var StartIndex = positions.length / 3;
  32073. var ulength = 0;
  32074. for (var i = 0; i < points.elements.length; i++) {
  32075. var p = points.elements[i];
  32076. var p1;
  32077. if ((i + 1) > points.elements.length - 1) {
  32078. p1 = points.elements[0];
  32079. }
  32080. else {
  32081. p1 = points.elements[i + 1];
  32082. }
  32083. positions.push(p.x, 0, p.y);
  32084. positions.push(p.x, -depth, p.y);
  32085. positions.push(p1.x, 0, p1.y);
  32086. positions.push(p1.x, -depth, p1.y);
  32087. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32088. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32089. var v3 = v2.subtract(v1);
  32090. var v4 = new BABYLON.Vector3(0, 1, 0);
  32091. var vn = BABYLON.Vector3.Cross(v3, v4);
  32092. vn = vn.normalize();
  32093. uvs.push(ulength / bounds.width, 0);
  32094. uvs.push(ulength / bounds.width, 1);
  32095. ulength += v3.length();
  32096. uvs.push((ulength / bounds.width), 0);
  32097. uvs.push((ulength / bounds.width), 1);
  32098. if (!flip) {
  32099. normals.push(-vn.x, -vn.y, -vn.z);
  32100. normals.push(-vn.x, -vn.y, -vn.z);
  32101. normals.push(-vn.x, -vn.y, -vn.z);
  32102. normals.push(-vn.x, -vn.y, -vn.z);
  32103. indices.push(StartIndex);
  32104. indices.push(StartIndex + 1);
  32105. indices.push(StartIndex + 2);
  32106. indices.push(StartIndex + 1);
  32107. indices.push(StartIndex + 3);
  32108. indices.push(StartIndex + 2);
  32109. }
  32110. else {
  32111. normals.push(vn.x, vn.y, vn.z);
  32112. normals.push(vn.x, vn.y, vn.z);
  32113. normals.push(vn.x, vn.y, vn.z);
  32114. normals.push(vn.x, vn.y, vn.z);
  32115. indices.push(StartIndex);
  32116. indices.push(StartIndex + 2);
  32117. indices.push(StartIndex + 1);
  32118. indices.push(StartIndex + 1);
  32119. indices.push(StartIndex + 2);
  32120. indices.push(StartIndex + 3);
  32121. }
  32122. StartIndex += 4;
  32123. }
  32124. ;
  32125. };
  32126. return PolygonMeshBuilder;
  32127. })();
  32128. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32129. })(BABYLON || (BABYLON = {}));
  32130. var BABYLON;
  32131. (function (BABYLON) {
  32132. var SimplificationSettings = (function () {
  32133. function SimplificationSettings(quality, distance, optimizeMesh) {
  32134. this.quality = quality;
  32135. this.distance = distance;
  32136. this.optimizeMesh = optimizeMesh;
  32137. }
  32138. return SimplificationSettings;
  32139. })();
  32140. BABYLON.SimplificationSettings = SimplificationSettings;
  32141. var SimplificationQueue = (function () {
  32142. function SimplificationQueue() {
  32143. this.running = false;
  32144. this._simplificationArray = [];
  32145. }
  32146. SimplificationQueue.prototype.addTask = function (task) {
  32147. this._simplificationArray.push(task);
  32148. };
  32149. SimplificationQueue.prototype.executeNext = function () {
  32150. var task = this._simplificationArray.pop();
  32151. if (task) {
  32152. this.running = true;
  32153. this.runSimplification(task);
  32154. }
  32155. else {
  32156. this.running = false;
  32157. }
  32158. };
  32159. SimplificationQueue.prototype.runSimplification = function (task) {
  32160. var _this = this;
  32161. if (task.parallelProcessing) {
  32162. //parallel simplifier
  32163. task.settings.forEach(function (setting) {
  32164. var simplifier = _this.getSimplifier(task);
  32165. simplifier.simplify(setting, function (newMesh) {
  32166. task.mesh.addLODLevel(setting.distance, newMesh);
  32167. newMesh.isVisible = true;
  32168. //check if it is the last
  32169. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  32170. //all done, run the success callback.
  32171. task.successCallback();
  32172. }
  32173. _this.executeNext();
  32174. });
  32175. });
  32176. }
  32177. else {
  32178. //single simplifier.
  32179. var simplifier = this.getSimplifier(task);
  32180. var runDecimation = function (setting, callback) {
  32181. simplifier.simplify(setting, function (newMesh) {
  32182. task.mesh.addLODLevel(setting.distance, newMesh);
  32183. newMesh.isVisible = true;
  32184. //run the next quality level
  32185. callback();
  32186. });
  32187. };
  32188. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  32189. runDecimation(task.settings[loop.index], function () {
  32190. loop.executeNext();
  32191. });
  32192. }, function () {
  32193. //execution ended, run the success callback.
  32194. if (task.successCallback) {
  32195. task.successCallback();
  32196. }
  32197. _this.executeNext();
  32198. });
  32199. }
  32200. };
  32201. SimplificationQueue.prototype.getSimplifier = function (task) {
  32202. switch (task.simplificationType) {
  32203. case SimplificationType.QUADRATIC:
  32204. default:
  32205. return new QuadraticErrorSimplification(task.mesh);
  32206. }
  32207. };
  32208. return SimplificationQueue;
  32209. })();
  32210. BABYLON.SimplificationQueue = SimplificationQueue;
  32211. /**
  32212. * The implemented types of simplification.
  32213. * At the moment only Quadratic Error Decimation is implemented.
  32214. */
  32215. (function (SimplificationType) {
  32216. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  32217. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  32218. var SimplificationType = BABYLON.SimplificationType;
  32219. var DecimationTriangle = (function () {
  32220. function DecimationTriangle(vertices) {
  32221. this.vertices = vertices;
  32222. this.error = new Array(4);
  32223. this.deleted = false;
  32224. this.isDirty = false;
  32225. this.deletePending = false;
  32226. this.borderFactor = 0;
  32227. }
  32228. return DecimationTriangle;
  32229. })();
  32230. BABYLON.DecimationTriangle = DecimationTriangle;
  32231. var DecimationVertex = (function () {
  32232. function DecimationVertex(position, id) {
  32233. this.position = position;
  32234. this.id = id;
  32235. this.isBorder = true;
  32236. this.q = new QuadraticMatrix();
  32237. this.triangleCount = 0;
  32238. this.triangleStart = 0;
  32239. this.originalOffsets = [];
  32240. }
  32241. DecimationVertex.prototype.updatePosition = function (newPosition) {
  32242. this.position.copyFrom(newPosition);
  32243. };
  32244. return DecimationVertex;
  32245. })();
  32246. BABYLON.DecimationVertex = DecimationVertex;
  32247. var QuadraticMatrix = (function () {
  32248. function QuadraticMatrix(data) {
  32249. this.data = new Array(10);
  32250. for (var i = 0; i < 10; ++i) {
  32251. if (data && data[i]) {
  32252. this.data[i] = data[i];
  32253. }
  32254. else {
  32255. this.data[i] = 0;
  32256. }
  32257. }
  32258. }
  32259. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  32260. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  32261. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  32262. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  32263. return det;
  32264. };
  32265. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  32266. for (var i = 0; i < 10; ++i) {
  32267. this.data[i] += matrix.data[i];
  32268. }
  32269. };
  32270. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  32271. for (var i = 0; i < 10; ++i) {
  32272. this.data[i] += data[i];
  32273. }
  32274. };
  32275. QuadraticMatrix.prototype.add = function (matrix) {
  32276. var m = new QuadraticMatrix();
  32277. for (var i = 0; i < 10; ++i) {
  32278. m.data[i] = this.data[i] + matrix.data[i];
  32279. }
  32280. return m;
  32281. };
  32282. QuadraticMatrix.FromData = function (a, b, c, d) {
  32283. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  32284. };
  32285. //returning an array to avoid garbage collection
  32286. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  32287. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  32288. };
  32289. return QuadraticMatrix;
  32290. })();
  32291. BABYLON.QuadraticMatrix = QuadraticMatrix;
  32292. var Reference = (function () {
  32293. function Reference(vertexId, triangleId) {
  32294. this.vertexId = vertexId;
  32295. this.triangleId = triangleId;
  32296. }
  32297. return Reference;
  32298. })();
  32299. BABYLON.Reference = Reference;
  32300. /**
  32301. * An implementation of the Quadratic Error simplification algorithm.
  32302. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  32303. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  32304. * @author RaananW
  32305. */
  32306. var QuadraticErrorSimplification = (function () {
  32307. function QuadraticErrorSimplification(_mesh) {
  32308. this._mesh = _mesh;
  32309. this.initialized = false;
  32310. this.syncIterations = 5000;
  32311. this.aggressiveness = 7;
  32312. this.decimationIterations = 100;
  32313. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  32314. }
  32315. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  32316. var _this = this;
  32317. this.initDecimatedMesh();
  32318. //iterating through the submeshes array, one after the other.
  32319. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  32320. _this.initWithMesh(loop.index, function () {
  32321. _this.runDecimation(settings, loop.index, function () {
  32322. loop.executeNext();
  32323. });
  32324. }, settings.optimizeMesh);
  32325. }, function () {
  32326. setTimeout(function () {
  32327. successCallback(_this._reconstructedMesh);
  32328. }, 0);
  32329. });
  32330. };
  32331. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  32332. var _this = this;
  32333. var gCount = 0;
  32334. triangle.vertices.forEach(function (vertex) {
  32335. var count = 0;
  32336. var vPos = vertex.position;
  32337. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  32338. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  32339. ++count;
  32340. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  32341. ++count;
  32342. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  32343. ++count;
  32344. if (count > 1) {
  32345. ++gCount;
  32346. }
  32347. ;
  32348. });
  32349. if (gCount > 1) {
  32350. console.log(triangle, gCount);
  32351. }
  32352. return gCount > 1;
  32353. };
  32354. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  32355. var _this = this;
  32356. var targetCount = ~~(this.triangles.length * settings.quality);
  32357. var deletedTriangles = 0;
  32358. var triangleCount = this.triangles.length;
  32359. var iterationFunction = function (iteration, callback) {
  32360. setTimeout(function () {
  32361. if (iteration % 5 === 0) {
  32362. _this.updateMesh(iteration === 0);
  32363. }
  32364. for (var i = 0; i < _this.triangles.length; ++i) {
  32365. _this.triangles[i].isDirty = false;
  32366. }
  32367. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  32368. var trianglesIterator = function (i) {
  32369. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  32370. var t = _this.triangles[tIdx];
  32371. if (!t)
  32372. return;
  32373. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  32374. return;
  32375. }
  32376. for (var j = 0; j < 3; ++j) {
  32377. if (t.error[j] < threshold) {
  32378. var deleted0 = [];
  32379. var deleted1 = [];
  32380. var v0 = t.vertices[j];
  32381. var v1 = t.vertices[(j + 1) % 3];
  32382. if (v0.isBorder !== v1.isBorder)
  32383. continue;
  32384. var p = BABYLON.Vector3.Zero();
  32385. var n = BABYLON.Vector3.Zero();
  32386. var uv = BABYLON.Vector2.Zero();
  32387. var color = new BABYLON.Color4(0, 0, 0, 1);
  32388. _this.calculateError(v0, v1, p, n, uv, color);
  32389. var delTr = [];
  32390. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  32391. continue;
  32392. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  32393. continue;
  32394. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  32395. continue;
  32396. var uniqueArray = [];
  32397. delTr.forEach(function (deletedT) {
  32398. if (uniqueArray.indexOf(deletedT) === -1) {
  32399. deletedT.deletePending = true;
  32400. uniqueArray.push(deletedT);
  32401. }
  32402. });
  32403. if (uniqueArray.length % 2 != 0) {
  32404. continue;
  32405. }
  32406. v0.q = v1.q.add(v0.q);
  32407. v0.updatePosition(p);
  32408. var tStart = _this.references.length;
  32409. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  32410. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  32411. var tCount = _this.references.length - tStart;
  32412. if (tCount <= v0.triangleCount) {
  32413. if (tCount) {
  32414. for (var c = 0; c < tCount; c++) {
  32415. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  32416. }
  32417. }
  32418. }
  32419. else {
  32420. v0.triangleStart = tStart;
  32421. }
  32422. v0.triangleCount = tCount;
  32423. break;
  32424. }
  32425. }
  32426. };
  32427. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  32428. }, 0);
  32429. };
  32430. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  32431. if (triangleCount - deletedTriangles <= targetCount)
  32432. loop.breakLoop();
  32433. else {
  32434. iterationFunction(loop.index, function () {
  32435. loop.executeNext();
  32436. });
  32437. }
  32438. }, function () {
  32439. setTimeout(function () {
  32440. //reconstruct this part of the mesh
  32441. _this.reconstructMesh(submeshIndex);
  32442. successCallback();
  32443. }, 0);
  32444. });
  32445. };
  32446. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  32447. var _this = this;
  32448. this.vertices = [];
  32449. this.triangles = [];
  32450. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32451. var indices = this._mesh.getIndices();
  32452. var submesh = this._mesh.subMeshes[submeshIndex];
  32453. var findInVertices = function (positionToSearch) {
  32454. if (optimizeMesh) {
  32455. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  32456. if (_this.vertices[ii].position.equals(positionToSearch)) {
  32457. return _this.vertices[ii];
  32458. }
  32459. }
  32460. }
  32461. return null;
  32462. };
  32463. var vertexReferences = [];
  32464. var vertexInit = function (i) {
  32465. var offset = i + submesh.verticesStart;
  32466. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  32467. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  32468. vertex.originalOffsets.push(offset);
  32469. if (vertex.id == _this.vertices.length) {
  32470. _this.vertices.push(vertex);
  32471. }
  32472. vertexReferences.push(vertex.id);
  32473. };
  32474. //var totalVertices = mesh.getTotalVertices();
  32475. var totalVertices = submesh.verticesCount;
  32476. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  32477. var indicesInit = function (i) {
  32478. var offset = (submesh.indexStart / 3) + i;
  32479. var pos = (offset * 3);
  32480. var i0 = indices[pos + 0];
  32481. var i1 = indices[pos + 1];
  32482. var i2 = indices[pos + 2];
  32483. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  32484. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  32485. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  32486. var triangle = new DecimationTriangle([v0, v1, v2]);
  32487. triangle.originalOffset = pos;
  32488. _this.triangles.push(triangle);
  32489. };
  32490. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  32491. _this.init(callback);
  32492. });
  32493. });
  32494. };
  32495. QuadraticErrorSimplification.prototype.init = function (callback) {
  32496. var _this = this;
  32497. var triangleInit1 = function (i) {
  32498. var t = _this.triangles[i];
  32499. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  32500. for (var j = 0; j < 3; j++) {
  32501. 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))));
  32502. }
  32503. };
  32504. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  32505. var triangleInit2 = function (i) {
  32506. var t = _this.triangles[i];
  32507. for (var j = 0; j < 3; ++j) {
  32508. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  32509. }
  32510. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32511. };
  32512. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  32513. _this.initialized = true;
  32514. callback();
  32515. });
  32516. });
  32517. };
  32518. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  32519. var newTriangles = [];
  32520. var i;
  32521. for (i = 0; i < this.vertices.length; ++i) {
  32522. this.vertices[i].triangleCount = 0;
  32523. }
  32524. var t;
  32525. var j;
  32526. for (i = 0; i < this.triangles.length; ++i) {
  32527. if (!this.triangles[i].deleted) {
  32528. t = this.triangles[i];
  32529. for (j = 0; j < 3; ++j) {
  32530. t.vertices[j].triangleCount = 1;
  32531. }
  32532. newTriangles.push(t);
  32533. }
  32534. }
  32535. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  32536. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  32537. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  32538. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  32539. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32540. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32541. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  32542. var vertexCount = 0;
  32543. for (i = 0; i < this.vertices.length; ++i) {
  32544. var vertex = this.vertices[i];
  32545. vertex.id = vertexCount;
  32546. if (vertex.triangleCount) {
  32547. vertex.originalOffsets.forEach(function (originalOffset) {
  32548. newPositionData.push(vertex.position.x);
  32549. newPositionData.push(vertex.position.y);
  32550. newPositionData.push(vertex.position.z);
  32551. newNormalData.push(normalData[originalOffset * 3]);
  32552. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  32553. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  32554. if (uvs && uvs.length) {
  32555. newUVsData.push(uvs[(originalOffset * 2)]);
  32556. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  32557. }
  32558. else if (colorsData && colorsData.length) {
  32559. newColorsData.push(colorsData[(originalOffset * 4)]);
  32560. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  32561. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  32562. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  32563. }
  32564. ++vertexCount;
  32565. });
  32566. }
  32567. }
  32568. var startingIndex = this._reconstructedMesh.getTotalIndices();
  32569. var startingVertex = this._reconstructedMesh.getTotalVertices();
  32570. var submeshesArray = this._reconstructedMesh.subMeshes;
  32571. this._reconstructedMesh.subMeshes = [];
  32572. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  32573. var originalIndices = this._mesh.getIndices();
  32574. for (i = 0; i < newTriangles.length; ++i) {
  32575. var t = newTriangles[i];
  32576. //now get the new referencing point for each vertex
  32577. [0, 1, 2].forEach(function (idx) {
  32578. var id = originalIndices[t.originalOffset + idx];
  32579. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  32580. if (offset < 0)
  32581. offset = 0;
  32582. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  32583. });
  32584. }
  32585. //overwriting the old vertex buffers and indices.
  32586. this._reconstructedMesh.setIndices(newIndicesArray);
  32587. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  32588. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  32589. if (newUVsData.length > 0)
  32590. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  32591. if (newColorsData.length > 0)
  32592. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  32593. //create submesh
  32594. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  32595. if (submeshIndex > 0) {
  32596. this._reconstructedMesh.subMeshes = [];
  32597. submeshesArray.forEach(function (submesh) {
  32598. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  32599. });
  32600. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  32601. }
  32602. };
  32603. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  32604. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  32605. this._reconstructedMesh.material = this._mesh.material;
  32606. this._reconstructedMesh.parent = this._mesh.parent;
  32607. this._reconstructedMesh.isVisible = false;
  32608. };
  32609. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  32610. for (var i = 0; i < vertex1.triangleCount; ++i) {
  32611. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  32612. if (t.deleted)
  32613. continue;
  32614. var s = this.references[vertex1.triangleStart + i].vertexId;
  32615. var v1 = t.vertices[(s + 1) % 3];
  32616. var v2 = t.vertices[(s + 2) % 3];
  32617. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  32618. deletedArray[i] = true;
  32619. delTr.push(t);
  32620. continue;
  32621. }
  32622. var d1 = v1.position.subtract(point);
  32623. d1 = d1.normalize();
  32624. var d2 = v2.position.subtract(point);
  32625. d2 = d2.normalize();
  32626. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  32627. return true;
  32628. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  32629. deletedArray[i] = false;
  32630. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  32631. return true;
  32632. }
  32633. return false;
  32634. };
  32635. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  32636. var newDeleted = deletedTriangles;
  32637. for (var i = 0; i < vertex.triangleCount; ++i) {
  32638. var ref = this.references[vertex.triangleStart + i];
  32639. var t = this.triangles[ref.triangleId];
  32640. if (t.deleted)
  32641. continue;
  32642. if (deletedArray[i] && t.deletePending) {
  32643. t.deleted = true;
  32644. newDeleted++;
  32645. continue;
  32646. }
  32647. t.vertices[ref.vertexId] = origVertex;
  32648. t.isDirty = true;
  32649. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  32650. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  32651. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  32652. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32653. this.references.push(ref);
  32654. }
  32655. return newDeleted;
  32656. };
  32657. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  32658. for (var i = 0; i < this.vertices.length; ++i) {
  32659. var vCount = [];
  32660. var vId = [];
  32661. var v = this.vertices[i];
  32662. var j;
  32663. for (j = 0; j < v.triangleCount; ++j) {
  32664. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  32665. for (var ii = 0; ii < 3; ii++) {
  32666. var ofs = 0;
  32667. var vv = triangle.vertices[ii];
  32668. while (ofs < vCount.length) {
  32669. if (vId[ofs] === vv.id)
  32670. break;
  32671. ++ofs;
  32672. }
  32673. if (ofs === vCount.length) {
  32674. vCount.push(1);
  32675. vId.push(vv.id);
  32676. }
  32677. else {
  32678. vCount[ofs]++;
  32679. }
  32680. }
  32681. }
  32682. for (j = 0; j < vCount.length; ++j) {
  32683. if (vCount[j] === 1) {
  32684. this.vertices[vId[j]].isBorder = true;
  32685. }
  32686. else {
  32687. this.vertices[vId[j]].isBorder = false;
  32688. }
  32689. }
  32690. }
  32691. };
  32692. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  32693. if (identifyBorders === void 0) { identifyBorders = false; }
  32694. var i;
  32695. if (!identifyBorders) {
  32696. var newTrianglesVector = [];
  32697. for (i = 0; i < this.triangles.length; ++i) {
  32698. if (!this.triangles[i].deleted) {
  32699. newTrianglesVector.push(this.triangles[i]);
  32700. }
  32701. }
  32702. this.triangles = newTrianglesVector;
  32703. }
  32704. for (i = 0; i < this.vertices.length; ++i) {
  32705. this.vertices[i].triangleCount = 0;
  32706. this.vertices[i].triangleStart = 0;
  32707. }
  32708. var t;
  32709. var j;
  32710. var v;
  32711. for (i = 0; i < this.triangles.length; ++i) {
  32712. t = this.triangles[i];
  32713. for (j = 0; j < 3; ++j) {
  32714. v = t.vertices[j];
  32715. v.triangleCount++;
  32716. }
  32717. }
  32718. var tStart = 0;
  32719. for (i = 0; i < this.vertices.length; ++i) {
  32720. this.vertices[i].triangleStart = tStart;
  32721. tStart += this.vertices[i].triangleCount;
  32722. this.vertices[i].triangleCount = 0;
  32723. }
  32724. var newReferences = new Array(this.triangles.length * 3);
  32725. for (i = 0; i < this.triangles.length; ++i) {
  32726. t = this.triangles[i];
  32727. for (j = 0; j < 3; ++j) {
  32728. v = t.vertices[j];
  32729. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32730. v.triangleCount++;
  32731. }
  32732. }
  32733. this.references = newReferences;
  32734. if (identifyBorders) {
  32735. this.identifyBorder();
  32736. }
  32737. };
  32738. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32739. var x = point.x;
  32740. var y = point.y;
  32741. var z = point.z;
  32742. 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
  32743. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32744. };
  32745. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32746. var q = vertex1.q.add(vertex2.q);
  32747. var border = vertex1.isBorder && vertex2.isBorder;
  32748. var error = 0;
  32749. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32750. if (qDet !== 0 && !border) {
  32751. if (!pointResult) {
  32752. pointResult = BABYLON.Vector3.Zero();
  32753. }
  32754. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32755. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32756. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32757. error = this.vertexError(q, pointResult);
  32758. }
  32759. else {
  32760. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32761. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32762. var error1 = this.vertexError(q, vertex1.position);
  32763. var error2 = this.vertexError(q, vertex2.position);
  32764. var error3 = this.vertexError(q, p3);
  32765. error = Math.min(error1, error2, error3);
  32766. if (error === error1) {
  32767. if (pointResult) {
  32768. pointResult.copyFrom(vertex1.position);
  32769. }
  32770. }
  32771. else if (error === error2) {
  32772. if (pointResult) {
  32773. pointResult.copyFrom(vertex2.position);
  32774. }
  32775. }
  32776. else {
  32777. if (pointResult) {
  32778. pointResult.copyFrom(p3);
  32779. }
  32780. }
  32781. }
  32782. return error;
  32783. };
  32784. return QuadraticErrorSimplification;
  32785. })();
  32786. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32787. })(BABYLON || (BABYLON = {}));
  32788. var BABYLON;
  32789. (function (BABYLON) {
  32790. var Analyser = (function () {
  32791. function Analyser(scene) {
  32792. this.SMOOTHING = 0.75;
  32793. this.FFT_SIZE = 512;
  32794. this.BARGRAPHAMPLITUDE = 256;
  32795. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32796. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32797. this._scene = scene;
  32798. this._audioEngine = BABYLON.Engine.audioEngine;
  32799. if (this._audioEngine.canUseWebAudio) {
  32800. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32801. this._webAudioAnalyser.minDecibels = -140;
  32802. this._webAudioAnalyser.maxDecibels = 0;
  32803. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32804. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32805. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32806. }
  32807. }
  32808. Analyser.prototype.getFrequencyBinCount = function () {
  32809. if (this._audioEngine.canUseWebAudio) {
  32810. return this._webAudioAnalyser.frequencyBinCount;
  32811. }
  32812. else {
  32813. return 0;
  32814. }
  32815. };
  32816. Analyser.prototype.getByteFrequencyData = function () {
  32817. if (this._audioEngine.canUseWebAudio) {
  32818. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32819. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32820. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32821. }
  32822. return this._byteFreqs;
  32823. };
  32824. Analyser.prototype.getByteTimeDomainData = function () {
  32825. if (this._audioEngine.canUseWebAudio) {
  32826. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32827. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32828. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32829. }
  32830. return this._byteTime;
  32831. };
  32832. Analyser.prototype.getFloatFrequencyData = function () {
  32833. if (this._audioEngine.canUseWebAudio) {
  32834. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32835. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32836. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32837. }
  32838. return this._floatFreqs;
  32839. };
  32840. Analyser.prototype.drawDebugCanvas = function () {
  32841. var _this = this;
  32842. if (this._audioEngine.canUseWebAudio) {
  32843. if (!this._debugCanvas) {
  32844. this._debugCanvas = document.createElement("canvas");
  32845. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32846. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32847. this._debugCanvas.style.position = "absolute";
  32848. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32849. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32850. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32851. document.body.appendChild(this._debugCanvas);
  32852. this._registerFunc = function () {
  32853. _this.drawDebugCanvas();
  32854. };
  32855. this._scene.registerBeforeRender(this._registerFunc);
  32856. }
  32857. if (this._registerFunc) {
  32858. var workingArray = this.getByteFrequencyData();
  32859. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32860. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32861. // Draw the frequency domain chart.
  32862. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32863. var value = workingArray[i];
  32864. var percent = value / this.BARGRAPHAMPLITUDE;
  32865. var height = this.DEBUGCANVASSIZE.height * percent;
  32866. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32867. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32868. var hue = i / this.getFrequencyBinCount() * 360;
  32869. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32870. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32871. }
  32872. }
  32873. }
  32874. };
  32875. Analyser.prototype.stopDebugCanvas = function () {
  32876. if (this._debugCanvas) {
  32877. this._scene.unregisterBeforeRender(this._registerFunc);
  32878. this._registerFunc = null;
  32879. document.body.removeChild(this._debugCanvas);
  32880. this._debugCanvas = null;
  32881. this._debugCanvasContext = null;
  32882. }
  32883. };
  32884. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32885. if (this._audioEngine.canUseWebAudio) {
  32886. inputAudioNode.connect(this._webAudioAnalyser);
  32887. this._webAudioAnalyser.connect(outputAudioNode);
  32888. }
  32889. };
  32890. Analyser.prototype.dispose = function () {
  32891. if (this._audioEngine.canUseWebAudio) {
  32892. this._webAudioAnalyser.disconnect();
  32893. }
  32894. };
  32895. return Analyser;
  32896. })();
  32897. BABYLON.Analyser = Analyser;
  32898. })(BABYLON || (BABYLON = {}));
  32899. var BABYLON;
  32900. (function (BABYLON) {
  32901. var DepthRenderer = (function () {
  32902. function DepthRenderer(scene, type) {
  32903. var _this = this;
  32904. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  32905. this._viewMatrix = BABYLON.Matrix.Zero();
  32906. this._projectionMatrix = BABYLON.Matrix.Zero();
  32907. this._transformMatrix = BABYLON.Matrix.Zero();
  32908. this._worldViewProjection = BABYLON.Matrix.Zero();
  32909. this._scene = scene;
  32910. var engine = scene.getEngine();
  32911. // Render target
  32912. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  32913. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32914. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32915. this._depthMap.refreshRate = 1;
  32916. this._depthMap.renderParticles = false;
  32917. this._depthMap.renderList = null;
  32918. // set default depth value to 1.0 (far away)
  32919. this._depthMap.onClear = function (engine) {
  32920. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  32921. };
  32922. // Custom render function
  32923. var renderSubMesh = function (subMesh) {
  32924. var mesh = subMesh.getRenderingMesh();
  32925. var scene = _this._scene;
  32926. var engine = scene.getEngine();
  32927. // Culling
  32928. engine.setState(subMesh.getMaterial().backFaceCulling);
  32929. // Managing instances
  32930. var batch = mesh._getInstancesRenderList(subMesh._id);
  32931. if (batch.mustReturn) {
  32932. return;
  32933. }
  32934. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32935. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32936. engine.enableEffect(_this._effect);
  32937. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  32938. var material = subMesh.getMaterial();
  32939. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32940. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  32941. // Alpha test
  32942. if (material && material.needAlphaTesting()) {
  32943. var alphaTexture = material.getAlphaTestTexture();
  32944. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32945. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32946. }
  32947. // Bones
  32948. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32949. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32950. }
  32951. // Draw
  32952. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32953. }
  32954. };
  32955. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32956. var index;
  32957. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32958. renderSubMesh(opaqueSubMeshes.data[index]);
  32959. }
  32960. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32961. renderSubMesh(alphaTestSubMeshes.data[index]);
  32962. }
  32963. };
  32964. }
  32965. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32966. var defines = [];
  32967. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32968. var mesh = subMesh.getMesh();
  32969. var scene = mesh.getScene();
  32970. var material = subMesh.getMaterial();
  32971. // Alpha test
  32972. if (material && material.needAlphaTesting()) {
  32973. defines.push("#define ALPHATEST");
  32974. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32975. attribs.push(BABYLON.VertexBuffer.UVKind);
  32976. defines.push("#define UV1");
  32977. }
  32978. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32979. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32980. defines.push("#define UV2");
  32981. }
  32982. }
  32983. // Bones
  32984. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32985. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32986. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32987. defines.push("#define BONES");
  32988. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32989. }
  32990. // Instances
  32991. if (useInstances) {
  32992. defines.push("#define INSTANCES");
  32993. attribs.push("world0");
  32994. attribs.push("world1");
  32995. attribs.push("world2");
  32996. attribs.push("world3");
  32997. }
  32998. // Get correct effect
  32999. var join = defines.join("\n");
  33000. if (this._cachedDefines !== join) {
  33001. this._cachedDefines = join;
  33002. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  33003. }
  33004. return this._effect.isReady();
  33005. };
  33006. DepthRenderer.prototype.getDepthMap = function () {
  33007. return this._depthMap;
  33008. };
  33009. // Methods
  33010. DepthRenderer.prototype.dispose = function () {
  33011. this._depthMap.dispose();
  33012. };
  33013. return DepthRenderer;
  33014. })();
  33015. BABYLON.DepthRenderer = DepthRenderer;
  33016. })(BABYLON || (BABYLON = {}));
  33017. var BABYLON;
  33018. (function (BABYLON) {
  33019. var SSAORenderingPipeline = (function (_super) {
  33020. __extends(SSAORenderingPipeline, _super);
  33021. /**
  33022. * @constructor
  33023. * @param {string} name - The rendering pipeline name
  33024. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33025. * @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 }
  33026. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33027. */
  33028. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  33029. var _this = this;
  33030. _super.call(this, scene.getEngine(), name);
  33031. // Members
  33032. /**
  33033. * The PassPostProcess id in the pipeline that contains the original scene color
  33034. * @type {string}
  33035. */
  33036. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  33037. /**
  33038. * The SSAO PostProcess id in the pipeline
  33039. * @type {string}
  33040. */
  33041. this.SSAORenderEffect = "SSAORenderEffect";
  33042. /**
  33043. * The horizontal blur PostProcess id in the pipeline
  33044. * @type {string}
  33045. */
  33046. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  33047. /**
  33048. * The vertical blur PostProcess id in the pipeline
  33049. * @type {string}
  33050. */
  33051. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  33052. /**
  33053. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  33054. * @type {string}
  33055. */
  33056. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  33057. /**
  33058. * The output strength of the SSAO post-process. Default value is 1.0.
  33059. * @type {number}
  33060. */
  33061. this.totalStrength = 1.0;
  33062. /**
  33063. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  33064. * @type {number}
  33065. */
  33066. this.radius = 0.0002;
  33067. /**
  33068. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  33069. * Must not be equal to fallOff and superior to fallOff.
  33070. * Default value is 0.0075
  33071. * @type {number}
  33072. */
  33073. this.area = 0.0075;
  33074. /**
  33075. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  33076. * Must not be equal to area and inferior to area.
  33077. * Default value is 0.0002
  33078. * @type {number}
  33079. */
  33080. this.fallOff = 0.0002;
  33081. this._firstUpdate = true;
  33082. this._scene = scene;
  33083. // Set up assets
  33084. this._createRandomTexture();
  33085. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  33086. var ssaoRatio = ratio.ssaoRatio || ratio;
  33087. var combineRatio = ratio.combineRatio || ratio;
  33088. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33089. this._createSSAOPostProcess(ssaoRatio);
  33090. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33091. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33092. this._createSSAOCombinePostProcess(combineRatio);
  33093. // Set up pipeline
  33094. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  33095. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  33096. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  33097. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  33098. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  33099. // Finish
  33100. scene.postProcessRenderPipelineManager.addPipeline(this);
  33101. if (cameras)
  33102. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33103. }
  33104. // Public Methods
  33105. /**
  33106. * Returns the horizontal blur PostProcess
  33107. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  33108. */
  33109. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  33110. return this._blurHPostProcess;
  33111. };
  33112. /**
  33113. * Returns the vertical blur PostProcess
  33114. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  33115. */
  33116. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  33117. return this._blurVPostProcess;
  33118. };
  33119. /**
  33120. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  33121. */
  33122. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  33123. if (disableDepthRender === void 0) { disableDepthRender = false; }
  33124. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33125. this._originalColorPostProcess = undefined;
  33126. this._ssaoPostProcess = undefined;
  33127. this._blurHPostProcess = undefined;
  33128. this._blurVPostProcess = undefined;
  33129. this._ssaoCombinePostProcess = undefined;
  33130. this._randomTexture.dispose();
  33131. if (disableDepthRender)
  33132. this._scene.disableDepthRenderer();
  33133. };
  33134. // Private Methods
  33135. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  33136. var _this = this;
  33137. var sampleSphere = [
  33138. 0.5381, 0.1856, -0.4319,
  33139. 0.1379, 0.2486, 0.4430,
  33140. 0.3371, 0.5679, -0.0057,
  33141. -0.6999, -0.0451, -0.0019,
  33142. 0.0689, -0.1598, -0.8547,
  33143. 0.0560, 0.0069, -0.1843,
  33144. -0.0146, 0.1402, 0.0762,
  33145. 0.0100, -0.1924, -0.0344,
  33146. -0.3577, -0.5301, -0.4358,
  33147. -0.3169, 0.1063, 0.0158,
  33148. 0.0103, -0.5869, 0.0046,
  33149. -0.0897, -0.4940, 0.3287,
  33150. 0.7119, -0.0154, -0.0918,
  33151. -0.0533, 0.0596, -0.5411,
  33152. 0.0352, -0.0631, 0.5460,
  33153. -0.4776, 0.2847, -0.0271
  33154. ];
  33155. var samplesFactor = 1.0 / 16.0;
  33156. 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);
  33157. this._ssaoPostProcess.onApply = function (effect) {
  33158. if (_this._firstUpdate) {
  33159. effect.setArray3("sampleSphere", sampleSphere);
  33160. effect.setFloat("samplesFactor", samplesFactor);
  33161. effect.setFloat("randTextureTiles", 4.0 / ratio);
  33162. _this._firstUpdate = false;
  33163. }
  33164. effect.setFloat("totalStrength", _this.totalStrength);
  33165. effect.setFloat("radius", _this.radius);
  33166. effect.setFloat("area", _this.area);
  33167. effect.setFloat("fallOff", _this.fallOff);
  33168. effect.setTexture("textureSampler", _this._depthTexture);
  33169. effect.setTexture("randomSampler", _this._randomTexture);
  33170. };
  33171. };
  33172. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  33173. var _this = this;
  33174. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33175. this._ssaoCombinePostProcess.onApply = function (effect) {
  33176. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  33177. };
  33178. };
  33179. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  33180. var size = 512;
  33181. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33182. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33183. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33184. var context = this._randomTexture.getContext();
  33185. var rand = function (min, max) {
  33186. return Math.random() * (max - min) + min;
  33187. };
  33188. for (var x = 0; x < size; x++) {
  33189. for (var y = 0; y < size; y++) {
  33190. var randVector = BABYLON.Vector3.Zero();
  33191. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  33192. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  33193. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  33194. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  33195. context.fillRect(x, y, 1, 1);
  33196. }
  33197. }
  33198. this._randomTexture.update(false);
  33199. };
  33200. return SSAORenderingPipeline;
  33201. })(BABYLON.PostProcessRenderPipeline);
  33202. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  33203. })(BABYLON || (BABYLON = {}));
  33204. var BABYLON;
  33205. (function (BABYLON) {
  33206. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  33207. var VolumetricLightScatteringPostProcess = (function (_super) {
  33208. __extends(VolumetricLightScatteringPostProcess, _super);
  33209. /**
  33210. * @constructor
  33211. * @param {string} name - The post-process name
  33212. * @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)
  33213. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  33214. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  33215. * @param {number} samples - The post-process quality, default 100
  33216. * @param {number} samplingMode - The post-process filtering mode
  33217. * @param {BABYLON.Engine} engine - The babylon engine
  33218. * @param {boolean} reusable - If the post-process is reusable
  33219. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  33220. */
  33221. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  33222. var _this = this;
  33223. if (samples === void 0) { samples = 100; }
  33224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33225. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  33226. this._screenCoordinates = BABYLON.Vector2.Zero();
  33227. /**
  33228. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  33229. * @type {boolean}
  33230. */
  33231. this.useCustomMeshPosition = false;
  33232. /**
  33233. * If the post-process should inverse the light scattering direction
  33234. * @type {boolean}
  33235. */
  33236. this.invert = true;
  33237. /**
  33238. * Set to true to use the diffuseColor instead of the diffuseTexture
  33239. * @type {boolean}
  33240. */
  33241. this.useDiffuseColor = false;
  33242. /**
  33243. * Array containing the excluded meshes not rendered in the internal pass
  33244. */
  33245. this.excludedMeshes = new Array();
  33246. /**
  33247. * Controls the overall intensity of the post-process
  33248. * @type {number}
  33249. */
  33250. this.exposure = 0.3;
  33251. /**
  33252. * Dissipates each sample's contribution in range [0, 1]
  33253. * @type {number}
  33254. */
  33255. this.decay = 0.96815;
  33256. /**
  33257. * Controls the overall intensity of each sample
  33258. * @type {number}
  33259. */
  33260. this.weight = 0.58767;
  33261. /**
  33262. * Controls the density of each sample
  33263. * @type {number}
  33264. */
  33265. this.density = 0.926;
  33266. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  33267. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  33268. // Configure mesh
  33269. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  33270. // Configure
  33271. this._createPass(scene, ratio.passRatio || ratio);
  33272. this.onApply = function (effect) {
  33273. _this._updateMeshScreenCoordinates(scene);
  33274. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  33275. effect.setFloat("exposure", _this.exposure);
  33276. effect.setFloat("decay", _this.decay);
  33277. effect.setFloat("weight", _this.weight);
  33278. effect.setFloat("density", _this.density);
  33279. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  33280. };
  33281. }
  33282. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  33283. var mesh = subMesh.getMesh();
  33284. var defines = [];
  33285. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33286. var material = subMesh.getMaterial();
  33287. var needUV = false;
  33288. // Render this.mesh as default
  33289. if (mesh === this.mesh) {
  33290. if (this.useDiffuseColor) {
  33291. defines.push("#define DIFFUSE_COLOR_RENDER");
  33292. }
  33293. else if (material) {
  33294. if (material.diffuseTexture !== undefined) {
  33295. defines.push("#define BASIC_RENDER");
  33296. }
  33297. else {
  33298. defines.push("#define DIFFUSE_COLOR_RENDER");
  33299. }
  33300. }
  33301. defines.push("#define NEED_UV");
  33302. needUV = true;
  33303. }
  33304. // Alpha test
  33305. if (material) {
  33306. if (material.needAlphaTesting()) {
  33307. defines.push("#define ALPHATEST");
  33308. }
  33309. if (material.opacityTexture !== undefined) {
  33310. defines.push("#define OPACITY");
  33311. if (material.opacityTexture.getAlphaFromRGB) {
  33312. defines.push("#define OPACITYRGB");
  33313. }
  33314. if (!needUV) {
  33315. defines.push("#define NEED_UV");
  33316. }
  33317. }
  33318. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33319. attribs.push(BABYLON.VertexBuffer.UVKind);
  33320. defines.push("#define UV1");
  33321. }
  33322. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33323. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33324. defines.push("#define UV2");
  33325. }
  33326. }
  33327. // Bones
  33328. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33329. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33330. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33331. defines.push("#define BONES");
  33332. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33333. }
  33334. // Instances
  33335. if (useInstances) {
  33336. defines.push("#define INSTANCES");
  33337. attribs.push("world0");
  33338. attribs.push("world1");
  33339. attribs.push("world2");
  33340. attribs.push("world3");
  33341. }
  33342. // Get correct effect
  33343. var join = defines.join("\n");
  33344. if (this._cachedDefines !== join) {
  33345. this._cachedDefines = join;
  33346. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  33347. }
  33348. return this._volumetricLightScatteringPass.isReady();
  33349. };
  33350. /**
  33351. * Sets the new light position for light scattering effect
  33352. * @param {BABYLON.Vector3} The new custom light position
  33353. */
  33354. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  33355. this._customMeshPosition = position;
  33356. };
  33357. /**
  33358. * Returns the light position for light scattering effect
  33359. * @return {BABYLON.Vector3} The custom light position
  33360. */
  33361. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  33362. return this._customMeshPosition;
  33363. };
  33364. /**
  33365. * Disposes the internal assets and detaches the post-process from the camera
  33366. */
  33367. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  33368. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  33369. if (rttIndex !== -1) {
  33370. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  33371. }
  33372. this._volumetricLightScatteringRTT.dispose();
  33373. _super.prototype.dispose.call(this, camera);
  33374. };
  33375. /**
  33376. * Returns the render target texture used by the post-process
  33377. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  33378. */
  33379. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  33380. return this._volumetricLightScatteringRTT;
  33381. };
  33382. // Private methods
  33383. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  33384. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  33385. return true;
  33386. }
  33387. return false;
  33388. };
  33389. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  33390. var _this = this;
  33391. var engine = scene.getEngine();
  33392. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  33393. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33394. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33395. this._volumetricLightScatteringRTT.renderList = null;
  33396. this._volumetricLightScatteringRTT.renderParticles = false;
  33397. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  33398. // Custom render function for submeshes
  33399. var renderSubMesh = function (subMesh) {
  33400. var mesh = subMesh.getRenderingMesh();
  33401. if (_this._meshExcluded(mesh)) {
  33402. return;
  33403. }
  33404. var scene = mesh.getScene();
  33405. var engine = scene.getEngine();
  33406. // Culling
  33407. engine.setState(subMesh.getMaterial().backFaceCulling);
  33408. // Managing instances
  33409. var batch = mesh._getInstancesRenderList(subMesh._id);
  33410. if (batch.mustReturn) {
  33411. return;
  33412. }
  33413. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33414. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33415. engine.enableEffect(_this._volumetricLightScatteringPass);
  33416. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  33417. var material = subMesh.getMaterial();
  33418. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  33419. // Alpha test
  33420. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  33421. var alphaTexture = material.getAlphaTestTexture();
  33422. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  33423. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  33424. }
  33425. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  33426. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  33427. if (alphaTexture) {
  33428. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33429. }
  33430. }
  33431. if (material.opacityTexture !== undefined) {
  33432. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  33433. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  33434. }
  33435. }
  33436. // Bones
  33437. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33438. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33439. }
  33440. // Draw
  33441. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  33442. }
  33443. };
  33444. // Render target texture callbacks
  33445. var savedSceneClearColor;
  33446. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  33447. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  33448. savedSceneClearColor = scene.clearColor;
  33449. scene.clearColor = sceneClearColor;
  33450. };
  33451. this._volumetricLightScatteringRTT.onAfterRender = function () {
  33452. scene.clearColor = savedSceneClearColor;
  33453. };
  33454. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33455. var engine = scene.getEngine();
  33456. var index;
  33457. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33458. renderSubMesh(opaqueSubMeshes.data[index]);
  33459. }
  33460. engine.setAlphaTesting(true);
  33461. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33462. renderSubMesh(alphaTestSubMeshes.data[index]);
  33463. }
  33464. engine.setAlphaTesting(false);
  33465. if (transparentSubMeshes.length) {
  33466. // Sort sub meshes
  33467. for (index = 0; index < transparentSubMeshes.length; index++) {
  33468. var submesh = transparentSubMeshes.data[index];
  33469. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  33470. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  33471. }
  33472. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  33473. sortedArray.sort(function (a, b) {
  33474. // Alpha index first
  33475. if (a._alphaIndex > b._alphaIndex) {
  33476. return 1;
  33477. }
  33478. if (a._alphaIndex < b._alphaIndex) {
  33479. return -1;
  33480. }
  33481. // Then distance to camera
  33482. if (a._distanceToCamera < b._distanceToCamera) {
  33483. return 1;
  33484. }
  33485. if (a._distanceToCamera > b._distanceToCamera) {
  33486. return -1;
  33487. }
  33488. return 0;
  33489. });
  33490. // Render sub meshes
  33491. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33492. for (index = 0; index < sortedArray.length; index++) {
  33493. renderSubMesh(sortedArray[index]);
  33494. }
  33495. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33496. }
  33497. };
  33498. };
  33499. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  33500. var transform = scene.getTransformMatrix();
  33501. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  33502. this._screenCoordinates.x = pos.x / this._viewPort.width;
  33503. this._screenCoordinates.y = pos.y / this._viewPort.height;
  33504. if (this.invert)
  33505. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  33506. };
  33507. // Static methods
  33508. /**
  33509. * Creates a default mesh for the Volumeric Light Scattering post-process
  33510. * @param {string} The mesh name
  33511. * @param {BABYLON.Scene} The scene where to create the mesh
  33512. * @return {BABYLON.Mesh} the default mesh
  33513. */
  33514. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  33515. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  33516. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  33517. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  33518. return mesh;
  33519. };
  33520. return VolumetricLightScatteringPostProcess;
  33521. })(BABYLON.PostProcess);
  33522. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  33523. })(BABYLON || (BABYLON = {}));
  33524. var BABYLON;
  33525. (function (BABYLON) {
  33526. var LensRenderingPipeline = (function (_super) {
  33527. __extends(LensRenderingPipeline, _super);
  33528. /**
  33529. * @constructor
  33530. *
  33531. * Effect parameters are as follow:
  33532. * {
  33533. * chromatic_aberration: number; // from 0 to x (1 for realism)
  33534. * edge_blur: number; // from 0 to x (1 for realism)
  33535. * distortion: number; // from 0 to x (1 for realism)
  33536. * grain_amount: number; // from 0 to 1
  33537. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  33538. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  33539. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  33540. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  33541. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  33542. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  33543. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  33544. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  33545. * }
  33546. * Note: if an effect parameter is unset, effect is disabled
  33547. *
  33548. * @param {string} name - The rendering pipeline name
  33549. * @param {object} parameters - An object containing all parameters (see above)
  33550. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33551. * @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)
  33552. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33553. */
  33554. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  33555. var _this = this;
  33556. if (ratio === void 0) { ratio = 1.0; }
  33557. _super.call(this, scene.getEngine(), name);
  33558. // Lens effects can be of the following:
  33559. // - chromatic aberration (slight shift of RGB colors)
  33560. // - blur on the edge of the lens
  33561. // - lens distortion
  33562. // - depth-of-field blur & highlights enhancing
  33563. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  33564. // - grain effect (noise or custom texture)
  33565. // Two additional texture samplers are needed:
  33566. // - depth map (for depth-of-field)
  33567. // - grain texture
  33568. /**
  33569. * The chromatic aberration PostProcess id in the pipeline
  33570. * @type {string}
  33571. */
  33572. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  33573. /**
  33574. * The highlights enhancing PostProcess id in the pipeline
  33575. * @type {string}
  33576. */
  33577. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  33578. /**
  33579. * The depth-of-field PostProcess id in the pipeline
  33580. * @type {string}
  33581. */
  33582. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  33583. this._scene = scene;
  33584. // Fetch texture samplers
  33585. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  33586. if (parameters.grain_texture) {
  33587. this._grainTexture = parameters.grain_texture;
  33588. }
  33589. else {
  33590. this._createGrainTexture();
  33591. }
  33592. // save parameters
  33593. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  33594. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  33595. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  33596. this._distortion = parameters.distortion ? parameters.distortion : 0;
  33597. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  33598. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  33599. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  33600. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  33601. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  33602. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  33603. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  33604. // Create effects
  33605. this._createChromaticAberrationPostProcess(ratio);
  33606. this._createHighlightsPostProcess(ratio);
  33607. this._createDepthOfFieldPostProcess(ratio / 4);
  33608. // Set up pipeline
  33609. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  33610. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  33611. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  33612. if (this._highlightsGain == -1) {
  33613. this._disableEffect(this.HighlightsEnhancingEffect, null);
  33614. }
  33615. // Finish
  33616. scene.postProcessRenderPipelineManager.addPipeline(this);
  33617. if (cameras) {
  33618. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33619. }
  33620. }
  33621. // public methods (self explanatory)
  33622. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  33623. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  33624. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  33625. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  33626. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  33627. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  33628. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  33629. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  33630. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  33631. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  33632. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  33633. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  33634. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  33635. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  33636. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  33637. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  33638. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  33639. this._highlightsGain = amount;
  33640. };
  33641. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  33642. if (this._highlightsGain == -1) {
  33643. this._highlightsGain = 1.0;
  33644. }
  33645. this._highlightsThreshold = amount;
  33646. };
  33647. LensRenderingPipeline.prototype.disableHighlights = function () {
  33648. this._highlightsGain = -1;
  33649. };
  33650. /**
  33651. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  33652. */
  33653. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  33654. if (disableDepthRender === void 0) { disableDepthRender = false; }
  33655. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33656. this._chromaticAberrationPostProcess = undefined;
  33657. this._highlightsPostProcess = undefined;
  33658. this._depthOfFieldPostProcess = undefined;
  33659. this._grainTexture.dispose();
  33660. if (disableDepthRender)
  33661. this._scene.disableDepthRenderer();
  33662. };
  33663. // colors shifting and distortion
  33664. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  33665. var _this = this;
  33666. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  33667. [], // samplers
  33668. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33669. this._chromaticAberrationPostProcess.onApply = function (effect) {
  33670. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  33671. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33672. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33673. };
  33674. };
  33675. // highlights enhancing
  33676. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  33677. var _this = this;
  33678. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  33679. [], // samplers
  33680. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33681. this._highlightsPostProcess.onApply = function (effect) {
  33682. effect.setFloat('gain', _this._highlightsGain);
  33683. effect.setFloat('threshold', _this._highlightsThreshold);
  33684. effect.setBool('pentagon', _this._dofPentagon);
  33685. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  33686. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33687. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33688. };
  33689. };
  33690. // colors shifting and distortion
  33691. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  33692. var _this = this;
  33693. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  33694. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  33695. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  33696. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33697. this._depthOfFieldPostProcess.onApply = function (effect) {
  33698. effect.setTexture("depthSampler", _this._depthTexture);
  33699. effect.setTexture("grainSampler", _this._grainTexture);
  33700. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  33701. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  33702. effect.setFloat('grain_amount', _this._grainAmount);
  33703. effect.setBool('blur_noise', _this._blurNoise);
  33704. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33705. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33706. effect.setFloat('distortion', _this._distortion);
  33707. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  33708. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  33709. effect.setFloat('aperture', _this._dofAperture);
  33710. effect.setFloat('darken', _this._dofDarken);
  33711. effect.setFloat('edge_blur', _this._edgeBlur);
  33712. effect.setBool('highlights', (_this._highlightsGain != -1));
  33713. effect.setFloat('near', _this._scene.activeCamera.minZ);
  33714. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  33715. };
  33716. };
  33717. // creates a black and white random noise texture, 512x512
  33718. LensRenderingPipeline.prototype._createGrainTexture = function () {
  33719. var size = 512;
  33720. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33721. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33722. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33723. var context = this._grainTexture.getContext();
  33724. var rand = function (min, max) {
  33725. return Math.random() * (max - min) + min;
  33726. };
  33727. var value;
  33728. for (var x = 0; x < size; x++) {
  33729. for (var y = 0; y < size; y++) {
  33730. value = Math.floor(rand(0.42, 0.58) * 255);
  33731. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  33732. context.fillRect(x, y, 1, 1);
  33733. }
  33734. }
  33735. this._grainTexture.update(false);
  33736. };
  33737. return LensRenderingPipeline;
  33738. })(BABYLON.PostProcessRenderPipeline);
  33739. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  33740. })(BABYLON || (BABYLON = {}));
  33741. //
  33742. // This post-process allows the modification of rendered colors by using
  33743. // a 'look-up table' (LUT). This effect is also called Color Grading.
  33744. //
  33745. // The object needs to be provided an url to a texture containing the color
  33746. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  33747. // Use an image editing software to tweak the LUT to match your needs.
  33748. //
  33749. // For an example of a color LUT, see here:
  33750. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  33751. // For explanations on color grading, see here:
  33752. // http://udn.epicgames.com/Three/ColorGrading.html
  33753. //
  33754. var BABYLON;
  33755. (function (BABYLON) {
  33756. var ColorCorrectionPostProcess = (function (_super) {
  33757. __extends(ColorCorrectionPostProcess, _super);
  33758. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  33759. var _this = this;
  33760. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  33761. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  33762. this._colorTableTexture.anisotropicFilteringLevel = 1;
  33763. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33764. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33765. this.onApply = function (effect) {
  33766. effect.setTexture("colorTable", _this._colorTableTexture);
  33767. };
  33768. }
  33769. return ColorCorrectionPostProcess;
  33770. })(BABYLON.PostProcess);
  33771. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  33772. })(BABYLON || (BABYLON = {}));
  33773. var BABYLON;
  33774. (function (BABYLON) {
  33775. var AnaglyphFreeCamera = (function (_super) {
  33776. __extends(AnaglyphFreeCamera, _super);
  33777. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  33778. _super.call(this, name, position, scene);
  33779. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33780. }
  33781. return AnaglyphFreeCamera;
  33782. })(BABYLON.FreeCamera);
  33783. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  33784. var AnaglyphArcRotateCamera = (function (_super) {
  33785. __extends(AnaglyphArcRotateCamera, _super);
  33786. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  33787. _super.call(this, name, alpha, beta, radius, target, scene);
  33788. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33789. }
  33790. return AnaglyphArcRotateCamera;
  33791. })(BABYLON.ArcRotateCamera);
  33792. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  33793. var AnaglyphGamepadCamera = (function (_super) {
  33794. __extends(AnaglyphGamepadCamera, _super);
  33795. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  33796. _super.call(this, name, position, scene);
  33797. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33798. }
  33799. return AnaglyphGamepadCamera;
  33800. })(BABYLON.GamepadCamera);
  33801. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  33802. var StereoscopicFreeCamera = (function (_super) {
  33803. __extends(StereoscopicFreeCamera, _super);
  33804. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33805. _super.call(this, name, position, scene);
  33806. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33807. }
  33808. return StereoscopicFreeCamera;
  33809. })(BABYLON.FreeCamera);
  33810. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  33811. var StereoscopicArcRotateCamera = (function (_super) {
  33812. __extends(StereoscopicArcRotateCamera, _super);
  33813. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  33814. _super.call(this, name, alpha, beta, radius, target, scene);
  33815. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33816. }
  33817. return StereoscopicArcRotateCamera;
  33818. })(BABYLON.ArcRotateCamera);
  33819. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  33820. var StereoscopicGamepadCamera = (function (_super) {
  33821. __extends(StereoscopicGamepadCamera, _super);
  33822. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33823. _super.call(this, name, position, scene);
  33824. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33825. }
  33826. return StereoscopicGamepadCamera;
  33827. })(BABYLON.GamepadCamera);
  33828. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  33829. })(BABYLON || (BABYLON = {}));
  33830. var BABYLON;
  33831. (function (BABYLON) {
  33832. var HDRRenderingPipeline = (function (_super) {
  33833. __extends(HDRRenderingPipeline, _super);
  33834. /**
  33835. * @constructor
  33836. * @param {string} name - The rendering pipeline name
  33837. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33838. * @param {any} 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)
  33839. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  33840. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33841. */
  33842. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  33843. var _this = this;
  33844. if (originalPostProcess === void 0) { originalPostProcess = null; }
  33845. _super.call(this, scene.getEngine(), name);
  33846. /**
  33847. * Public members
  33848. */
  33849. // Gaussian Blur
  33850. /**
  33851. * Gaussian blur coefficient
  33852. * @type {number}
  33853. */
  33854. this.gaussCoeff = 0.3;
  33855. /**
  33856. * Gaussian blur mean
  33857. * @type {number}
  33858. */
  33859. this.gaussMean = 1.0;
  33860. /**
  33861. * Gaussian blur standard deviation
  33862. * @type {number}
  33863. */
  33864. this.gaussStandDev = 0.8;
  33865. // HDR
  33866. /**
  33867. * Exposure, controls the overall intensity of the pipeline
  33868. * @type {number}
  33869. */
  33870. this.exposure = 1.0;
  33871. /**
  33872. * Minimum luminance that the post-process can output. Luminance is >= 0
  33873. * @type {number}
  33874. */
  33875. this.minimumLuminance = 1.0;
  33876. /**
  33877. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  33878. * @type {number}
  33879. */
  33880. this.maximumLuminance = 1e20;
  33881. /**
  33882. * Increase rate for luminance: eye adaptation speed to dark
  33883. * @type {number}
  33884. */
  33885. this.luminanceIncreaserate = 0.5;
  33886. /**
  33887. * Decrease rate for luminance: eye adaptation speed to bright
  33888. * @type {number}
  33889. */
  33890. this.luminanceDecreaseRate = 0.5;
  33891. // Bright pass
  33892. /**
  33893. * Minimum luminance needed to compute HDR
  33894. * @type {number}
  33895. */
  33896. this.brightThreshold = 0.8;
  33897. this._needUpdate = true;
  33898. this._scene = scene;
  33899. // Bright pass
  33900. this._createBrightPassPostProcess(scene, ratio);
  33901. // Down sample X4
  33902. this._createDownSampleX4PostProcess(scene, ratio);
  33903. // Create gaussian blur post-processes
  33904. this._createGaussianBlurPostProcess(scene, ratio);
  33905. // Texture adder
  33906. this._createTextureAdderPostProcess(scene, ratio);
  33907. // Luminance generator
  33908. this._createLuminanceGeneratorPostProcess(scene);
  33909. // HDR
  33910. this._createHDRPostProcess(scene, ratio);
  33911. // Pass postprocess
  33912. if (originalPostProcess === null) {
  33913. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33914. }
  33915. else {
  33916. this._originalPostProcess = originalPostProcess;
  33917. }
  33918. // Configure pipeline
  33919. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  33920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  33921. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  33922. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  33923. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  33924. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  33925. var addDownSamplerPostProcess = function (id) {
  33926. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  33927. };
  33928. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33929. addDownSamplerPostProcess(i);
  33930. }
  33931. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  33932. // Finish
  33933. scene.postProcessRenderPipelineManager.addPipeline(this);
  33934. if (cameras !== null) {
  33935. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33936. }
  33937. this.update();
  33938. }
  33939. /**
  33940. * Tells the pipeline to update its post-processes
  33941. */
  33942. HDRRenderingPipeline.prototype.update = function () {
  33943. this._needUpdate = true;
  33944. };
  33945. /**
  33946. * Returns the current calculated luminance
  33947. */
  33948. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33949. return this._hdrCurrentLuminance;
  33950. };
  33951. /**
  33952. * Returns the currently drawn luminance
  33953. */
  33954. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33955. return this._hdrOutputLuminance;
  33956. };
  33957. /**
  33958. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33959. */
  33960. HDRRenderingPipeline.prototype.dispose = function () {
  33961. this._originalPostProcess = undefined;
  33962. this._brightPassPostProcess = undefined;
  33963. this._downSampleX4PostProcess = undefined;
  33964. this._guassianBlurHPostProcess = undefined;
  33965. this._guassianBlurVPostProcess = undefined;
  33966. this._textureAdderPostProcess = undefined;
  33967. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33968. this._downSamplePostProcesses[i] = undefined;
  33969. }
  33970. this._hdrPostProcess = undefined;
  33971. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33972. };
  33973. /**
  33974. * Creates the HDR post-process and computes the luminance adaptation
  33975. */
  33976. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33977. var _this = this;
  33978. var hdrLastLuminance = 0.0;
  33979. this._hdrOutputLuminance = -1.0;
  33980. this._hdrCurrentLuminance = 1.0;
  33981. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33982. this._hdrPostProcess.onApply = function (effect) {
  33983. if (_this._hdrOutputLuminance < 0.0) {
  33984. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33985. }
  33986. else {
  33987. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33988. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33989. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33990. }
  33991. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33992. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33993. }
  33994. else {
  33995. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33996. }
  33997. }
  33998. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33999. hdrLastLuminance += scene.getEngine().getDeltaTime();
  34000. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  34001. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  34002. effect.setFloat("exposure", _this.exposure);
  34003. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  34004. _this._needUpdate = false;
  34005. };
  34006. };
  34007. /**
  34008. * Texture Adder post-process
  34009. */
  34010. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  34011. var _this = this;
  34012. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  34013. this._textureAdderPostProcess.onApply = function (effect) {
  34014. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  34015. };
  34016. };
  34017. /**
  34018. * Down sample X4 post-process
  34019. */
  34020. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  34021. var _this = this;
  34022. var downSampleX4Offsets = new Array(32);
  34023. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  34024. this._downSampleX4PostProcess.onApply = function (effect) {
  34025. if (_this._needUpdate) {
  34026. var id = 0;
  34027. for (var i = -2; i < 2; i++) {
  34028. for (var j = -2; j < 2; j++) {
  34029. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  34030. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  34031. id += 2;
  34032. }
  34033. }
  34034. }
  34035. effect.setArray2("dsOffsets", downSampleX4Offsets);
  34036. };
  34037. };
  34038. /**
  34039. * Bright pass post-process
  34040. */
  34041. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  34042. var _this = this;
  34043. var brightOffsets = new Array(8);
  34044. var brightPassCallback = function (effect) {
  34045. if (_this._needUpdate) {
  34046. var sU = (1.0 / _this._brightPassPostProcess.width);
  34047. var sV = (1.0 / _this._brightPassPostProcess.height);
  34048. brightOffsets[0] = -0.5 * sU;
  34049. brightOffsets[1] = 0.5 * sV;
  34050. brightOffsets[2] = 0.5 * sU;
  34051. brightOffsets[3] = 0.5 * sV;
  34052. brightOffsets[4] = -0.5 * sU;
  34053. brightOffsets[5] = -0.5 * sV;
  34054. brightOffsets[6] = 0.5 * sU;
  34055. brightOffsets[7] = -0.5 * sV;
  34056. }
  34057. effect.setArray2("dsOffsets", brightOffsets);
  34058. effect.setFloat("brightThreshold", _this.brightThreshold);
  34059. };
  34060. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  34061. this._brightPassPostProcess.onApply = brightPassCallback;
  34062. };
  34063. /**
  34064. * Luminance generator. Creates the luminance post-process and down sample post-processes
  34065. */
  34066. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  34067. var _this = this;
  34068. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  34069. var luminanceOffsets = new Array(8);
  34070. var downSampleOffsets = new Array(18);
  34071. var halfDestPixelSize;
  34072. this._downSamplePostProcesses = new Array(lumSteps);
  34073. // Utils for luminance
  34074. var luminanceUpdateSourceOffsets = function (width, height) {
  34075. var sU = (1.0 / width);
  34076. var sV = (1.0 / height);
  34077. luminanceOffsets[0] = -0.5 * sU;
  34078. luminanceOffsets[1] = 0.5 * sV;
  34079. luminanceOffsets[2] = 0.5 * sU;
  34080. luminanceOffsets[3] = 0.5 * sV;
  34081. luminanceOffsets[4] = -0.5 * sU;
  34082. luminanceOffsets[5] = -0.5 * sV;
  34083. luminanceOffsets[6] = 0.5 * sU;
  34084. luminanceOffsets[7] = -0.5 * sV;
  34085. };
  34086. var luminanceUpdateDestOffsets = function (width, height) {
  34087. var id = 0;
  34088. for (var x = -1; x < 2; x++) {
  34089. for (var y = -1; y < 2; y++) {
  34090. downSampleOffsets[id] = (x) / width;
  34091. downSampleOffsets[id + 1] = (y) / height;
  34092. id += 2;
  34093. }
  34094. }
  34095. };
  34096. // Luminance callback
  34097. var luminanceCallback = function (effect) {
  34098. if (_this._needUpdate) {
  34099. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  34100. }
  34101. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  34102. effect.setArray2("lumOffsets", luminanceOffsets);
  34103. };
  34104. // Down sample callbacks
  34105. var downSampleCallback = function (indice) {
  34106. var i = indice;
  34107. return function (effect) {
  34108. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  34109. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  34110. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  34111. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  34112. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  34113. effect.setArray2("dsOffsets", downSampleOffsets);
  34114. };
  34115. };
  34116. var downSampleAfterRenderCallback = function (effect) {
  34117. // Unpack result
  34118. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  34119. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  34120. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  34121. };
  34122. // Create luminance post-process
  34123. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  34124. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  34125. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  34126. // Create down sample post-processes
  34127. for (var i = lumSteps - 2; i >= 0; i--) {
  34128. var length = Math.pow(3, i);
  34129. ratio = { width: length, height: length };
  34130. var defines = "#define DOWN_SAMPLE\n";
  34131. if (i === 0) {
  34132. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  34133. }
  34134. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  34135. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  34136. if (i === 0) {
  34137. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  34138. }
  34139. }
  34140. };
  34141. /**
  34142. * Gaussian blur post-processes. Horizontal and Vertical
  34143. */
  34144. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  34145. var _this = this;
  34146. var blurOffsetsW = new Array(9);
  34147. var blurOffsetsH = new Array(9);
  34148. var blurWeights = new Array(9);
  34149. var uniforms = ["blurOffsets", "blurWeights"];
  34150. // Utils for gaussian blur
  34151. var calculateBlurOffsets = function (height) {
  34152. var lastOutputDimensions = {
  34153. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  34154. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  34155. };
  34156. for (var i = 0; i < 9; i++) {
  34157. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  34158. if (height) {
  34159. blurOffsetsH[i] = value;
  34160. }
  34161. else {
  34162. blurOffsetsW[i] = value;
  34163. }
  34164. }
  34165. };
  34166. var calculateWeights = function () {
  34167. var x = 0.0;
  34168. for (var i = 0; i < 9; i++) {
  34169. x = (i - 4.0) / 4.0;
  34170. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  34171. }
  34172. };
  34173. // Callback
  34174. var gaussianBlurCallback = function (height) {
  34175. return function (effect) {
  34176. if (_this._needUpdate) {
  34177. calculateWeights();
  34178. calculateBlurOffsets(height);
  34179. }
  34180. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  34181. effect.setArray("blurWeights", blurWeights);
  34182. };
  34183. };
  34184. // Create horizontal gaussian blur post-processes
  34185. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  34186. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  34187. // Create vertical gaussian blur post-process
  34188. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  34189. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  34190. };
  34191. // Luminance generator
  34192. HDRRenderingPipeline.LUM_STEPS = 6;
  34193. return HDRRenderingPipeline;
  34194. })(BABYLON.PostProcessRenderPipeline);
  34195. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  34196. })(BABYLON || (BABYLON = {}));
  34197. var BABYLON;
  34198. (function (BABYLON) {
  34199. var FaceAdjacencies = (function () {
  34200. function FaceAdjacencies() {
  34201. this.edges = new Array();
  34202. this.edgesConnectedCount = 0;
  34203. }
  34204. return FaceAdjacencies;
  34205. })();
  34206. var EdgesRenderer = (function () {
  34207. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  34208. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  34209. if (epsilon === void 0) { epsilon = 0.95; }
  34210. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  34211. this._linesPositions = new Array();
  34212. this._linesNormals = new Array();
  34213. this._linesIndices = new Array();
  34214. this._buffers = new Array();
  34215. this._checkVerticesInsteadOfIndices = false;
  34216. this._source = source;
  34217. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  34218. this._epsilon = epsilon;
  34219. this._prepareRessources();
  34220. this._generateEdgesLines();
  34221. }
  34222. EdgesRenderer.prototype._prepareRessources = function () {
  34223. if (this._lineShader) {
  34224. return;
  34225. }
  34226. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  34227. attributes: ["position", "normal"],
  34228. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  34229. });
  34230. this._lineShader.disableDepthWrite = true;
  34231. this._lineShader.backFaceCulling = false;
  34232. };
  34233. EdgesRenderer.prototype.dispose = function () {
  34234. this._vb0.dispose();
  34235. this._vb1.dispose();
  34236. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  34237. this._lineShader.dispose();
  34238. };
  34239. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  34240. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  34241. return 0;
  34242. }
  34243. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  34244. return 1;
  34245. }
  34246. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  34247. return 2;
  34248. }
  34249. return -1;
  34250. };
  34251. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  34252. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  34253. return 0;
  34254. }
  34255. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  34256. return 1;
  34257. }
  34258. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  34259. return 2;
  34260. }
  34261. return -1;
  34262. };
  34263. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  34264. var needToCreateLine;
  34265. if (edge === undefined) {
  34266. needToCreateLine = true;
  34267. }
  34268. else {
  34269. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  34270. needToCreateLine = dotProduct < this._epsilon;
  34271. }
  34272. if (needToCreateLine) {
  34273. var offset = this._linesPositions.length / 3;
  34274. var normal = p0.subtract(p1);
  34275. normal.normalize();
  34276. // Positions
  34277. this._linesPositions.push(p0.x);
  34278. this._linesPositions.push(p0.y);
  34279. this._linesPositions.push(p0.z);
  34280. this._linesPositions.push(p0.x);
  34281. this._linesPositions.push(p0.y);
  34282. this._linesPositions.push(p0.z);
  34283. this._linesPositions.push(p1.x);
  34284. this._linesPositions.push(p1.y);
  34285. this._linesPositions.push(p1.z);
  34286. this._linesPositions.push(p1.x);
  34287. this._linesPositions.push(p1.y);
  34288. this._linesPositions.push(p1.z);
  34289. // Normals
  34290. this._linesNormals.push(p1.x);
  34291. this._linesNormals.push(p1.y);
  34292. this._linesNormals.push(p1.z);
  34293. this._linesNormals.push(-1);
  34294. this._linesNormals.push(p1.x);
  34295. this._linesNormals.push(p1.y);
  34296. this._linesNormals.push(p1.z);
  34297. this._linesNormals.push(1);
  34298. this._linesNormals.push(p0.x);
  34299. this._linesNormals.push(p0.y);
  34300. this._linesNormals.push(p0.z);
  34301. this._linesNormals.push(-1);
  34302. this._linesNormals.push(p0.x);
  34303. this._linesNormals.push(p0.y);
  34304. this._linesNormals.push(p0.z);
  34305. this._linesNormals.push(1);
  34306. // Indices
  34307. this._linesIndices.push(offset);
  34308. this._linesIndices.push(offset + 1);
  34309. this._linesIndices.push(offset + 2);
  34310. this._linesIndices.push(offset);
  34311. this._linesIndices.push(offset + 2);
  34312. this._linesIndices.push(offset + 3);
  34313. }
  34314. };
  34315. EdgesRenderer.prototype._generateEdgesLines = function () {
  34316. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34317. var indices = this._source.getIndices();
  34318. // First let's find adjacencies
  34319. var adjacencies = new Array();
  34320. var faceNormals = new Array();
  34321. var index;
  34322. var faceAdjacencies;
  34323. // Prepare faces
  34324. for (index = 0; index < indices.length; index += 3) {
  34325. faceAdjacencies = new FaceAdjacencies();
  34326. var p0Index = indices[index];
  34327. var p1Index = indices[index + 1];
  34328. var p2Index = indices[index + 2];
  34329. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  34330. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  34331. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  34332. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  34333. faceNormal.normalize();
  34334. faceNormals.push(faceNormal);
  34335. adjacencies.push(faceAdjacencies);
  34336. }
  34337. // Scan
  34338. for (index = 0; index < adjacencies.length; index++) {
  34339. faceAdjacencies = adjacencies[index];
  34340. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  34341. var otherFaceAdjacencies = adjacencies[otherIndex];
  34342. if (faceAdjacencies.edgesConnectedCount === 3) {
  34343. break;
  34344. }
  34345. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  34346. continue;
  34347. }
  34348. var otherP0 = indices[otherIndex * 3];
  34349. var otherP1 = indices[otherIndex * 3 + 1];
  34350. var otherP2 = indices[otherIndex * 3 + 2];
  34351. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  34352. var otherEdgeIndex;
  34353. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  34354. continue;
  34355. }
  34356. switch (edgeIndex) {
  34357. case 0:
  34358. if (this._checkVerticesInsteadOfIndices) {
  34359. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34360. }
  34361. else {
  34362. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  34363. }
  34364. break;
  34365. case 1:
  34366. if (this._checkVerticesInsteadOfIndices) {
  34367. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34368. }
  34369. else {
  34370. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  34371. }
  34372. break;
  34373. case 2:
  34374. if (this._checkVerticesInsteadOfIndices) {
  34375. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34376. }
  34377. else {
  34378. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  34379. }
  34380. break;
  34381. }
  34382. if (otherEdgeIndex === -1) {
  34383. continue;
  34384. }
  34385. faceAdjacencies.edges[edgeIndex] = otherIndex;
  34386. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  34387. faceAdjacencies.edgesConnectedCount++;
  34388. otherFaceAdjacencies.edgesConnectedCount++;
  34389. if (faceAdjacencies.edgesConnectedCount === 3) {
  34390. break;
  34391. }
  34392. }
  34393. }
  34394. }
  34395. // Create lines
  34396. for (index = 0; index < adjacencies.length; index++) {
  34397. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  34398. var current = adjacencies[index];
  34399. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  34400. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  34401. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  34402. }
  34403. // Merge into a single mesh
  34404. var engine = this._source.getScene().getEngine();
  34405. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  34406. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  34407. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  34408. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  34409. this._ib = engine.createIndexBuffer(this._linesIndices);
  34410. this._indicesCount = this._linesIndices.length;
  34411. };
  34412. EdgesRenderer.prototype.render = function () {
  34413. if (!this._lineShader.isReady()) {
  34414. return;
  34415. }
  34416. var scene = this._source.getScene();
  34417. var engine = scene.getEngine();
  34418. this._lineShader._preBind();
  34419. // VBOs
  34420. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  34421. scene.resetCachedMaterial();
  34422. this._lineShader.setColor4("color", this._source.edgesColor);
  34423. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  34424. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  34425. this._lineShader.bind(this._source.getWorldMatrix());
  34426. // Draw order
  34427. engine.draw(true, 0, this._indicesCount);
  34428. this._lineShader.unbind();
  34429. engine.setDepthWrite(true);
  34430. };
  34431. return EdgesRenderer;
  34432. })();
  34433. BABYLON.EdgesRenderer = EdgesRenderer;
  34434. })(BABYLON || (BABYLON = {}));
  34435. var BABYLON;
  34436. (function (BABYLON) {
  34437. (function (TonemappingOperator) {
  34438. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  34439. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  34440. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  34441. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  34442. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  34443. var TonemappingOperator = BABYLON.TonemappingOperator;
  34444. ;
  34445. var TonemapPostProcess = (function (_super) {
  34446. __extends(TonemapPostProcess, _super);
  34447. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  34448. var _this = this;
  34449. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34450. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34451. this._operator = operator;
  34452. this._exposureAdjustment = exposureAdjustment;
  34453. var params = ["_ExposureAdjustment"];
  34454. var defines = "#define ";
  34455. if (operator === TonemappingOperator.Hable)
  34456. defines += "HABLE_TONEMAPPING";
  34457. else if (operator === TonemappingOperator.Reinhard)
  34458. defines += "REINHARD_TONEMAPPING";
  34459. else if (operator === TonemappingOperator.HejiDawson)
  34460. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  34461. else if (operator === TonemappingOperator.Photographic)
  34462. defines += "PHOTOGRAPHIC_TONEMAPPING";
  34463. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  34464. this.onApply = function (effect) {
  34465. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  34466. };
  34467. }
  34468. return TonemapPostProcess;
  34469. })(BABYLON.PostProcess);
  34470. BABYLON.TonemapPostProcess = TonemapPostProcess;
  34471. })(BABYLON || (BABYLON = {}));
  34472. var BABYLON;
  34473. (function (BABYLON) {
  34474. var DefaultLoadingScreen = (function () {
  34475. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  34476. var _this = this;
  34477. if (_loadingText === void 0) { _loadingText = ""; }
  34478. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  34479. this._renderingCanvas = _renderingCanvas;
  34480. this._loadingText = _loadingText;
  34481. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  34482. // Resize
  34483. this._resizeLoadingUI = function () {
  34484. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  34485. _this._loadingDiv.style.position = "absolute";
  34486. _this._loadingDiv.style.left = canvasRect.left + "px";
  34487. _this._loadingDiv.style.top = canvasRect.top + "px";
  34488. _this._loadingDiv.style.width = canvasRect.width + "px";
  34489. _this._loadingDiv.style.height = canvasRect.height + "px";
  34490. };
  34491. }
  34492. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  34493. var _this = this;
  34494. this._loadingDiv = document.createElement("div");
  34495. this._loadingDiv.style.opacity = "0";
  34496. this._loadingDiv.style.transition = "opacity 1.5s ease";
  34497. // Loading text
  34498. this._loadingTextDiv = document.createElement("div");
  34499. this._loadingTextDiv.style.position = "absolute";
  34500. this._loadingTextDiv.style.left = "0";
  34501. this._loadingTextDiv.style.top = "50%";
  34502. this._loadingTextDiv.style.marginTop = "80px";
  34503. this._loadingTextDiv.style.width = "100%";
  34504. this._loadingTextDiv.style.height = "20px";
  34505. this._loadingTextDiv.style.fontFamily = "Arial";
  34506. this._loadingTextDiv.style.fontSize = "14px";
  34507. this._loadingTextDiv.style.color = "white";
  34508. this._loadingTextDiv.style.textAlign = "center";
  34509. this._loadingTextDiv.innerHTML = "Loading";
  34510. this._loadingDiv.appendChild(this._loadingTextDiv);
  34511. //set the predefined text
  34512. this._loadingTextDiv.innerHTML = this._loadingText;
  34513. // Loading img
  34514. var imgBack = new Image();
  34515. 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==";
  34516. imgBack.style.position = "absolute";
  34517. imgBack.style.left = "50%";
  34518. imgBack.style.top = "50%";
  34519. imgBack.style.marginLeft = "-50px";
  34520. imgBack.style.marginTop = "-50px";
  34521. imgBack.style.transition = "transform 1.0s ease";
  34522. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  34523. var deg = 360;
  34524. var onTransitionEnd = function () {
  34525. deg += 360;
  34526. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  34527. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  34528. };
  34529. imgBack.addEventListener("transitionend", onTransitionEnd);
  34530. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  34531. this._loadingDiv.appendChild(imgBack);
  34532. // front image
  34533. var imgFront = new Image();
  34534. 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=";
  34535. imgFront.style.position = "absolute";
  34536. imgFront.style.left = "50%";
  34537. imgFront.style.top = "50%";
  34538. imgFront.style.marginLeft = "-50px";
  34539. imgFront.style.marginTop = "-50px";
  34540. this._loadingDiv.appendChild(imgFront);
  34541. this._resizeLoadingUI();
  34542. window.addEventListener("resize", this._resizeLoadingUI);
  34543. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34544. document.body.appendChild(this._loadingDiv);
  34545. setTimeout(function () {
  34546. _this._loadingDiv.style.opacity = "1";
  34547. imgBack.style.transform = "rotateZ(360deg)";
  34548. imgBack.style.webkitTransform = "rotateZ(360deg)";
  34549. }, 0);
  34550. };
  34551. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  34552. var _this = this;
  34553. if (!this._loadingDiv) {
  34554. return;
  34555. }
  34556. var onTransitionEnd = function () {
  34557. if (!_this._loadingDiv) {
  34558. return;
  34559. }
  34560. document.body.removeChild(_this._loadingDiv);
  34561. window.removeEventListener("resize", _this._resizeLoadingUI);
  34562. _this._loadingDiv = null;
  34563. };
  34564. this._loadingDiv.style.opacity = "0";
  34565. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  34566. };
  34567. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  34568. set: function (text) {
  34569. this._loadingText = text;
  34570. if (this._loadingTextDiv) {
  34571. this._loadingTextDiv.innerHTML = this._loadingText;
  34572. }
  34573. },
  34574. enumerable: true,
  34575. configurable: true
  34576. });
  34577. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  34578. get: function () {
  34579. return this._loadingDivBackgroundColor;
  34580. },
  34581. set: function (color) {
  34582. this._loadingDivBackgroundColor = color;
  34583. if (!this._loadingDiv) {
  34584. return;
  34585. }
  34586. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34587. },
  34588. enumerable: true,
  34589. configurable: true
  34590. });
  34591. return DefaultLoadingScreen;
  34592. })();
  34593. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  34594. })(BABYLON || (BABYLON = {}));
  34595. var BABYLON;
  34596. (function (BABYLON) {
  34597. var maxSimultaneousLights = 4;
  34598. var PBRMaterialDefines = (function () {
  34599. function PBRMaterialDefines() {
  34600. this.ALBEDO = false;
  34601. this.CLIPPLANE = false;
  34602. this.ALPHATEST = false;
  34603. this.FOG = false;
  34604. this.NORMAL = false;
  34605. this.UV1 = false;
  34606. this.UV2 = false;
  34607. this.VERTEXCOLOR = false;
  34608. this.VERTEXALPHA = false;
  34609. this.BONES = false;
  34610. this.BONES4 = false;
  34611. this.BonesPerMesh = 0;
  34612. this.INSTANCES = false;
  34613. this.POINTSIZE = false;
  34614. this._keys = Object.keys(this);
  34615. }
  34616. PBRMaterialDefines.prototype.isEqual = function (other) {
  34617. for (var index = 0; index < this._keys.length; index++) {
  34618. var prop = this._keys[index];
  34619. if (this[prop] !== other[prop]) {
  34620. return false;
  34621. }
  34622. }
  34623. return true;
  34624. };
  34625. PBRMaterialDefines.prototype.cloneTo = function (other) {
  34626. for (var index = 0; index < this._keys.length; index++) {
  34627. var prop = this._keys[index];
  34628. other[prop] = this[prop];
  34629. }
  34630. };
  34631. PBRMaterialDefines.prototype.reset = function () {
  34632. for (var index = 0; index < this._keys.length; index++) {
  34633. var prop = this._keys[index];
  34634. if (prop === "BonesPerMesh") {
  34635. this[prop] = 0;
  34636. continue;
  34637. }
  34638. this[prop] = false;
  34639. }
  34640. };
  34641. PBRMaterialDefines.prototype.toString = function () {
  34642. var result = "";
  34643. for (var index = 0; index < this._keys.length; index++) {
  34644. var prop = this._keys[index];
  34645. if (prop === "BonesPerMesh" && this[prop] > 0) {
  34646. result += "#define BonesPerMesh " + this[prop] + "\n";
  34647. continue;
  34648. }
  34649. if (this[prop]) {
  34650. result += "#define " + prop + "\n";
  34651. }
  34652. }
  34653. return result;
  34654. };
  34655. return PBRMaterialDefines;
  34656. })();
  34657. var PBRMaterial = (function (_super) {
  34658. __extends(PBRMaterial, _super);
  34659. function PBRMaterial(name, scene) {
  34660. _super.call(this, name, scene);
  34661. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  34662. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34663. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34664. this._scaledDiffuse = new BABYLON.Color3();
  34665. this._scaledSpecular = new BABYLON.Color3();
  34666. this._defines = new PBRMaterialDefines();
  34667. this._cachedDefines = new PBRMaterialDefines();
  34668. this._cachedDefines.BonesPerMesh = -1;
  34669. }
  34670. PBRMaterial.prototype.needAlphaBlending = function () {
  34671. return this.alpha < 1.0;
  34672. };
  34673. PBRMaterial.prototype.needAlphaTesting = function () {
  34674. return false;
  34675. };
  34676. PBRMaterial.prototype.getAlphaTestTexture = function () {
  34677. return null;
  34678. };
  34679. // Methods
  34680. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  34681. if (this.checkReadyOnlyOnce) {
  34682. if (this._wasPreviouslyReady) {
  34683. return true;
  34684. }
  34685. }
  34686. var scene = this.getScene();
  34687. if (!this.checkReadyOnEveryCall) {
  34688. if (this._renderId === scene.getRenderId()) {
  34689. return true;
  34690. }
  34691. }
  34692. var engine = scene.getEngine();
  34693. var needNormals = false;
  34694. var needUVs = false;
  34695. this._defines.reset();
  34696. // Textures
  34697. if (scene.texturesEnabled) {
  34698. }
  34699. // Effect
  34700. if (scene.clipPlane) {
  34701. this._defines.CLIPPLANE = true;
  34702. }
  34703. if (engine.getAlphaTesting()) {
  34704. this._defines.ALPHATEST = true;
  34705. }
  34706. // Point size
  34707. if (this.pointsCloud || scene.forcePointsCloud) {
  34708. this._defines.POINTSIZE = true;
  34709. }
  34710. // Fog
  34711. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34712. this._defines.FOG = true;
  34713. }
  34714. // Lights
  34715. // Attribs
  34716. if (mesh) {
  34717. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34718. this._defines.NORMAL = true;
  34719. }
  34720. if (needUVs) {
  34721. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34722. this._defines.UV1 = true;
  34723. }
  34724. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34725. this._defines.UV2 = true;
  34726. }
  34727. }
  34728. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34729. this._defines.VERTEXCOLOR = true;
  34730. if (mesh.hasVertexAlpha) {
  34731. this._defines.VERTEXALPHA = true;
  34732. }
  34733. }
  34734. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34735. this._defines.BONES = true;
  34736. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  34737. this._defines.BONES4 = true;
  34738. }
  34739. // Instances
  34740. if (useInstances) {
  34741. this._defines.INSTANCES = true;
  34742. }
  34743. }
  34744. // Get correct effect
  34745. if (!this._defines.isEqual(this._cachedDefines)) {
  34746. this._defines.cloneTo(this._cachedDefines);
  34747. scene.resetCachedMaterial();
  34748. // Fallbacks
  34749. var fallbacks = new BABYLON.EffectFallbacks();
  34750. if (this._defines.FOG) {
  34751. fallbacks.addFallback(1, "FOG");
  34752. }
  34753. if (this._defines.BONES4) {
  34754. fallbacks.addFallback(0, "BONES4");
  34755. }
  34756. //Attributes
  34757. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34758. if (this._defines.NORMAL) {
  34759. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34760. }
  34761. if (this._defines.UV1) {
  34762. attribs.push(BABYLON.VertexBuffer.UVKind);
  34763. }
  34764. if (this._defines.UV2) {
  34765. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34766. }
  34767. if (this._defines.VERTEXCOLOR) {
  34768. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34769. }
  34770. if (this._defines.BONES) {
  34771. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34772. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34773. }
  34774. if (this._defines.INSTANCES) {
  34775. attribs.push("world0");
  34776. attribs.push("world1");
  34777. attribs.push("world2");
  34778. attribs.push("world3");
  34779. }
  34780. // Legacy browser patch
  34781. var join = this._defines.toString();
  34782. this._effect = scene.getEngine().createEffect("pbr", attribs, ["world", "view", "viewProjection", "vEyePosition", "vAlbedoColor",
  34783. "vFogInfos", "vFogColor", "pointSize",
  34784. "mBones",
  34785. "vClipPlane",
  34786. ], [], join, fallbacks, this.onCompiled, this.onError);
  34787. }
  34788. if (!this._effect.isReady()) {
  34789. return false;
  34790. }
  34791. this._renderId = scene.getRenderId();
  34792. this._wasPreviouslyReady = true;
  34793. return true;
  34794. };
  34795. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34796. this._effect.setMatrix("world", world);
  34797. };
  34798. PBRMaterial.prototype.bind = function (world, mesh) {
  34799. var scene = this.getScene();
  34800. // Matrices
  34801. this.bindOnlyWorldMatrix(world);
  34802. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34803. // Bones
  34804. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34805. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34806. }
  34807. if (scene.getCachedMaterial() !== this) {
  34808. // Clip plane
  34809. if (scene.clipPlane) {
  34810. var clipPlane = scene.clipPlane;
  34811. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34812. }
  34813. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  34814. }
  34815. // Point size
  34816. if (this.pointsCloud) {
  34817. this._effect.setFloat("pointSize", this.pointSize);
  34818. }
  34819. // Colors
  34820. this._effect.setColor4("vAlbedoColor", this.albedoColor, this.alpha * mesh.visibility);
  34821. // View
  34822. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34823. this._effect.setMatrix("view", scene.getViewMatrix());
  34824. }
  34825. // Fog
  34826. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34827. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34828. this._effect.setColor3("vFogColor", scene.fogColor);
  34829. }
  34830. _super.prototype.bind.call(this, world, mesh);
  34831. };
  34832. PBRMaterial.prototype.getAnimatables = function () {
  34833. var results = [];
  34834. return results;
  34835. };
  34836. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  34837. _super.prototype.dispose.call(this, forceDisposeEffect);
  34838. };
  34839. PBRMaterial.prototype.clone = function (name) {
  34840. var newPBRMaterial = new PBRMaterial(name, this.getScene());
  34841. // Base material
  34842. this.copyTo(newPBRMaterial);
  34843. // PBRMaterial material
  34844. newPBRMaterial.albedoColor = this.albedoColor.clone();
  34845. return newPBRMaterial;
  34846. };
  34847. return PBRMaterial;
  34848. })(BABYLON.Material);
  34849. BABYLON.PBRMaterial = PBRMaterial;
  34850. })(BABYLON || (BABYLON = {}));
  34851. var BABYLON;
  34852. (function (BABYLON) {
  34853. var ReflectionProbe = (function () {
  34854. //http://localhost:61437/Playground/index%20-%20debug.html#KA93U#7
  34855. function ReflectionProbe(name, size, scene, generateMipMaps) {
  34856. var _this = this;
  34857. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34858. this.name = name;
  34859. this._viewMatrix = BABYLON.Matrix.Identity();
  34860. this._target = BABYLON.Vector3.Zero();
  34861. this._add = BABYLON.Vector3.Zero();
  34862. this.position = BABYLON.Vector3.Zero();
  34863. this._scene = scene;
  34864. this._scene.reflectionProbes.push(this);
  34865. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  34866. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  34867. switch (faceIndex) {
  34868. case 0:
  34869. _this._add.copyFromFloats(1, 0, 0);
  34870. break;
  34871. case 1:
  34872. _this._add.copyFromFloats(-1, 0, 0);
  34873. break;
  34874. case 2:
  34875. _this._add.copyFromFloats(0, -1, 0);
  34876. break;
  34877. case 3:
  34878. _this._add.copyFromFloats(0, 1, 0);
  34879. break;
  34880. case 4:
  34881. _this._add.copyFromFloats(0, 0, 1);
  34882. break;
  34883. case 5:
  34884. _this._add.copyFromFloats(0, 0, -1);
  34885. break;
  34886. }
  34887. if (_this._attachedMesh) {
  34888. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  34889. }
  34890. _this.position.addToRef(_this._add, _this._target);
  34891. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  34892. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  34893. };
  34894. this._renderTargetTexture.onAfterUnbind = function () {
  34895. scene.updateTransformMatrix(true);
  34896. };
  34897. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  34898. }
  34899. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  34900. get: function () {
  34901. return this._renderTargetTexture.refreshRate;
  34902. },
  34903. set: function (value) {
  34904. this._renderTargetTexture.refreshRate = value;
  34905. },
  34906. enumerable: true,
  34907. configurable: true
  34908. });
  34909. ReflectionProbe.prototype.getScene = function () {
  34910. return this._scene;
  34911. };
  34912. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  34913. get: function () {
  34914. return this._renderTargetTexture;
  34915. },
  34916. enumerable: true,
  34917. configurable: true
  34918. });
  34919. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  34920. get: function () {
  34921. return this._renderTargetTexture.renderList;
  34922. },
  34923. enumerable: true,
  34924. configurable: true
  34925. });
  34926. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  34927. this._attachedMesh = mesh;
  34928. };
  34929. ReflectionProbe.prototype.dispose = function () {
  34930. var index = this._scene.reflectionProbes.indexOf(this);
  34931. if (index !== -1) {
  34932. // Remove from the scene if found
  34933. this._scene.reflectionProbes.splice(index, 1);
  34934. }
  34935. };
  34936. return ReflectionProbe;
  34937. })();
  34938. BABYLON.ReflectionProbe = ReflectionProbe;
  34939. })(BABYLON || (BABYLON = {}));
  34940. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n\t#ifdef SPECULAR\r\n\t\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\t\tspecularColor = specularMapColor.rgb;\r\n\t\t#ifdef GLOSSINESS\r\n\t\t\tglossiness = glossiness * specularMapColor.a;\r\n\t\t#endif\r\n\t#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\t#ifdef REFLECTIONMAP_3D\r\n\t\t\tfloat bias = 0.;\r\n\r\n\t\t#ifdef ROUGHNESS\r\n\t\t\t\tbias = vReflectionInfos.y;\r\n\t\t#endif\r\n\r\n\t\t#ifdef SPECULARTERM\r\n\t\t\t#ifdef SPECULAR\r\n\t\t\t\t#ifdef GLOSSINESS\r\n\t\t\t\t\t\tbias *= (1.0 - specularMapColor.a);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\r\n\t\t#endif\r\n\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x * shadow;\r\n\t#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\t#ifdef REFLECTIONMAP_PROJECTION\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x * shadow;\r\n#endif\t\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n vec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\tfloat lightmapIllum = clamp(dot(lightmapColor, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n\r\n\tif (lightmapIllum > vLightmapInfos.z)\r\n\t{\r\n\t\tcolor.rgb += lightmapColor;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcolor.rgb *= lightmapColor;\r\n\t}\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","pbrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec4 vAlbedoColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec3 baseColor = vAlbedoColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vAlbedoColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n\t// Composition\r\n vec4 color = vec4(clamp(baseColor, 0.0, 1.0), alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","pbrVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  34941. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,o){return this.r===t&&this.g===i&&this.b===o},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||7!==o.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16);return i.FromInts(n,r,s)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2])},i.FromInts=function(t,o,n){return new i(t/255,o/255,n/255)},i.Lerp=function(t,o,n){var r=t.r+(o.r-t.r)*n,s=t.g+(o.g-t.g)*n,e=t.b+(o.b-t.b)*n;return new i(r,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var o=function(){function i(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0,r=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||9!==o.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16),e=parseInt(o.substring(7,9),16);return i.FromInts(n,r,s,e)},i.Lerp=function(t,o,n){var r=new i(0,0,0,0);return i.LerpToRef(t,o,n,r),r},i.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromInts=function(t,o,n,r){return new i(t/255,o/255,n/255,r/255)},i}();t.Color4=o;var n=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a);return new i(h,u)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},i}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromFloatArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),l=SIMD.float32x4.load(n.m,8),m=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),l=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(n).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert();var u=new i(o.x/n*2-1,-(o.y/r*2-1),o.z),l=i.TransformCoordinates(u,h),m=u.x*h.m[3]+u.y*h.m[7]+u.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(m,1)&&(l=l.scale(1/m)),l},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(t,o,n){var r=i.Zero();return i.RotationFromAxisToRef(t,o,n,r),r},i.RotationFromAxisToRef=function(o,n,r,s){var e,a,h,u=i.Normalize(o),l=i.Normalize(r),m=f.X,x=f.Y,y=0,c=0,p=0,z=0,M=0,w=0,d=0,I=-1,D=0,S=0;t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?w=1:t.Tools.WithinEpsilon(l.x,0,t.Engine.Epsilon)?z=1:(d=l.z/l.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),a=new i(z,M,w),a.normalize(),h=i.Cross(l,a),h.normalize(),e=i.Cross(u,a),e.normalize(),i.Dot(l,e)<0&&(I=1),S=i.Dot(u,a),S=Math.min(1,Math.max(-1,S)),p=Math.acos(S)*I,i.Dot(a,m)<0&&(p=Math.PI+p,a=a.scaleInPlace(-1),h=h.scaleInPlace(-1),D++);var v,g;z=0,M=0,w=0,I=-1,t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?z=1:(d=a.z/a.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),v=new i(z,M,w),v.normalize(),g=i.Cross(v,a),g.normalize(),e=i.Cross(l,v),e.normalize(),i.Dot(a,e)<0&&(I=1),S=i.Dot(l,v),S=Math.min(1,Math.max(-1,S)),c=Math.acos(S)*I,i.Dot(g,x)<0&&(c=Math.PI+c,g=g.scaleInPlace(-1),v=v.scaleInPlace(-1),D++),I=-1,e=i.Cross(m,a),e.normalize(),i.Dot(e,x)<0&&(I=1),S=i.Dot(a,m),S=Math.min(1,Math.max(-1,S)),y=-Math.acos(S)*I,0>S&&2>D&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)&&t.Tools.WithinEpsilon(this.w,i.w,o)},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,r=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,n,r,s),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,l=o*n,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],l=n[2],m=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return i.normalize(),n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var o=new i;return this.addToRef(t,o),o},i.prototype.addToRef=function(t,i){for(var o=0;16>o;o++)i.m[o]=this.m[o]+t.m[o];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,d=u*p-f*x,I=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,F=e*c-a*y,A=s*p-h*x,P=s*c-a*x,C=s*y-e*x,E=a*f-h*m,L=e*f-h*l,q=e*m-a*l,Z=s*f-h*u,H=s*m-a*u,W=s*l-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*F)*R,t.m[6]=-(i*_-n*A+r*P)*R,t.m[10]=(i*b-o*A+r*C)*R,t.m[14]=-(i*F-o*P+n*C)*R,t.m[3]=-(o*E-n*L+r*q)*R,t.m[7]=(i*E-n*Z+r*H)*R,t.m[11]=-(i*L-o*Z+r*W)*R,t.m[15]=(i*q-o*H+n*W)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],F=t.m[11],A=t.m[12],P=t.m[13],C=t.m[14],E=t.m[15];return i[o]=n*w+r*S+s*R+e*A,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*F+e*E,i[o+4]=a*w+h*S+u*R+l*A,i[o+5]=a*d+h*v+u*_+l*P,i[o+6]=a*I+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*F+l*E,i[o+8]=m*w+f*S+x*R+y*A,i[o+9]=m*d+f*v+x*_+y*P,i[o+10]=m*I+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*F+y*E,i[o+12]=c*w+p*S+z*R+M*A,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*F+M*E,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));\n\nvar l=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.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])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromFloat32ArrayToRefScaled=function(t,i,o,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]*o},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=i.Zero();return i.RotationAxisToRef(t,o,n),n},i.RotationAxisToRef=function(t,i,o){var n=Math.sin(-i),r=Math.cos(-i),s=1-r;t.normalize(),o.m[0]=t.x*t.x*s+r,o.m[1]=t.x*t.y*s-t.z*n,o.m[2]=t.x*t.z*s+t.y*n,o.m[3]=0,o.m[4]=t.y*t.x*s+t.z*n,o.m[5]=t.y*t.y*s+r,o.m[6]=t.y*t.z*s-t.x*n,o.m[7]=0,o.m[8]=t.z*t.x*s-t.y*n,o.m[9]=t.z*t.y*s+t.x*n,o.m[10]=t.z*t.z*s+r,o.m[11]=0,o.m[15]=1},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.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,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(l,m,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(n).multiply(r).multiply(m)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],l=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],m=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,l=s*u-e*h,m=e*a-r*u,f=r*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return n=0!==x?1/x:0,this.normal.x=l*n,this.normal.y=m*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=l;var m=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o,n,r,s,e=0,a=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(o=1/this.direction.x,n=(t.x-this.origin.x)*o,r=(i.x-this.origin.x)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(o=1/this.direction.y,n=(t.y-this.origin.y)*o,r=(i.y-this.origin.y)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(o=1/this.direction.z,n=(t.z-this.origin.z)*o,r=(i.z-this.origin.z)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),l=r.Unproject(new r(t,o,1),n,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=m,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=t.Orientation,c=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),f+=m}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),l=u.length()+r;if(o>=r&&l>=o){var m=u.normalize(),f=o-r;return new n(a.x+m.x*f,a.y+m.y*f)}r=l}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=function(){function i(t,i,o){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=o||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),a=this._tangents[u],h=this._binormals[u-1],this._normals[u]=r.Cross(h,a),this._raw||this._normals[u].normalize(),this._binormals[u]=r.Cross(a,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0===o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},i.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0===o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},i.prototype._normalVector=function(i,o,n){var s;if(void 0===n||null===n){var e;t.Tools.WithinEpsilon(o.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.z,1,t.Engine.Epsilon)||(e=new r(0,0,1)):e=new r(1,0,0):e=new r(0,-1,0),s=r.Cross(o,e)}else s=r.Cross(o,n),r.CrossToRef(s,o,s);return s.normalize(),s},i}();t.Path3D=w;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,i.x,o.x,n.x),a(h/s,i.y,o.y,n.y),a(h/s,i.z,o.z,n.z)));return new t(e)},t.CreateCubicBezier=function(i,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,i.x,o.x,n.x,s.x),h(u/e,i.y,o.y,n.y,s.y),h(u/e,i.z,o.z,n.z,s.z)));return new t(a)},t.CreateHermiteSpline=function(i,o,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(r.Hermite(i,o,n,s,u*h));return new t(a)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=i.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new t(n);return e},t.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},t}();t.Curve3=d;var I=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=I;var D=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function t(){}return Object.defineProperty(t,\"IsEnabled\",{get:function(){return t._isEnabled},enumerable:!0,configurable:!0}),t.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,t._isEnabled=!1},t.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(r.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(r.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(r.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),t._isEnabled=!0)},t._isEnabled=!1,t}();t.SIMDHelper=_}(BABYLON||(BABYLON={}));";
  34942. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  34943. module.exports = BABYLON;
  34944. };