babylon.max.js 1.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265
  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. result.w = Math.cos(angle / 2);
  1409. result.x = axis.x * sin;
  1410. result.y = axis.y * sin;
  1411. result.z = axis.z * sin;
  1412. return result;
  1413. };
  1414. Quaternion.FromArray = function (array, offset) {
  1415. if (!offset) {
  1416. offset = 0;
  1417. }
  1418. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1419. };
  1420. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1421. var result = new Quaternion();
  1422. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1423. return result;
  1424. };
  1425. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1426. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1427. var halfRoll = roll * 0.5;
  1428. var halfPitch = pitch * 0.5;
  1429. var halfYaw = yaw * 0.5;
  1430. var sinRoll = Math.sin(halfRoll);
  1431. var cosRoll = Math.cos(halfRoll);
  1432. var sinPitch = Math.sin(halfPitch);
  1433. var cosPitch = Math.cos(halfPitch);
  1434. var sinYaw = Math.sin(halfYaw);
  1435. var cosYaw = Math.cos(halfYaw);
  1436. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1437. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1438. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1439. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1440. };
  1441. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1442. var result = new Quaternion();
  1443. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1444. return result;
  1445. };
  1446. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1447. // Produces a quaternion from Euler angles in the z-x-z orientation
  1448. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1449. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1450. var halfBeta = beta * 0.5;
  1451. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1452. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1453. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1454. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1455. };
  1456. Quaternion.Slerp = function (left, right, amount) {
  1457. var num2;
  1458. var num3;
  1459. var num = amount;
  1460. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1461. var flag = false;
  1462. if (num4 < 0) {
  1463. flag = true;
  1464. num4 = -num4;
  1465. }
  1466. if (num4 > 0.999999) {
  1467. num3 = 1 - num;
  1468. num2 = flag ? -num : num;
  1469. }
  1470. else {
  1471. var num5 = Math.acos(num4);
  1472. var num6 = (1.0 / Math.sin(num5));
  1473. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1474. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1475. }
  1476. 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));
  1477. };
  1478. return Quaternion;
  1479. })();
  1480. BABYLON.Quaternion = Quaternion;
  1481. var Matrix = (function () {
  1482. function Matrix() {
  1483. this.m = new Float32Array(16);
  1484. }
  1485. // Properties
  1486. Matrix.prototype.isIdentity = function () {
  1487. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1488. return false;
  1489. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1490. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1491. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1492. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1493. return false;
  1494. return true;
  1495. };
  1496. Matrix.prototype.determinant = function () {
  1497. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1498. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1499. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1500. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1501. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1502. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1503. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1504. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1505. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1506. };
  1507. // Methods
  1508. Matrix.prototype.toArray = function () {
  1509. return this.m;
  1510. };
  1511. Matrix.prototype.asArray = function () {
  1512. return this.toArray();
  1513. };
  1514. Matrix.prototype.invert = function () {
  1515. this.invertToRef(this);
  1516. return this;
  1517. };
  1518. Matrix.prototype.reset = function () {
  1519. for (var index = 0; index < 16; index++) {
  1520. this.m[index] = 0;
  1521. }
  1522. return this;
  1523. };
  1524. Matrix.prototype.add = function (other) {
  1525. var result = new Matrix();
  1526. this.addToRef(other, result);
  1527. return result;
  1528. };
  1529. Matrix.prototype.addToRef = function (other, result) {
  1530. for (var index = 0; index < 16; index++) {
  1531. result.m[index] = this.m[index] + other.m[index];
  1532. }
  1533. return this;
  1534. };
  1535. Matrix.prototype.addToSelf = function (other) {
  1536. for (var index = 0; index < 16; index++) {
  1537. this.m[index] += other.m[index];
  1538. }
  1539. return this;
  1540. };
  1541. Matrix.prototype.invertToRef = function (other) {
  1542. var l1 = this.m[0];
  1543. var l2 = this.m[1];
  1544. var l3 = this.m[2];
  1545. var l4 = this.m[3];
  1546. var l5 = this.m[4];
  1547. var l6 = this.m[5];
  1548. var l7 = this.m[6];
  1549. var l8 = this.m[7];
  1550. var l9 = this.m[8];
  1551. var l10 = this.m[9];
  1552. var l11 = this.m[10];
  1553. var l12 = this.m[11];
  1554. var l13 = this.m[12];
  1555. var l14 = this.m[13];
  1556. var l15 = this.m[14];
  1557. var l16 = this.m[15];
  1558. var l17 = (l11 * l16) - (l12 * l15);
  1559. var l18 = (l10 * l16) - (l12 * l14);
  1560. var l19 = (l10 * l15) - (l11 * l14);
  1561. var l20 = (l9 * l16) - (l12 * l13);
  1562. var l21 = (l9 * l15) - (l11 * l13);
  1563. var l22 = (l9 * l14) - (l10 * l13);
  1564. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1565. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1566. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1567. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1568. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1569. var l28 = (l7 * l16) - (l8 * l15);
  1570. var l29 = (l6 * l16) - (l8 * l14);
  1571. var l30 = (l6 * l15) - (l7 * l14);
  1572. var l31 = (l5 * l16) - (l8 * l13);
  1573. var l32 = (l5 * l15) - (l7 * l13);
  1574. var l33 = (l5 * l14) - (l6 * l13);
  1575. var l34 = (l7 * l12) - (l8 * l11);
  1576. var l35 = (l6 * l12) - (l8 * l10);
  1577. var l36 = (l6 * l11) - (l7 * l10);
  1578. var l37 = (l5 * l12) - (l8 * l9);
  1579. var l38 = (l5 * l11) - (l7 * l9);
  1580. var l39 = (l5 * l10) - (l6 * l9);
  1581. other.m[0] = l23 * l27;
  1582. other.m[4] = l24 * l27;
  1583. other.m[8] = l25 * l27;
  1584. other.m[12] = l26 * l27;
  1585. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1586. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1587. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1588. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1589. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1590. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1591. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1592. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1593. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1594. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1595. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1596. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1597. return this;
  1598. };
  1599. Matrix.prototype.invertToRefSIMD = function (other) {
  1600. var src = this.m;
  1601. var dest = other.m;
  1602. var row0, row1, row2, row3;
  1603. var tmp1;
  1604. var minor0, minor1, minor2, minor3;
  1605. var det;
  1606. // Load the 4 rows
  1607. var src0 = SIMD.float32x4.load(src, 0);
  1608. var src1 = SIMD.float32x4.load(src, 4);
  1609. var src2 = SIMD.float32x4.load(src, 8);
  1610. var src3 = SIMD.float32x4.load(src, 12);
  1611. // Transpose the source matrix. Sort of. Not a true transpose operation
  1612. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1613. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1614. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1615. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1616. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1617. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1618. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1619. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1620. // This is a true transposition, but it will lead to an incorrect result
  1621. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1622. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1623. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1624. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1625. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1626. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1627. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1628. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1629. // ----
  1630. tmp1 = SIMD.float32x4.mul(row2, row3);
  1631. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1632. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1633. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1634. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1635. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1636. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1637. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1638. // ----
  1639. tmp1 = SIMD.float32x4.mul(row1, row2);
  1640. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1641. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1642. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1643. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1644. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1645. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1646. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1647. // ----
  1648. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1649. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1650. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1651. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1652. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1653. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1654. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1655. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1656. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1657. // ----
  1658. tmp1 = SIMD.float32x4.mul(row0, row1);
  1659. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1660. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1661. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1662. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1663. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1664. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1665. // ----
  1666. tmp1 = SIMD.float32x4.mul(row0, row3);
  1667. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1668. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1669. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1670. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1671. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1672. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1673. // ----
  1674. tmp1 = SIMD.float32x4.mul(row0, row2);
  1675. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1676. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1677. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1678. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1679. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1680. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1681. // Compute determinant
  1682. det = SIMD.float32x4.mul(row0, minor0);
  1683. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1684. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1685. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1686. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1687. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1688. // These shuffles aren't necessary if the faulty transposition is done
  1689. // up at the top of this function.
  1690. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1691. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1692. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1693. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1694. // Compute final values by multiplying with 1/det
  1695. minor0 = SIMD.float32x4.mul(det, minor0);
  1696. minor1 = SIMD.float32x4.mul(det, minor1);
  1697. minor2 = SIMD.float32x4.mul(det, minor2);
  1698. minor3 = SIMD.float32x4.mul(det, minor3);
  1699. SIMD.float32x4.store(dest, 0, minor0);
  1700. SIMD.float32x4.store(dest, 4, minor1);
  1701. SIMD.float32x4.store(dest, 8, minor2);
  1702. SIMD.float32x4.store(dest, 12, minor3);
  1703. return this;
  1704. };
  1705. Matrix.prototype.setTranslation = function (vector3) {
  1706. this.m[12] = vector3.x;
  1707. this.m[13] = vector3.y;
  1708. this.m[14] = vector3.z;
  1709. return this;
  1710. };
  1711. Matrix.prototype.multiply = function (other) {
  1712. var result = new Matrix();
  1713. this.multiplyToRef(other, result);
  1714. return result;
  1715. };
  1716. Matrix.prototype.copyFrom = function (other) {
  1717. for (var index = 0; index < 16; index++) {
  1718. this.m[index] = other.m[index];
  1719. }
  1720. return this;
  1721. };
  1722. Matrix.prototype.copyToArray = function (array, offset) {
  1723. if (offset === void 0) { offset = 0; }
  1724. for (var index = 0; index < 16; index++) {
  1725. array[offset + index] = this.m[index];
  1726. }
  1727. return this;
  1728. };
  1729. Matrix.prototype.multiplyToRef = function (other, result) {
  1730. this.multiplyToArray(other, result.m, 0);
  1731. return this;
  1732. };
  1733. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1734. var tm0 = this.m[0];
  1735. var tm1 = this.m[1];
  1736. var tm2 = this.m[2];
  1737. var tm3 = this.m[3];
  1738. var tm4 = this.m[4];
  1739. var tm5 = this.m[5];
  1740. var tm6 = this.m[6];
  1741. var tm7 = this.m[7];
  1742. var tm8 = this.m[8];
  1743. var tm9 = this.m[9];
  1744. var tm10 = this.m[10];
  1745. var tm11 = this.m[11];
  1746. var tm12 = this.m[12];
  1747. var tm13 = this.m[13];
  1748. var tm14 = this.m[14];
  1749. var tm15 = this.m[15];
  1750. var om0 = other.m[0];
  1751. var om1 = other.m[1];
  1752. var om2 = other.m[2];
  1753. var om3 = other.m[3];
  1754. var om4 = other.m[4];
  1755. var om5 = other.m[5];
  1756. var om6 = other.m[6];
  1757. var om7 = other.m[7];
  1758. var om8 = other.m[8];
  1759. var om9 = other.m[9];
  1760. var om10 = other.m[10];
  1761. var om11 = other.m[11];
  1762. var om12 = other.m[12];
  1763. var om13 = other.m[13];
  1764. var om14 = other.m[14];
  1765. var om15 = other.m[15];
  1766. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1767. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1768. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1769. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1770. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1771. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1772. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1773. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1774. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1775. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1776. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1777. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1778. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1779. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1780. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1781. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1782. return this;
  1783. };
  1784. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1785. if (offset === void 0) { offset = 0; }
  1786. var tm = this.m;
  1787. var om = other.m;
  1788. var om0 = SIMD.float32x4.load(om, 0);
  1789. var om1 = SIMD.float32x4.load(om, 4);
  1790. var om2 = SIMD.float32x4.load(om, 8);
  1791. var om3 = SIMD.float32x4.load(om, 12);
  1792. var tm0 = SIMD.float32x4.load(tm, 0);
  1793. 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)))));
  1794. var tm1 = SIMD.float32x4.load(tm, 4);
  1795. 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)))));
  1796. var tm2 = SIMD.float32x4.load(tm, 8);
  1797. 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)))));
  1798. var tm3 = SIMD.float32x4.load(tm, 12);
  1799. 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)))));
  1800. };
  1801. Matrix.prototype.equals = function (value) {
  1802. return value &&
  1803. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1804. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1805. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1806. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1807. };
  1808. Matrix.prototype.clone = function () {
  1809. 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]);
  1810. };
  1811. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1812. translation.x = this.m[12];
  1813. translation.y = this.m[13];
  1814. translation.z = this.m[14];
  1815. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1816. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1817. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1818. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1819. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1820. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1821. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1822. rotation.x = 0;
  1823. rotation.y = 0;
  1824. rotation.z = 0;
  1825. rotation.w = 1;
  1826. return false;
  1827. }
  1828. 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);
  1829. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1830. return true;
  1831. };
  1832. // Statics
  1833. Matrix.FromArray = function (array, offset) {
  1834. var result = new Matrix();
  1835. if (!offset) {
  1836. offset = 0;
  1837. }
  1838. Matrix.FromArrayToRef(array, offset, result);
  1839. return result;
  1840. };
  1841. Matrix.FromArrayToRef = function (array, offset, result) {
  1842. for (var index = 0; index < 16; index++) {
  1843. result.m[index] = array[index + offset];
  1844. }
  1845. };
  1846. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1847. for (var index = 0; index < 16; index++) {
  1848. result.m[index] = array[index + offset] * scale;
  1849. }
  1850. };
  1851. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1852. result.m[0] = initialM11;
  1853. result.m[1] = initialM12;
  1854. result.m[2] = initialM13;
  1855. result.m[3] = initialM14;
  1856. result.m[4] = initialM21;
  1857. result.m[5] = initialM22;
  1858. result.m[6] = initialM23;
  1859. result.m[7] = initialM24;
  1860. result.m[8] = initialM31;
  1861. result.m[9] = initialM32;
  1862. result.m[10] = initialM33;
  1863. result.m[11] = initialM34;
  1864. result.m[12] = initialM41;
  1865. result.m[13] = initialM42;
  1866. result.m[14] = initialM43;
  1867. result.m[15] = initialM44;
  1868. };
  1869. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1870. var result = new Matrix();
  1871. result.m[0] = initialM11;
  1872. result.m[1] = initialM12;
  1873. result.m[2] = initialM13;
  1874. result.m[3] = initialM14;
  1875. result.m[4] = initialM21;
  1876. result.m[5] = initialM22;
  1877. result.m[6] = initialM23;
  1878. result.m[7] = initialM24;
  1879. result.m[8] = initialM31;
  1880. result.m[9] = initialM32;
  1881. result.m[10] = initialM33;
  1882. result.m[11] = initialM34;
  1883. result.m[12] = initialM41;
  1884. result.m[13] = initialM42;
  1885. result.m[14] = initialM43;
  1886. result.m[15] = initialM44;
  1887. return result;
  1888. };
  1889. Matrix.Compose = function (scale, rotation, translation) {
  1890. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1891. var rotationMatrix = Matrix.Identity();
  1892. rotation.toRotationMatrix(rotationMatrix);
  1893. result = result.multiply(rotationMatrix);
  1894. result.setTranslation(translation);
  1895. return result;
  1896. };
  1897. Matrix.Identity = function () {
  1898. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1899. };
  1900. Matrix.IdentityToRef = function (result) {
  1901. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1902. };
  1903. Matrix.Zero = function () {
  1904. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1905. };
  1906. Matrix.RotationX = function (angle) {
  1907. var result = new Matrix();
  1908. Matrix.RotationXToRef(angle, result);
  1909. return result;
  1910. };
  1911. Matrix.Invert = function (source) {
  1912. var result = new Matrix();
  1913. source.invertToRef(result);
  1914. return result;
  1915. };
  1916. Matrix.RotationXToRef = function (angle, result) {
  1917. var s = Math.sin(angle);
  1918. var c = Math.cos(angle);
  1919. result.m[0] = 1.0;
  1920. result.m[15] = 1.0;
  1921. result.m[5] = c;
  1922. result.m[10] = c;
  1923. result.m[9] = -s;
  1924. result.m[6] = s;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[7] = 0;
  1930. result.m[8] = 0;
  1931. result.m[11] = 0;
  1932. result.m[12] = 0;
  1933. result.m[13] = 0;
  1934. result.m[14] = 0;
  1935. };
  1936. Matrix.RotationY = function (angle) {
  1937. var result = new Matrix();
  1938. Matrix.RotationYToRef(angle, result);
  1939. return result;
  1940. };
  1941. Matrix.RotationYToRef = function (angle, result) {
  1942. var s = Math.sin(angle);
  1943. var c = Math.cos(angle);
  1944. result.m[5] = 1.0;
  1945. result.m[15] = 1.0;
  1946. result.m[0] = c;
  1947. result.m[2] = -s;
  1948. result.m[8] = s;
  1949. result.m[10] = c;
  1950. result.m[1] = 0;
  1951. result.m[3] = 0;
  1952. result.m[4] = 0;
  1953. result.m[6] = 0;
  1954. result.m[7] = 0;
  1955. result.m[9] = 0;
  1956. result.m[11] = 0;
  1957. result.m[12] = 0;
  1958. result.m[13] = 0;
  1959. result.m[14] = 0;
  1960. };
  1961. Matrix.RotationZ = function (angle) {
  1962. var result = new Matrix();
  1963. Matrix.RotationZToRef(angle, result);
  1964. return result;
  1965. };
  1966. Matrix.RotationZToRef = function (angle, result) {
  1967. var s = Math.sin(angle);
  1968. var c = Math.cos(angle);
  1969. result.m[10] = 1.0;
  1970. result.m[15] = 1.0;
  1971. result.m[0] = c;
  1972. result.m[1] = s;
  1973. result.m[4] = -s;
  1974. result.m[5] = c;
  1975. result.m[2] = 0;
  1976. result.m[3] = 0;
  1977. result.m[6] = 0;
  1978. result.m[7] = 0;
  1979. result.m[8] = 0;
  1980. result.m[9] = 0;
  1981. result.m[11] = 0;
  1982. result.m[12] = 0;
  1983. result.m[13] = 0;
  1984. result.m[14] = 0;
  1985. };
  1986. Matrix.RotationAxis = function (axis, angle) {
  1987. var s = Math.sin(-angle);
  1988. var c = Math.cos(-angle);
  1989. var c1 = 1 - c;
  1990. axis.normalize();
  1991. var result = Matrix.Zero();
  1992. result.m[0] = (axis.x * axis.x) * c1 + c;
  1993. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1994. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1995. result.m[3] = 0.0;
  1996. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1997. result.m[5] = (axis.y * axis.y) * c1 + c;
  1998. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1999. result.m[7] = 0.0;
  2000. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2001. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2002. result.m[10] = (axis.z * axis.z) * c1 + c;
  2003. result.m[11] = 0.0;
  2004. result.m[15] = 1.0;
  2005. return result;
  2006. };
  2007. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2008. var result = new Matrix();
  2009. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2010. return result;
  2011. };
  2012. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2013. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2014. this._tempQuaternion.toRotationMatrix(result);
  2015. };
  2016. Matrix.Scaling = function (x, y, z) {
  2017. var result = Matrix.Zero();
  2018. Matrix.ScalingToRef(x, y, z, result);
  2019. return result;
  2020. };
  2021. Matrix.ScalingToRef = function (x, y, z, result) {
  2022. result.m[0] = x;
  2023. result.m[1] = 0;
  2024. result.m[2] = 0;
  2025. result.m[3] = 0;
  2026. result.m[4] = 0;
  2027. result.m[5] = y;
  2028. result.m[6] = 0;
  2029. result.m[7] = 0;
  2030. result.m[8] = 0;
  2031. result.m[9] = 0;
  2032. result.m[10] = z;
  2033. result.m[11] = 0;
  2034. result.m[12] = 0;
  2035. result.m[13] = 0;
  2036. result.m[14] = 0;
  2037. result.m[15] = 1.0;
  2038. };
  2039. Matrix.Translation = function (x, y, z) {
  2040. var result = Matrix.Identity();
  2041. Matrix.TranslationToRef(x, y, z, result);
  2042. return result;
  2043. };
  2044. Matrix.TranslationToRef = function (x, y, z, result) {
  2045. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2046. };
  2047. Matrix.LookAtLH = function (eye, target, up) {
  2048. var result = Matrix.Zero();
  2049. Matrix.LookAtLHToRef(eye, target, up, result);
  2050. return result;
  2051. };
  2052. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2053. // Z axis
  2054. target.subtractToRef(eye, this._zAxis);
  2055. this._zAxis.normalize();
  2056. // X axis
  2057. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2058. this._xAxis.normalize();
  2059. // Y axis
  2060. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2061. this._yAxis.normalize();
  2062. // Eye angles
  2063. var ex = -Vector3.Dot(this._xAxis, eye);
  2064. var ey = -Vector3.Dot(this._yAxis, eye);
  2065. var ez = -Vector3.Dot(this._zAxis, eye);
  2066. 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);
  2067. };
  2068. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2069. var out = result.m;
  2070. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2071. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2072. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2073. // cc.kmVec3Subtract(f, pCenter, pEye);
  2074. var f = SIMD.float32x4.sub(center, eye);
  2075. // cc.kmVec3Normalize(f, f);
  2076. var tmp = SIMD.float32x4.mul(f, f);
  2077. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2078. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2079. // cc.kmVec3Assign(up, pUp);
  2080. // cc.kmVec3Normalize(up, up);
  2081. tmp = SIMD.float32x4.mul(up, up);
  2082. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2083. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2084. // cc.kmVec3Cross(s, f, up);
  2085. 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)));
  2086. // cc.kmVec3Normalize(s, s);
  2087. tmp = SIMD.float32x4.mul(s, s);
  2088. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2089. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2090. // cc.kmVec3Cross(u, s, f);
  2091. 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)));
  2092. // cc.kmVec3Normalize(s, s);
  2093. tmp = SIMD.float32x4.mul(s, s);
  2094. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2095. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2096. var zero = SIMD.float32x4.splat(0.0);
  2097. s = SIMD.float32x4.neg(s);
  2098. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2099. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2100. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2101. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2102. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2103. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2104. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2105. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2106. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2107. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2108. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2109. var b3 = SIMD.float32x4.neg(eye);
  2110. b3 = SIMD.float32x4.withW(b3, 1.0);
  2111. 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)))));
  2112. 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)))));
  2113. 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)))));
  2114. 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)))));
  2115. };
  2116. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2117. var matrix = Matrix.Zero();
  2118. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2119. return matrix;
  2120. };
  2121. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2122. var hw = 2.0 / width;
  2123. var hh = 2.0 / height;
  2124. var id = 1.0 / (zfar - znear);
  2125. var nid = znear / (znear - zfar);
  2126. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2127. };
  2128. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2129. var matrix = Matrix.Zero();
  2130. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2131. return matrix;
  2132. };
  2133. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2134. result.m[0] = 2.0 / (right - left);
  2135. result.m[1] = result.m[2] = result.m[3] = 0;
  2136. result.m[5] = 2.0 / (top - bottom);
  2137. result.m[4] = result.m[6] = result.m[7] = 0;
  2138. result.m[10] = -1.0 / (znear - zfar);
  2139. result.m[8] = result.m[9] = result.m[11] = 0;
  2140. result.m[12] = (left + right) / (left - right);
  2141. result.m[13] = (top + bottom) / (bottom - top);
  2142. result.m[14] = znear / (znear - zfar);
  2143. result.m[15] = 1.0;
  2144. };
  2145. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2146. var matrix = Matrix.Zero();
  2147. matrix.m[0] = (2.0 * znear) / width;
  2148. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2149. matrix.m[5] = (2.0 * znear) / height;
  2150. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2151. matrix.m[10] = -zfar / (znear - zfar);
  2152. matrix.m[8] = matrix.m[9] = 0.0;
  2153. matrix.m[11] = 1.0;
  2154. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2155. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2156. return matrix;
  2157. };
  2158. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2159. var matrix = Matrix.Zero();
  2160. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2161. return matrix;
  2162. };
  2163. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2164. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2165. var tan = 1.0 / (Math.tan(fov * 0.5));
  2166. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2167. if (v_fixed) {
  2168. result.m[0] = tan / aspect;
  2169. }
  2170. else {
  2171. result.m[0] = tan;
  2172. }
  2173. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2174. if (v_fixed) {
  2175. result.m[5] = tan;
  2176. }
  2177. else {
  2178. result.m[5] = tan * aspect;
  2179. }
  2180. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2181. result.m[8] = result.m[9] = 0.0;
  2182. result.m[10] = -zfar / (znear - zfar);
  2183. result.m[11] = 1.0;
  2184. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2185. result.m[14] = (znear * zfar) / (znear - zfar);
  2186. };
  2187. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2188. var cw = viewport.width;
  2189. var ch = viewport.height;
  2190. var cx = viewport.x;
  2191. var cy = viewport.y;
  2192. 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);
  2193. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2194. };
  2195. Matrix.GetAsMatrix2x2 = function (matrix) {
  2196. return new Float32Array([
  2197. matrix.m[0], matrix.m[1],
  2198. matrix.m[4], matrix.m[5]
  2199. ]);
  2200. };
  2201. Matrix.GetAsMatrix3x3 = function (matrix) {
  2202. return new Float32Array([
  2203. matrix.m[0], matrix.m[1], matrix.m[2],
  2204. matrix.m[4], matrix.m[5], matrix.m[6],
  2205. matrix.m[8], matrix.m[9], matrix.m[10]
  2206. ]);
  2207. };
  2208. Matrix.Transpose = function (matrix) {
  2209. var result = new Matrix();
  2210. result.m[0] = matrix.m[0];
  2211. result.m[1] = matrix.m[4];
  2212. result.m[2] = matrix.m[8];
  2213. result.m[3] = matrix.m[12];
  2214. result.m[4] = matrix.m[1];
  2215. result.m[5] = matrix.m[5];
  2216. result.m[6] = matrix.m[9];
  2217. result.m[7] = matrix.m[13];
  2218. result.m[8] = matrix.m[2];
  2219. result.m[9] = matrix.m[6];
  2220. result.m[10] = matrix.m[10];
  2221. result.m[11] = matrix.m[14];
  2222. result.m[12] = matrix.m[3];
  2223. result.m[13] = matrix.m[7];
  2224. result.m[14] = matrix.m[11];
  2225. result.m[15] = matrix.m[15];
  2226. return result;
  2227. };
  2228. Matrix.Reflection = function (plane) {
  2229. var matrix = new Matrix();
  2230. Matrix.ReflectionToRef(plane, matrix);
  2231. return matrix;
  2232. };
  2233. Matrix.ReflectionToRef = function (plane, result) {
  2234. plane.normalize();
  2235. var x = plane.normal.x;
  2236. var y = plane.normal.y;
  2237. var z = plane.normal.z;
  2238. var temp = -2 * x;
  2239. var temp2 = -2 * y;
  2240. var temp3 = -2 * z;
  2241. result.m[0] = (temp * x) + 1;
  2242. result.m[1] = temp2 * x;
  2243. result.m[2] = temp3 * x;
  2244. result.m[3] = 0.0;
  2245. result.m[4] = temp * y;
  2246. result.m[5] = (temp2 * y) + 1;
  2247. result.m[6] = temp3 * y;
  2248. result.m[7] = 0.0;
  2249. result.m[8] = temp * z;
  2250. result.m[9] = temp2 * z;
  2251. result.m[10] = (temp3 * z) + 1;
  2252. result.m[11] = 0.0;
  2253. result.m[12] = temp * plane.d;
  2254. result.m[13] = temp2 * plane.d;
  2255. result.m[14] = temp3 * plane.d;
  2256. result.m[15] = 1.0;
  2257. };
  2258. Matrix._tempQuaternion = new Quaternion();
  2259. Matrix._xAxis = Vector3.Zero();
  2260. Matrix._yAxis = Vector3.Zero();
  2261. Matrix._zAxis = Vector3.Zero();
  2262. return Matrix;
  2263. })();
  2264. BABYLON.Matrix = Matrix;
  2265. var Plane = (function () {
  2266. function Plane(a, b, c, d) {
  2267. this.normal = new Vector3(a, b, c);
  2268. this.d = d;
  2269. }
  2270. Plane.prototype.asArray = function () {
  2271. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2272. };
  2273. // Methods
  2274. Plane.prototype.clone = function () {
  2275. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2276. };
  2277. Plane.prototype.normalize = function () {
  2278. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2279. var magnitude = 0;
  2280. if (norm !== 0) {
  2281. magnitude = 1.0 / norm;
  2282. }
  2283. this.normal.x *= magnitude;
  2284. this.normal.y *= magnitude;
  2285. this.normal.z *= magnitude;
  2286. this.d *= magnitude;
  2287. return this;
  2288. };
  2289. Plane.prototype.transform = function (transformation) {
  2290. var transposedMatrix = Matrix.Transpose(transformation);
  2291. var x = this.normal.x;
  2292. var y = this.normal.y;
  2293. var z = this.normal.z;
  2294. var d = this.d;
  2295. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2296. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2297. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2298. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2299. return new Plane(normalX, normalY, normalZ, finalD);
  2300. };
  2301. Plane.prototype.dotCoordinate = function (point) {
  2302. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2303. };
  2304. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2305. var x1 = point2.x - point1.x;
  2306. var y1 = point2.y - point1.y;
  2307. var z1 = point2.z - point1.z;
  2308. var x2 = point3.x - point1.x;
  2309. var y2 = point3.y - point1.y;
  2310. var z2 = point3.z - point1.z;
  2311. var yz = (y1 * z2) - (z1 * y2);
  2312. var xz = (z1 * x2) - (x1 * z2);
  2313. var xy = (x1 * y2) - (y1 * x2);
  2314. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2315. var invPyth;
  2316. if (pyth !== 0) {
  2317. invPyth = 1.0 / pyth;
  2318. }
  2319. else {
  2320. invPyth = 0;
  2321. }
  2322. this.normal.x = yz * invPyth;
  2323. this.normal.y = xz * invPyth;
  2324. this.normal.z = xy * invPyth;
  2325. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2326. return this;
  2327. };
  2328. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2329. var dot = Vector3.Dot(this.normal, direction);
  2330. return (dot <= epsilon);
  2331. };
  2332. Plane.prototype.signedDistanceTo = function (point) {
  2333. return Vector3.Dot(point, this.normal) + this.d;
  2334. };
  2335. // Statics
  2336. Plane.FromArray = function (array) {
  2337. return new Plane(array[0], array[1], array[2], array[3]);
  2338. };
  2339. Plane.FromPoints = function (point1, point2, point3) {
  2340. var result = new Plane(0, 0, 0, 0);
  2341. result.copyFromPoints(point1, point2, point3);
  2342. return result;
  2343. };
  2344. Plane.FromPositionAndNormal = function (origin, normal) {
  2345. var result = new Plane(0, 0, 0, 0);
  2346. normal.normalize();
  2347. result.normal = normal;
  2348. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2349. return result;
  2350. };
  2351. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2352. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2353. return Vector3.Dot(point, normal) + d;
  2354. };
  2355. return Plane;
  2356. })();
  2357. BABYLON.Plane = Plane;
  2358. var Viewport = (function () {
  2359. function Viewport(x, y, width, height) {
  2360. this.x = x;
  2361. this.y = y;
  2362. this.width = width;
  2363. this.height = height;
  2364. }
  2365. Viewport.prototype.toGlobal = function (engine) {
  2366. var width = engine.getRenderWidth();
  2367. var height = engine.getRenderHeight();
  2368. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2369. };
  2370. return Viewport;
  2371. })();
  2372. BABYLON.Viewport = Viewport;
  2373. var Frustum = (function () {
  2374. function Frustum() {
  2375. }
  2376. Frustum.GetPlanes = function (transform) {
  2377. var frustumPlanes = [];
  2378. for (var index = 0; index < 6; index++) {
  2379. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2380. }
  2381. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2382. return frustumPlanes;
  2383. };
  2384. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2385. // Near
  2386. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2387. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2388. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2389. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2390. frustumPlanes[0].normalize();
  2391. // Far
  2392. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2393. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2394. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2395. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2396. frustumPlanes[1].normalize();
  2397. // Left
  2398. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2399. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2400. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2401. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2402. frustumPlanes[2].normalize();
  2403. // Right
  2404. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2405. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2406. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2407. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2408. frustumPlanes[3].normalize();
  2409. // Top
  2410. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2411. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2412. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2413. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2414. frustumPlanes[4].normalize();
  2415. // Bottom
  2416. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2417. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2418. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2419. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2420. frustumPlanes[5].normalize();
  2421. };
  2422. return Frustum;
  2423. })();
  2424. BABYLON.Frustum = Frustum;
  2425. var Ray = (function () {
  2426. function Ray(origin, direction, length) {
  2427. if (length === void 0) { length = Number.MAX_VALUE; }
  2428. this.origin = origin;
  2429. this.direction = direction;
  2430. this.length = length;
  2431. }
  2432. // Methods
  2433. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2434. var d = 0.0;
  2435. var maxValue = Number.MAX_VALUE;
  2436. var inv;
  2437. var min;
  2438. var max;
  2439. var temp;
  2440. if (Math.abs(this.direction.x) < 0.0000001) {
  2441. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2442. return false;
  2443. }
  2444. }
  2445. else {
  2446. inv = 1.0 / this.direction.x;
  2447. min = (minimum.x - this.origin.x) * inv;
  2448. max = (maximum.x - this.origin.x) * inv;
  2449. if (max === -Infinity) {
  2450. max = Infinity;
  2451. }
  2452. if (min > max) {
  2453. temp = min;
  2454. min = max;
  2455. max = temp;
  2456. }
  2457. d = Math.max(min, d);
  2458. maxValue = Math.min(max, maxValue);
  2459. if (d > maxValue) {
  2460. return false;
  2461. }
  2462. }
  2463. if (Math.abs(this.direction.y) < 0.0000001) {
  2464. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2465. return false;
  2466. }
  2467. }
  2468. else {
  2469. inv = 1.0 / this.direction.y;
  2470. min = (minimum.y - this.origin.y) * inv;
  2471. max = (maximum.y - this.origin.y) * inv;
  2472. if (max === -Infinity) {
  2473. max = Infinity;
  2474. }
  2475. if (min > max) {
  2476. temp = min;
  2477. min = max;
  2478. max = temp;
  2479. }
  2480. d = Math.max(min, d);
  2481. maxValue = Math.min(max, maxValue);
  2482. if (d > maxValue) {
  2483. return false;
  2484. }
  2485. }
  2486. if (Math.abs(this.direction.z) < 0.0000001) {
  2487. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2488. return false;
  2489. }
  2490. }
  2491. else {
  2492. inv = 1.0 / this.direction.z;
  2493. min = (minimum.z - this.origin.z) * inv;
  2494. max = (maximum.z - this.origin.z) * inv;
  2495. if (max === -Infinity) {
  2496. max = Infinity;
  2497. }
  2498. if (min > max) {
  2499. temp = min;
  2500. min = max;
  2501. max = temp;
  2502. }
  2503. d = Math.max(min, d);
  2504. maxValue = Math.min(max, maxValue);
  2505. if (d > maxValue) {
  2506. return false;
  2507. }
  2508. }
  2509. return true;
  2510. };
  2511. Ray.prototype.intersectsBox = function (box) {
  2512. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2513. };
  2514. Ray.prototype.intersectsSphere = function (sphere) {
  2515. var x = sphere.center.x - this.origin.x;
  2516. var y = sphere.center.y - this.origin.y;
  2517. var z = sphere.center.z - this.origin.z;
  2518. var pyth = (x * x) + (y * y) + (z * z);
  2519. var rr = sphere.radius * sphere.radius;
  2520. if (pyth <= rr) {
  2521. return true;
  2522. }
  2523. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2524. if (dot < 0.0) {
  2525. return false;
  2526. }
  2527. var temp = pyth - (dot * dot);
  2528. return temp <= rr;
  2529. };
  2530. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2531. if (!this._edge1) {
  2532. this._edge1 = Vector3.Zero();
  2533. this._edge2 = Vector3.Zero();
  2534. this._pvec = Vector3.Zero();
  2535. this._tvec = Vector3.Zero();
  2536. this._qvec = Vector3.Zero();
  2537. }
  2538. vertex1.subtractToRef(vertex0, this._edge1);
  2539. vertex2.subtractToRef(vertex0, this._edge2);
  2540. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2541. var det = Vector3.Dot(this._edge1, this._pvec);
  2542. if (det === 0) {
  2543. return null;
  2544. }
  2545. var invdet = 1 / det;
  2546. this.origin.subtractToRef(vertex0, this._tvec);
  2547. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2548. if (bu < 0 || bu > 1.0) {
  2549. return null;
  2550. }
  2551. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2552. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2553. if (bv < 0 || bu + bv > 1.0) {
  2554. return null;
  2555. }
  2556. //check if the distance is longer than the predefined length.
  2557. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2558. if (distance > this.length) {
  2559. return null;
  2560. }
  2561. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2562. };
  2563. // Statics
  2564. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2565. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2566. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2567. var direction = end.subtract(start);
  2568. direction.normalize();
  2569. return new Ray(start, direction);
  2570. };
  2571. /**
  2572. * 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
  2573. * transformed to the given world matrix.
  2574. * @param origin The origin point
  2575. * @param end The end point
  2576. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2577. */
  2578. Ray.CreateNewFromTo = function (origin, end, world) {
  2579. if (world === void 0) { world = Matrix.Identity(); }
  2580. var direction = end.subtract(origin);
  2581. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2582. direction.normalize();
  2583. return Ray.Transform(new Ray(origin, direction, length), world);
  2584. };
  2585. Ray.Transform = function (ray, matrix) {
  2586. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2587. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2588. return new Ray(newOrigin, newDirection, ray.length);
  2589. };
  2590. return Ray;
  2591. })();
  2592. BABYLON.Ray = Ray;
  2593. (function (Space) {
  2594. Space[Space["LOCAL"] = 0] = "LOCAL";
  2595. Space[Space["WORLD"] = 1] = "WORLD";
  2596. })(BABYLON.Space || (BABYLON.Space = {}));
  2597. var Space = BABYLON.Space;
  2598. var Axis = (function () {
  2599. function Axis() {
  2600. }
  2601. Axis.X = new Vector3(1, 0, 0);
  2602. Axis.Y = new Vector3(0, 1, 0);
  2603. Axis.Z = new Vector3(0, 0, 1);
  2604. return Axis;
  2605. })();
  2606. BABYLON.Axis = Axis;
  2607. ;
  2608. var BezierCurve = (function () {
  2609. function BezierCurve() {
  2610. }
  2611. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2612. // Extract X (which is equal to time here)
  2613. var f0 = 1 - 3 * x2 + 3 * x1;
  2614. var f1 = 3 * x2 - 6 * x1;
  2615. var f2 = 3 * x1;
  2616. var refinedT = t;
  2617. for (var i = 0; i < 5; i++) {
  2618. var refinedT2 = refinedT * refinedT;
  2619. var refinedT3 = refinedT2 * refinedT;
  2620. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2621. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2622. refinedT -= (x - t) * slope;
  2623. refinedT = Math.min(1, Math.max(0, refinedT));
  2624. }
  2625. // Resolve cubic bezier for the given x
  2626. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2627. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2628. Math.pow(refinedT, 3);
  2629. };
  2630. return BezierCurve;
  2631. })();
  2632. BABYLON.BezierCurve = BezierCurve;
  2633. (function (Orientation) {
  2634. Orientation[Orientation["CW"] = 0] = "CW";
  2635. Orientation[Orientation["CCW"] = 1] = "CCW";
  2636. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2637. var Orientation = BABYLON.Orientation;
  2638. var Angle = (function () {
  2639. function Angle(radians) {
  2640. var _this = this;
  2641. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2642. this.radians = function () { return _this._radians; };
  2643. this._radians = radians;
  2644. if (this._radians < 0)
  2645. this._radians += (2 * Math.PI);
  2646. }
  2647. Angle.BetweenTwoPoints = function (a, b) {
  2648. var delta = b.subtract(a);
  2649. var theta = Math.atan2(delta.y, delta.x);
  2650. return new Angle(theta);
  2651. };
  2652. Angle.FromRadians = function (radians) {
  2653. return new Angle(radians);
  2654. };
  2655. Angle.FromDegrees = function (degrees) {
  2656. return new Angle(degrees * Math.PI / 180);
  2657. };
  2658. return Angle;
  2659. })();
  2660. BABYLON.Angle = Angle;
  2661. var Arc2 = (function () {
  2662. function Arc2(startPoint, midPoint, endPoint) {
  2663. this.startPoint = startPoint;
  2664. this.midPoint = midPoint;
  2665. this.endPoint = endPoint;
  2666. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2667. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2668. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2669. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2670. 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);
  2671. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2672. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2673. var a1 = this.startAngle.degrees();
  2674. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2675. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2676. // angles correction
  2677. if (a2 - a1 > +180.0)
  2678. a2 -= 360.0;
  2679. if (a2 - a1 < -180.0)
  2680. a2 += 360.0;
  2681. if (a3 - a2 > +180.0)
  2682. a3 -= 360.0;
  2683. if (a3 - a2 < -180.0)
  2684. a3 += 360.0;
  2685. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2686. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2687. }
  2688. return Arc2;
  2689. })();
  2690. BABYLON.Arc2 = Arc2;
  2691. var PathCursor = (function () {
  2692. function PathCursor(path) {
  2693. this.path = path;
  2694. this._onchange = new Array();
  2695. this.value = 0;
  2696. this.animations = new Array();
  2697. }
  2698. PathCursor.prototype.getPoint = function () {
  2699. var point = this.path.getPointAtLengthPosition(this.value);
  2700. return new Vector3(point.x, 0, point.y);
  2701. };
  2702. PathCursor.prototype.moveAhead = function (step) {
  2703. if (step === void 0) { step = 0.002; }
  2704. this.move(step);
  2705. return this;
  2706. };
  2707. PathCursor.prototype.moveBack = function (step) {
  2708. if (step === void 0) { step = 0.002; }
  2709. this.move(-step);
  2710. return this;
  2711. };
  2712. PathCursor.prototype.move = function (step) {
  2713. if (Math.abs(step) > 1) {
  2714. throw "step size should be less than 1.";
  2715. }
  2716. this.value += step;
  2717. this.ensureLimits();
  2718. this.raiseOnChange();
  2719. return this;
  2720. };
  2721. PathCursor.prototype.ensureLimits = function () {
  2722. while (this.value > 1) {
  2723. this.value -= 1;
  2724. }
  2725. while (this.value < 0) {
  2726. this.value += 1;
  2727. }
  2728. return this;
  2729. };
  2730. // used by animation engine
  2731. PathCursor.prototype.markAsDirty = function (propertyName) {
  2732. this.ensureLimits();
  2733. this.raiseOnChange();
  2734. return this;
  2735. };
  2736. PathCursor.prototype.raiseOnChange = function () {
  2737. var _this = this;
  2738. this._onchange.forEach(function (f) { return f(_this); });
  2739. return this;
  2740. };
  2741. PathCursor.prototype.onchange = function (f) {
  2742. this._onchange.push(f);
  2743. return this;
  2744. };
  2745. return PathCursor;
  2746. })();
  2747. BABYLON.PathCursor = PathCursor;
  2748. var Path2 = (function () {
  2749. function Path2(x, y) {
  2750. this._points = new Array();
  2751. this._length = 0;
  2752. this.closed = false;
  2753. this._points.push(new Vector2(x, y));
  2754. }
  2755. Path2.prototype.addLineTo = function (x, y) {
  2756. if (closed) {
  2757. BABYLON.Tools.Error("cannot add lines to closed paths");
  2758. return this;
  2759. }
  2760. var newPoint = new Vector2(x, y);
  2761. var previousPoint = this._points[this._points.length - 1];
  2762. this._points.push(newPoint);
  2763. this._length += newPoint.subtract(previousPoint).length();
  2764. return this;
  2765. };
  2766. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2767. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2768. if (closed) {
  2769. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2770. return this;
  2771. }
  2772. var startPoint = this._points[this._points.length - 1];
  2773. var midPoint = new Vector2(midX, midY);
  2774. var endPoint = new Vector2(endX, endY);
  2775. var arc = new Arc2(startPoint, midPoint, endPoint);
  2776. var increment = arc.angle.radians() / numberOfSegments;
  2777. if (arc.orientation === Orientation.CW)
  2778. increment *= -1;
  2779. var currentAngle = arc.startAngle.radians() + increment;
  2780. for (var i = 0; i < numberOfSegments; i++) {
  2781. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2782. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2783. this.addLineTo(x, y);
  2784. currentAngle += increment;
  2785. }
  2786. return this;
  2787. };
  2788. Path2.prototype.close = function () {
  2789. this.closed = true;
  2790. return this;
  2791. };
  2792. Path2.prototype.length = function () {
  2793. var result = this._length;
  2794. if (!this.closed) {
  2795. var lastPoint = this._points[this._points.length - 1];
  2796. var firstPoint = this._points[0];
  2797. result += (firstPoint.subtract(lastPoint).length());
  2798. }
  2799. return result;
  2800. };
  2801. Path2.prototype.getPoints = function () {
  2802. return this._points;
  2803. };
  2804. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2805. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2806. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2807. return Vector2.Zero();
  2808. }
  2809. var lengthPosition = normalizedLengthPosition * this.length();
  2810. var previousOffset = 0;
  2811. for (var i = 0; i < this._points.length; i++) {
  2812. var j = (i + 1) % this._points.length;
  2813. var a = this._points[i];
  2814. var b = this._points[j];
  2815. var bToA = b.subtract(a);
  2816. var nextOffset = (bToA.length() + previousOffset);
  2817. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2818. var dir = bToA.normalize();
  2819. var localOffset = lengthPosition - previousOffset;
  2820. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2821. }
  2822. previousOffset = nextOffset;
  2823. }
  2824. BABYLON.Tools.Error("internal error");
  2825. return Vector2.Zero();
  2826. };
  2827. Path2.StartingAt = function (x, y) {
  2828. return new Path2(x, y);
  2829. };
  2830. return Path2;
  2831. })();
  2832. BABYLON.Path2 = Path2;
  2833. var Path3D = (function () {
  2834. /**
  2835. * new Path3D(path, normal, raw)
  2836. * path : an array of Vector3, the curve axis of the Path3D
  2837. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2838. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2839. */
  2840. function Path3D(path, firstNormal, raw) {
  2841. this.path = path;
  2842. this._curve = new Array();
  2843. this._distances = new Array();
  2844. this._tangents = new Array();
  2845. this._normals = new Array();
  2846. this._binormals = new Array();
  2847. for (var p = 0; p < path.length; p++) {
  2848. this._curve[p] = path[p].clone(); // hard copy
  2849. }
  2850. this._raw = raw || false;
  2851. this._compute(firstNormal);
  2852. }
  2853. Path3D.prototype.getCurve = function () {
  2854. return this._curve;
  2855. };
  2856. Path3D.prototype.getTangents = function () {
  2857. return this._tangents;
  2858. };
  2859. Path3D.prototype.getNormals = function () {
  2860. return this._normals;
  2861. };
  2862. Path3D.prototype.getBinormals = function () {
  2863. return this._binormals;
  2864. };
  2865. Path3D.prototype.getDistances = function () {
  2866. return this._distances;
  2867. };
  2868. Path3D.prototype.update = function (path, firstNormal) {
  2869. for (var p = 0; p < path.length; p++) {
  2870. this._curve[p].x = path[p].x;
  2871. this._curve[p].y = path[p].y;
  2872. this._curve[p].z = path[p].z;
  2873. }
  2874. this._compute(firstNormal);
  2875. return this;
  2876. };
  2877. // private function compute() : computes tangents, normals and binormals
  2878. Path3D.prototype._compute = function (firstNormal) {
  2879. var l = this._curve.length;
  2880. // first and last tangents
  2881. this._tangents[0] = this._getFirstNonNullVector(0);
  2882. if (!this._raw) {
  2883. this._tangents[0].normalize();
  2884. }
  2885. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2886. if (!this._raw) {
  2887. this._tangents[l - 1].normalize();
  2888. }
  2889. // normals and binormals at first point : arbitrary vector with _normalVector()
  2890. var tg0 = this._tangents[0];
  2891. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2892. this._normals[0] = pp0;
  2893. if (!this._raw) {
  2894. this._normals[0].normalize();
  2895. }
  2896. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2897. if (!this._raw) {
  2898. this._binormals[0].normalize();
  2899. }
  2900. this._distances[0] = 0;
  2901. // normals and binormals : next points
  2902. var prev; // previous vector (segment)
  2903. var cur; // current vector (segment)
  2904. var curTang; // current tangent
  2905. // previous normal
  2906. var prevBinor; // previous binormal
  2907. for (var i = 1; i < l; i++) {
  2908. // tangents
  2909. prev = this._getLastNonNullVector(i);
  2910. if (i < l - 1) {
  2911. cur = this._getFirstNonNullVector(i);
  2912. this._tangents[i] = prev.add(cur);
  2913. this._tangents[i].normalize();
  2914. }
  2915. this._distances[i] = this._distances[i - 1] + prev.length();
  2916. // normals and binormals
  2917. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2918. curTang = this._tangents[i];
  2919. prevBinor = this._binormals[i - 1];
  2920. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2921. if (!this._raw) {
  2922. this._normals[i].normalize();
  2923. }
  2924. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2925. if (!this._raw) {
  2926. this._binormals[i].normalize();
  2927. }
  2928. }
  2929. };
  2930. // private function getFirstNonNullVector(index)
  2931. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2932. Path3D.prototype._getFirstNonNullVector = function (index) {
  2933. var i = 1;
  2934. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2935. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2936. i++;
  2937. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2938. }
  2939. return nNVector;
  2940. };
  2941. // private function getLastNonNullVector(index)
  2942. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2943. Path3D.prototype._getLastNonNullVector = function (index) {
  2944. var i = 1;
  2945. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2946. while (nLVector.length() === 0 && index > i + 1) {
  2947. i++;
  2948. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2949. }
  2950. return nLVector;
  2951. };
  2952. // private function normalVector(v0, vt, va) :
  2953. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2954. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2955. Path3D.prototype._normalVector = function (v0, vt, va) {
  2956. var normal0;
  2957. if (va === undefined || va === null) {
  2958. var point;
  2959. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2960. point = new Vector3(0, -1, 0);
  2961. }
  2962. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2963. point = new Vector3(1, 0, 0);
  2964. }
  2965. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2966. point = new Vector3(0, 0, 1);
  2967. }
  2968. normal0 = Vector3.Cross(vt, point);
  2969. }
  2970. else {
  2971. normal0 = Vector3.Cross(vt, va);
  2972. Vector3.CrossToRef(normal0, vt, normal0);
  2973. }
  2974. normal0.normalize();
  2975. return normal0;
  2976. };
  2977. return Path3D;
  2978. })();
  2979. BABYLON.Path3D = Path3D;
  2980. var Curve3 = (function () {
  2981. function Curve3(points) {
  2982. this._length = 0;
  2983. this._points = points;
  2984. this._length = this._computeLength(points);
  2985. }
  2986. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2987. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2988. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2989. var bez = new Array();
  2990. var equation = function (t, val0, val1, val2) {
  2991. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2992. return res;
  2993. };
  2994. for (var i = 0; i <= nbPoints; i++) {
  2995. 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)));
  2996. }
  2997. return new Curve3(bez);
  2998. };
  2999. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  3000. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3001. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3002. var bez = new Array();
  3003. var equation = function (t, val0, val1, val2, val3) {
  3004. 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;
  3005. return res;
  3006. };
  3007. for (var i = 0; i <= nbPoints; i++) {
  3008. 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)));
  3009. }
  3010. return new Curve3(bez);
  3011. };
  3012. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  3013. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3014. var hermite = new Array();
  3015. var step = 1 / nbPoints;
  3016. for (var i = 0; i <= nbPoints; i++) {
  3017. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3018. }
  3019. return new Curve3(hermite);
  3020. };
  3021. Curve3.prototype.getPoints = function () {
  3022. return this._points;
  3023. };
  3024. Curve3.prototype.length = function () {
  3025. return this._length;
  3026. };
  3027. Curve3.prototype.continue = function (curve) {
  3028. var lastPoint = this._points[this._points.length - 1];
  3029. var continuedPoints = this._points.slice();
  3030. var curvePoints = curve.getPoints();
  3031. for (var i = 1; i < curvePoints.length; i++) {
  3032. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3033. }
  3034. var continuedCurve = new Curve3(continuedPoints);
  3035. return continuedCurve;
  3036. };
  3037. Curve3.prototype._computeLength = function (path) {
  3038. var l = 0;
  3039. for (var i = 1; i < path.length; i++) {
  3040. l += (path[i].subtract(path[i - 1])).length();
  3041. }
  3042. return l;
  3043. };
  3044. return Curve3;
  3045. })();
  3046. BABYLON.Curve3 = Curve3;
  3047. // Vertex formats
  3048. var PositionNormalVertex = (function () {
  3049. function PositionNormalVertex(position, normal) {
  3050. if (position === void 0) { position = Vector3.Zero(); }
  3051. if (normal === void 0) { normal = Vector3.Up(); }
  3052. this.position = position;
  3053. this.normal = normal;
  3054. }
  3055. PositionNormalVertex.prototype.clone = function () {
  3056. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3057. };
  3058. return PositionNormalVertex;
  3059. })();
  3060. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3061. var PositionNormalTextureVertex = (function () {
  3062. function PositionNormalTextureVertex(position, normal, uv) {
  3063. if (position === void 0) { position = Vector3.Zero(); }
  3064. if (normal === void 0) { normal = Vector3.Up(); }
  3065. if (uv === void 0) { uv = Vector2.Zero(); }
  3066. this.position = position;
  3067. this.normal = normal;
  3068. this.uv = uv;
  3069. }
  3070. PositionNormalTextureVertex.prototype.clone = function () {
  3071. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3072. };
  3073. return PositionNormalTextureVertex;
  3074. })();
  3075. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3076. // SIMD
  3077. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3078. var previousInvertToRef = Matrix.prototype.invertToRef;
  3079. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3080. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3081. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3082. var SIMDHelper = (function () {
  3083. function SIMDHelper() {
  3084. }
  3085. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3086. get: function () {
  3087. return SIMDHelper._isEnabled;
  3088. },
  3089. enumerable: true,
  3090. configurable: true
  3091. });
  3092. SIMDHelper.DisableSIMD = function () {
  3093. // Replace functions
  3094. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3095. Matrix.prototype.invertToRef = previousInvertToRef;
  3096. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3097. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3098. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3099. SIMDHelper._isEnabled = false;
  3100. };
  3101. SIMDHelper.EnableSIMD = function () {
  3102. if (window.SIMD === undefined) {
  3103. return;
  3104. }
  3105. // Replace functions
  3106. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3107. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3108. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3109. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3110. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3111. Object.defineProperty(Vector3.prototype, "x", {
  3112. get: function () { return this._data[0]; },
  3113. set: function (value) {
  3114. if (!this._data) {
  3115. this._data = new Float32Array(3);
  3116. }
  3117. this._data[0] = value;
  3118. }
  3119. });
  3120. Object.defineProperty(Vector3.prototype, "y", {
  3121. get: function () { return this._data[1]; },
  3122. set: function (value) {
  3123. this._data[1] = value;
  3124. }
  3125. });
  3126. Object.defineProperty(Vector3.prototype, "z", {
  3127. get: function () { return this._data[2]; },
  3128. set: function (value) {
  3129. this._data[2] = value;
  3130. }
  3131. });
  3132. SIMDHelper._isEnabled = true;
  3133. };
  3134. SIMDHelper._isEnabled = false;
  3135. return SIMDHelper;
  3136. })();
  3137. BABYLON.SIMDHelper = SIMDHelper;
  3138. })(BABYLON || (BABYLON = {}));
  3139. var BABYLON;
  3140. (function (BABYLON) {
  3141. var Database = (function () {
  3142. function Database(urlToScene, callbackManifestChecked) {
  3143. // Handling various flavors of prefixed version of IndexedDB
  3144. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3145. this.callbackManifestChecked = callbackManifestChecked;
  3146. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3147. this.db = null;
  3148. this.enableSceneOffline = false;
  3149. this.enableTexturesOffline = false;
  3150. this.manifestVersionFound = 0;
  3151. this.mustUpdateRessources = false;
  3152. this.hasReachedQuota = false;
  3153. if (!Database.IDBStorageEnabled) {
  3154. this.callbackManifestChecked(true);
  3155. }
  3156. else {
  3157. this.checkManifestFile();
  3158. }
  3159. }
  3160. Database.prototype.checkManifestFile = function () {
  3161. var _this = this;
  3162. function noManifestFile() {
  3163. that.enableSceneOffline = false;
  3164. that.enableTexturesOffline = false;
  3165. that.callbackManifestChecked(false);
  3166. }
  3167. var that = this;
  3168. var manifestURL = this.currentSceneUrl + ".manifest";
  3169. var xhr = new XMLHttpRequest();
  3170. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3171. xhr.open("GET", manifestURLTimeStamped, true);
  3172. xhr.addEventListener("load", function () {
  3173. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3174. try {
  3175. var manifestFile = JSON.parse(xhr.response);
  3176. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3177. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3178. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3179. _this.manifestVersionFound = manifestFile.version;
  3180. }
  3181. if (_this.callbackManifestChecked) {
  3182. _this.callbackManifestChecked(true);
  3183. }
  3184. }
  3185. catch (ex) {
  3186. noManifestFile();
  3187. }
  3188. }
  3189. else {
  3190. noManifestFile();
  3191. }
  3192. }, false);
  3193. xhr.addEventListener("error", function (event) {
  3194. noManifestFile();
  3195. }, false);
  3196. try {
  3197. xhr.send();
  3198. }
  3199. catch (ex) {
  3200. BABYLON.Tools.Error("Error on XHR send request.");
  3201. that.callbackManifestChecked(false);
  3202. }
  3203. };
  3204. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3205. var _this = this;
  3206. function handleError() {
  3207. that.isSupported = false;
  3208. if (errorCallback)
  3209. errorCallback();
  3210. }
  3211. var that = this;
  3212. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3213. // Your browser doesn't support IndexedDB
  3214. this.isSupported = false;
  3215. if (errorCallback)
  3216. errorCallback();
  3217. }
  3218. else {
  3219. // If the DB hasn't been opened or created yet
  3220. if (!this.db) {
  3221. this.hasReachedQuota = false;
  3222. this.isSupported = true;
  3223. var request = this.idbFactory.open("babylonjs", 1);
  3224. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3225. request.onerror = function (event) {
  3226. handleError();
  3227. };
  3228. // executes when a version change transaction cannot complete due to other active transactions
  3229. request.onblocked = function (event) {
  3230. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3231. handleError();
  3232. };
  3233. // DB has been opened successfully
  3234. request.onsuccess = function (event) {
  3235. _this.db = request.result;
  3236. successCallback();
  3237. };
  3238. // Initialization of the DB. Creating Scenes & Textures stores
  3239. request.onupgradeneeded = function (event) {
  3240. _this.db = (event.target).result;
  3241. try {
  3242. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3243. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3244. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3245. }
  3246. catch (ex) {
  3247. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3248. handleError();
  3249. }
  3250. };
  3251. }
  3252. else {
  3253. if (successCallback)
  3254. successCallback();
  3255. }
  3256. }
  3257. };
  3258. Database.prototype.loadImageFromDB = function (url, image) {
  3259. var _this = this;
  3260. var completeURL = Database.ReturnFullUrlLocation(url);
  3261. var saveAndLoadImage = function () {
  3262. if (!_this.hasReachedQuota && _this.db !== null) {
  3263. // the texture is not yet in the DB, let's try to save it
  3264. _this._saveImageIntoDBAsync(completeURL, image);
  3265. }
  3266. else {
  3267. image.src = url;
  3268. }
  3269. };
  3270. if (!this.mustUpdateRessources) {
  3271. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3272. }
  3273. else {
  3274. saveAndLoadImage();
  3275. }
  3276. };
  3277. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3278. if (this.isSupported && this.db !== null) {
  3279. var texture;
  3280. var transaction = this.db.transaction(["textures"]);
  3281. transaction.onabort = function (event) {
  3282. image.src = url;
  3283. };
  3284. transaction.oncomplete = function (event) {
  3285. var blobTextureURL;
  3286. if (texture) {
  3287. var URL = window.URL || window.webkitURL;
  3288. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3289. image.onerror = function () {
  3290. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3291. image.src = url;
  3292. };
  3293. image.src = blobTextureURL;
  3294. }
  3295. else {
  3296. notInDBCallback();
  3297. }
  3298. };
  3299. var getRequest = transaction.objectStore("textures").get(url);
  3300. getRequest.onsuccess = function (event) {
  3301. texture = (event.target).result;
  3302. };
  3303. getRequest.onerror = function (event) {
  3304. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3305. image.src = url;
  3306. };
  3307. }
  3308. else {
  3309. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3310. image.src = url;
  3311. }
  3312. };
  3313. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3314. var _this = this;
  3315. if (this.isSupported) {
  3316. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3317. var generateBlobUrl = function () {
  3318. var blobTextureURL;
  3319. if (blob) {
  3320. var URL = window.URL || window.webkitURL;
  3321. try {
  3322. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3323. }
  3324. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3325. catch (ex) {
  3326. blobTextureURL = URL.createObjectURL(blob);
  3327. }
  3328. }
  3329. image.src = blobTextureURL;
  3330. };
  3331. if (Database.IsUASupportingBlobStorage) {
  3332. var xhr = new XMLHttpRequest(), blob;
  3333. xhr.open("GET", url, true);
  3334. xhr.responseType = "blob";
  3335. xhr.addEventListener("load", function () {
  3336. if (xhr.status === 200) {
  3337. // Blob as response (XHR2)
  3338. blob = xhr.response;
  3339. var transaction = _this.db.transaction(["textures"], "readwrite");
  3340. // the transaction could abort because of a QuotaExceededError error
  3341. transaction.onabort = function (event) {
  3342. try {
  3343. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3344. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3345. this.hasReachedQuota = true;
  3346. }
  3347. }
  3348. catch (ex) { }
  3349. generateBlobUrl();
  3350. };
  3351. transaction.oncomplete = function (event) {
  3352. generateBlobUrl();
  3353. };
  3354. var newTexture = { textureUrl: url, data: blob };
  3355. try {
  3356. // Put the blob into the dabase
  3357. var addRequest = transaction.objectStore("textures").put(newTexture);
  3358. addRequest.onsuccess = function (event) {
  3359. };
  3360. addRequest.onerror = function (event) {
  3361. generateBlobUrl();
  3362. };
  3363. }
  3364. catch (ex) {
  3365. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3366. if (ex.code === 25) {
  3367. Database.IsUASupportingBlobStorage = false;
  3368. }
  3369. image.src = url;
  3370. }
  3371. }
  3372. else {
  3373. image.src = url;
  3374. }
  3375. }, false);
  3376. xhr.addEventListener("error", function (event) {
  3377. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3378. image.src = url;
  3379. }, false);
  3380. xhr.send();
  3381. }
  3382. else {
  3383. image.src = url;
  3384. }
  3385. }
  3386. else {
  3387. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3388. image.src = url;
  3389. }
  3390. };
  3391. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3392. var _this = this;
  3393. var updateVersion = function (event) {
  3394. // the version is not yet in the DB or we need to update it
  3395. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3396. };
  3397. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3398. };
  3399. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3400. var _this = this;
  3401. if (this.isSupported) {
  3402. var version;
  3403. try {
  3404. var transaction = this.db.transaction(["versions"]);
  3405. transaction.oncomplete = function (event) {
  3406. if (version) {
  3407. // If the version in the JSON file is > than the version in DB
  3408. if (_this.manifestVersionFound > version.data) {
  3409. _this.mustUpdateRessources = true;
  3410. updateInDBCallback();
  3411. }
  3412. else {
  3413. callback(version.data);
  3414. }
  3415. }
  3416. else {
  3417. _this.mustUpdateRessources = true;
  3418. updateInDBCallback();
  3419. }
  3420. };
  3421. transaction.onabort = function (event) {
  3422. callback(-1);
  3423. };
  3424. var getRequest = transaction.objectStore("versions").get(url);
  3425. getRequest.onsuccess = function (event) {
  3426. version = (event.target).result;
  3427. };
  3428. getRequest.onerror = function (event) {
  3429. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3430. callback(-1);
  3431. };
  3432. }
  3433. catch (ex) {
  3434. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3435. callback(-1);
  3436. }
  3437. }
  3438. else {
  3439. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3440. callback(-1);
  3441. }
  3442. };
  3443. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3444. var _this = this;
  3445. if (this.isSupported && !this.hasReachedQuota) {
  3446. try {
  3447. // Open a transaction to the database
  3448. var transaction = this.db.transaction(["versions"], "readwrite");
  3449. // the transaction could abort because of a QuotaExceededError error
  3450. transaction.onabort = function (event) {
  3451. try {
  3452. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3453. _this.hasReachedQuota = true;
  3454. }
  3455. }
  3456. catch (ex) { }
  3457. callback(-1);
  3458. };
  3459. transaction.oncomplete = function (event) {
  3460. callback(_this.manifestVersionFound);
  3461. };
  3462. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3463. // Put the scene into the database
  3464. var addRequest = transaction.objectStore("versions").put(newVersion);
  3465. addRequest.onsuccess = function (event) {
  3466. };
  3467. addRequest.onerror = function (event) {
  3468. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3469. };
  3470. }
  3471. catch (ex) {
  3472. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3473. callback(-1);
  3474. }
  3475. }
  3476. else {
  3477. callback(-1);
  3478. }
  3479. };
  3480. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3481. var _this = this;
  3482. var completeUrl = Database.ReturnFullUrlLocation(url);
  3483. var saveAndLoadFile = function (event) {
  3484. // the scene is not yet in the DB, let's try to save it
  3485. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3486. };
  3487. this._checkVersionFromDB(completeUrl, function (version) {
  3488. if (version !== -1) {
  3489. if (!_this.mustUpdateRessources) {
  3490. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3491. }
  3492. else {
  3493. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3494. }
  3495. }
  3496. else {
  3497. errorCallback();
  3498. }
  3499. });
  3500. };
  3501. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3502. if (this.isSupported) {
  3503. var targetStore;
  3504. if (url.indexOf(".babylon") !== -1) {
  3505. targetStore = "scenes";
  3506. }
  3507. else {
  3508. targetStore = "textures";
  3509. }
  3510. var file;
  3511. var transaction = this.db.transaction([targetStore]);
  3512. transaction.oncomplete = function (event) {
  3513. if (file) {
  3514. callback(file.data);
  3515. }
  3516. else {
  3517. notInDBCallback();
  3518. }
  3519. };
  3520. transaction.onabort = function (event) {
  3521. notInDBCallback();
  3522. };
  3523. var getRequest = transaction.objectStore(targetStore).get(url);
  3524. getRequest.onsuccess = function (event) {
  3525. file = (event.target).result;
  3526. };
  3527. getRequest.onerror = function (event) {
  3528. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3529. notInDBCallback();
  3530. };
  3531. }
  3532. else {
  3533. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3534. callback();
  3535. }
  3536. };
  3537. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3538. var _this = this;
  3539. if (this.isSupported) {
  3540. var targetStore;
  3541. if (url.indexOf(".babylon") !== -1) {
  3542. targetStore = "scenes";
  3543. }
  3544. else {
  3545. targetStore = "textures";
  3546. }
  3547. // Create XHR
  3548. var xhr = new XMLHttpRequest(), fileData;
  3549. xhr.open("GET", url, true);
  3550. if (useArrayBuffer) {
  3551. xhr.responseType = "arraybuffer";
  3552. }
  3553. xhr.onprogress = progressCallback;
  3554. xhr.addEventListener("load", function () {
  3555. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3556. // Blob as response (XHR2)
  3557. //fileData = xhr.responseText;
  3558. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3559. if (!_this.hasReachedQuota) {
  3560. // Open a transaction to the database
  3561. var transaction = _this.db.transaction([targetStore], "readwrite");
  3562. // the transaction could abort because of a QuotaExceededError error
  3563. transaction.onabort = function (event) {
  3564. try {
  3565. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3566. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3567. this.hasReachedQuota = true;
  3568. }
  3569. }
  3570. catch (ex) { }
  3571. callback(fileData);
  3572. };
  3573. transaction.oncomplete = function (event) {
  3574. callback(fileData);
  3575. };
  3576. var newFile;
  3577. if (targetStore === "scenes") {
  3578. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3579. }
  3580. else {
  3581. newFile = { textureUrl: url, data: fileData };
  3582. }
  3583. try {
  3584. // Put the scene into the database
  3585. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3586. addRequest.onsuccess = function (event) {
  3587. };
  3588. addRequest.onerror = function (event) {
  3589. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3590. };
  3591. }
  3592. catch (ex) {
  3593. callback(fileData);
  3594. }
  3595. }
  3596. else {
  3597. callback(fileData);
  3598. }
  3599. }
  3600. else {
  3601. callback();
  3602. }
  3603. }, false);
  3604. xhr.addEventListener("error", function (event) {
  3605. BABYLON.Tools.Error("error on XHR request.");
  3606. callback();
  3607. }, false);
  3608. xhr.send();
  3609. }
  3610. else {
  3611. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3612. callback();
  3613. }
  3614. };
  3615. Database.IsUASupportingBlobStorage = true;
  3616. Database.IDBStorageEnabled = true;
  3617. Database.parseURL = function (url) {
  3618. var a = document.createElement('a');
  3619. a.href = url;
  3620. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3621. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3622. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3623. return absLocation;
  3624. };
  3625. Database.ReturnFullUrlLocation = function (url) {
  3626. if (url.indexOf("http:/") === -1) {
  3627. return (Database.parseURL(window.location.href) + url);
  3628. }
  3629. else {
  3630. return url;
  3631. }
  3632. };
  3633. return Database;
  3634. })();
  3635. BABYLON.Database = Database;
  3636. })(BABYLON || (BABYLON = {}));
  3637. var BABYLON;
  3638. (function (BABYLON) {
  3639. var Internals;
  3640. (function (Internals) {
  3641. /*
  3642. * Based on jsTGALoader - Javascript loader for TGA file
  3643. * By Vincent Thibault
  3644. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3645. */
  3646. var TGATools = (function () {
  3647. function TGATools() {
  3648. }
  3649. TGATools.GetTGAHeader = function (data) {
  3650. var offset = 0;
  3651. var header = {
  3652. id_length: data[offset++],
  3653. colormap_type: data[offset++],
  3654. image_type: data[offset++],
  3655. colormap_index: data[offset++] | data[offset++] << 8,
  3656. colormap_length: data[offset++] | data[offset++] << 8,
  3657. colormap_size: data[offset++],
  3658. origin: [
  3659. data[offset++] | data[offset++] << 8,
  3660. data[offset++] | data[offset++] << 8
  3661. ],
  3662. width: data[offset++] | data[offset++] << 8,
  3663. height: data[offset++] | data[offset++] << 8,
  3664. pixel_size: data[offset++],
  3665. flags: data[offset++]
  3666. };
  3667. return header;
  3668. };
  3669. TGATools.UploadContent = function (gl, data) {
  3670. // Not enough data to contain header ?
  3671. if (data.length < 19) {
  3672. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3673. return;
  3674. }
  3675. // Read Header
  3676. var offset = 18;
  3677. var header = TGATools.GetTGAHeader(data);
  3678. // Assume it's a valid Targa file.
  3679. if (header.id_length + offset > data.length) {
  3680. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3681. return;
  3682. }
  3683. // Skip not needed data
  3684. offset += header.id_length;
  3685. var use_rle = false;
  3686. var use_pal = false;
  3687. var use_rgb = false;
  3688. var use_grey = false;
  3689. // Get some informations.
  3690. switch (header.image_type) {
  3691. case TGATools._TYPE_RLE_INDEXED:
  3692. use_rle = true;
  3693. case TGATools._TYPE_INDEXED:
  3694. use_pal = true;
  3695. break;
  3696. case TGATools._TYPE_RLE_RGB:
  3697. use_rle = true;
  3698. case TGATools._TYPE_RGB:
  3699. use_rgb = true;
  3700. break;
  3701. case TGATools._TYPE_RLE_GREY:
  3702. use_rle = true;
  3703. case TGATools._TYPE_GREY:
  3704. use_grey = true;
  3705. break;
  3706. }
  3707. var pixel_data;
  3708. var numAlphaBits = header.flags & 0xf;
  3709. var pixel_size = header.pixel_size >> 3;
  3710. var pixel_total = header.width * header.height * pixel_size;
  3711. // Read palettes
  3712. var palettes;
  3713. if (use_pal) {
  3714. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3715. }
  3716. // Read LRE
  3717. if (use_rle) {
  3718. pixel_data = new Uint8Array(pixel_total);
  3719. var c, count, i;
  3720. var localOffset = 0;
  3721. var pixels = new Uint8Array(pixel_size);
  3722. while (offset < pixel_total && localOffset < pixel_total) {
  3723. c = data[offset++];
  3724. count = (c & 0x7f) + 1;
  3725. // RLE pixels
  3726. if (c & 0x80) {
  3727. // Bind pixel tmp array
  3728. for (i = 0; i < pixel_size; ++i) {
  3729. pixels[i] = data[offset++];
  3730. }
  3731. // Copy pixel array
  3732. for (i = 0; i < count; ++i) {
  3733. pixel_data.set(pixels, localOffset + i * pixel_size);
  3734. }
  3735. localOffset += pixel_size * count;
  3736. }
  3737. else {
  3738. count *= pixel_size;
  3739. for (i = 0; i < count; ++i) {
  3740. pixel_data[localOffset + i] = data[offset++];
  3741. }
  3742. localOffset += count;
  3743. }
  3744. }
  3745. }
  3746. else {
  3747. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3748. }
  3749. // Load to texture
  3750. var x_start, y_start, x_step, y_step, y_end, x_end;
  3751. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3752. default:
  3753. case TGATools._ORIGIN_UL:
  3754. x_start = 0;
  3755. x_step = 1;
  3756. x_end = header.width;
  3757. y_start = 0;
  3758. y_step = 1;
  3759. y_end = header.height;
  3760. break;
  3761. case TGATools._ORIGIN_BL:
  3762. x_start = 0;
  3763. x_step = 1;
  3764. x_end = header.width;
  3765. y_start = header.height - 1;
  3766. y_step = -1;
  3767. y_end = -1;
  3768. break;
  3769. case TGATools._ORIGIN_UR:
  3770. x_start = header.width - 1;
  3771. x_step = -1;
  3772. x_end = -1;
  3773. y_start = 0;
  3774. y_step = 1;
  3775. y_end = header.height;
  3776. break;
  3777. case TGATools._ORIGIN_BR:
  3778. x_start = header.width - 1;
  3779. x_step = -1;
  3780. x_end = -1;
  3781. y_start = header.height - 1;
  3782. y_step = -1;
  3783. y_end = -1;
  3784. break;
  3785. }
  3786. // Load the specify method
  3787. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3788. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3789. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3790. };
  3791. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3792. var image = pixel_data, colormap = palettes;
  3793. var width = header.width, height = header.height;
  3794. var color, i = 0, x, y;
  3795. var imageData = new Uint8Array(width * height * 4);
  3796. for (y = y_start; y !== y_end; y += y_step) {
  3797. for (x = x_start; x !== x_end; x += x_step, i++) {
  3798. color = image[i];
  3799. imageData[(x + width * y) * 4 + 3] = 255;
  3800. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3801. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3802. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3803. }
  3804. }
  3805. return imageData;
  3806. };
  3807. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3808. var image = pixel_data;
  3809. var width = header.width, height = header.height;
  3810. var color, i = 0, x, y;
  3811. var imageData = new Uint8Array(width * height * 4);
  3812. for (y = y_start; y !== y_end; y += y_step) {
  3813. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3814. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3815. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3816. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3817. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3818. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3819. }
  3820. }
  3821. return imageData;
  3822. };
  3823. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3824. var image = pixel_data;
  3825. var width = header.width, height = header.height;
  3826. var i = 0, x, y;
  3827. var imageData = new Uint8Array(width * height * 4);
  3828. for (y = y_start; y !== y_end; y += y_step) {
  3829. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3830. imageData[(x + width * y) * 4 + 3] = 255;
  3831. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3832. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3833. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3834. }
  3835. }
  3836. return imageData;
  3837. };
  3838. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3839. var image = pixel_data;
  3840. var width = header.width, height = header.height;
  3841. var i = 0, x, y;
  3842. var imageData = new Uint8Array(width * height * 4);
  3843. for (y = y_start; y !== y_end; y += y_step) {
  3844. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3845. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3846. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3847. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3848. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3849. }
  3850. }
  3851. return imageData;
  3852. };
  3853. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3854. var image = pixel_data;
  3855. var width = header.width, height = header.height;
  3856. var color, i = 0, x, y;
  3857. var imageData = new Uint8Array(width * height * 4);
  3858. for (y = y_start; y !== y_end; y += y_step) {
  3859. for (x = x_start; x !== x_end; x += x_step, i++) {
  3860. color = image[i];
  3861. imageData[(x + width * y) * 4 + 0] = color;
  3862. imageData[(x + width * y) * 4 + 1] = color;
  3863. imageData[(x + width * y) * 4 + 2] = color;
  3864. imageData[(x + width * y) * 4 + 3] = 255;
  3865. }
  3866. }
  3867. return imageData;
  3868. };
  3869. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3870. var image = pixel_data;
  3871. var width = header.width, height = header.height;
  3872. var i = 0, x, y;
  3873. var imageData = new Uint8Array(width * height * 4);
  3874. for (y = y_start; y !== y_end; y += y_step) {
  3875. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3876. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3877. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3878. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3879. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3880. }
  3881. }
  3882. return imageData;
  3883. };
  3884. TGATools._TYPE_NO_DATA = 0;
  3885. TGATools._TYPE_INDEXED = 1;
  3886. TGATools._TYPE_RGB = 2;
  3887. TGATools._TYPE_GREY = 3;
  3888. TGATools._TYPE_RLE_INDEXED = 9;
  3889. TGATools._TYPE_RLE_RGB = 10;
  3890. TGATools._TYPE_RLE_GREY = 11;
  3891. TGATools._ORIGIN_MASK = 0x30;
  3892. TGATools._ORIGIN_SHIFT = 0x04;
  3893. TGATools._ORIGIN_BL = 0x00;
  3894. TGATools._ORIGIN_BR = 0x01;
  3895. TGATools._ORIGIN_UL = 0x02;
  3896. TGATools._ORIGIN_UR = 0x03;
  3897. return TGATools;
  3898. })();
  3899. Internals.TGATools = TGATools;
  3900. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3901. })(BABYLON || (BABYLON = {}));
  3902. var BABYLON;
  3903. (function (BABYLON) {
  3904. var Internals;
  3905. (function (Internals) {
  3906. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3907. // All values and structures referenced from:
  3908. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3909. var DDS_MAGIC = 0x20534444;
  3910. 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;
  3911. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3912. 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;
  3913. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3914. function FourCCToInt32(value) {
  3915. return value.charCodeAt(0) +
  3916. (value.charCodeAt(1) << 8) +
  3917. (value.charCodeAt(2) << 16) +
  3918. (value.charCodeAt(3) << 24);
  3919. }
  3920. function Int32ToFourCC(value) {
  3921. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3922. }
  3923. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3924. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3925. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3926. var headerLengthInt = 31; // The header length in 32 bit ints
  3927. // Offsets into the header array
  3928. var off_magic = 0;
  3929. var off_size = 1;
  3930. var off_flags = 2;
  3931. var off_height = 3;
  3932. var off_width = 4;
  3933. var off_mipmapCount = 7;
  3934. var off_pfFlags = 20;
  3935. var off_pfFourCC = 21;
  3936. var off_RGBbpp = 22;
  3937. var off_RMask = 23;
  3938. var off_GMask = 24;
  3939. var off_BMask = 25;
  3940. var off_AMask = 26;
  3941. var off_caps1 = 27;
  3942. var off_caps2 = 28;
  3943. ;
  3944. var DDSTools = (function () {
  3945. function DDSTools() {
  3946. }
  3947. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3948. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3949. var mipmapCount = 1;
  3950. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3951. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3952. }
  3953. return {
  3954. width: header[off_width],
  3955. height: header[off_height],
  3956. mipmapCount: mipmapCount,
  3957. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3958. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3959. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3960. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3961. };
  3962. };
  3963. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3964. var byteArray = new Uint8Array(dataLength);
  3965. var srcData = new Uint8Array(arrayBuffer);
  3966. var index = 0;
  3967. for (var y = height - 1; y >= 0; y--) {
  3968. for (var x = 0; x < width; x++) {
  3969. var srcPos = dataOffset + (x + y * width) * 4;
  3970. byteArray[index + 2] = srcData[srcPos];
  3971. byteArray[index + 1] = srcData[srcPos + 1];
  3972. byteArray[index] = srcData[srcPos + 2];
  3973. byteArray[index + 3] = srcData[srcPos + 3];
  3974. index += 4;
  3975. }
  3976. }
  3977. return byteArray;
  3978. };
  3979. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3980. var byteArray = new Uint8Array(dataLength);
  3981. var srcData = new Uint8Array(arrayBuffer);
  3982. var index = 0;
  3983. for (var y = height - 1; y >= 0; y--) {
  3984. for (var x = 0; x < width; x++) {
  3985. var srcPos = dataOffset + (x + y * width) * 3;
  3986. byteArray[index + 2] = srcData[srcPos];
  3987. byteArray[index + 1] = srcData[srcPos + 1];
  3988. byteArray[index] = srcData[srcPos + 2];
  3989. index += 3;
  3990. }
  3991. }
  3992. return byteArray;
  3993. };
  3994. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3995. var byteArray = new Uint8Array(dataLength);
  3996. var srcData = new Uint8Array(arrayBuffer);
  3997. var index = 0;
  3998. for (var y = height - 1; y >= 0; y--) {
  3999. for (var x = 0; x < width; x++) {
  4000. var srcPos = dataOffset + (x + y * width);
  4001. byteArray[index] = srcData[srcPos];
  4002. index++;
  4003. }
  4004. }
  4005. return byteArray;
  4006. };
  4007. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  4008. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  4009. if (header[off_magic] != DDS_MAGIC) {
  4010. BABYLON.Tools.Error("Invalid magic number in DDS header");
  4011. return;
  4012. }
  4013. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  4014. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  4015. return;
  4016. }
  4017. if (info.isFourCC) {
  4018. fourCC = header[off_pfFourCC];
  4019. switch (fourCC) {
  4020. case FOURCC_DXT1:
  4021. blockBytes = 8;
  4022. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  4023. break;
  4024. case FOURCC_DXT3:
  4025. blockBytes = 16;
  4026. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  4027. break;
  4028. case FOURCC_DXT5:
  4029. blockBytes = 16;
  4030. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  4031. break;
  4032. default:
  4033. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  4034. return;
  4035. }
  4036. }
  4037. mipmapCount = 1;
  4038. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4039. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4040. }
  4041. var bpp = header[off_RGBbpp];
  4042. for (var face = 0; face < faces; face++) {
  4043. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4044. width = header[off_width];
  4045. height = header[off_height];
  4046. dataOffset = header[off_size] + 4;
  4047. for (i = 0; i < mipmapCount; ++i) {
  4048. if (info.isRGB) {
  4049. if (bpp == 24) {
  4050. dataLength = width * height * 3;
  4051. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4052. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4053. }
  4054. else {
  4055. dataLength = width * height * 4;
  4056. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4057. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4058. }
  4059. }
  4060. else if (info.isLuminance) {
  4061. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4062. var unpaddedRowSize = width;
  4063. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4064. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4065. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4066. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4067. }
  4068. else {
  4069. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4070. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4071. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4072. }
  4073. dataOffset += dataLength;
  4074. width *= 0.5;
  4075. height *= 0.5;
  4076. width = Math.max(1.0, width);
  4077. height = Math.max(1.0, height);
  4078. }
  4079. }
  4080. };
  4081. return DDSTools;
  4082. })();
  4083. Internals.DDSTools = DDSTools;
  4084. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4085. })(BABYLON || (BABYLON = {}));
  4086. var BABYLON;
  4087. (function (BABYLON) {
  4088. var SmartArray = (function () {
  4089. function SmartArray(capacity) {
  4090. this.length = 0;
  4091. this._duplicateId = 0;
  4092. this.data = new Array(capacity);
  4093. this._id = SmartArray._GlobalId++;
  4094. }
  4095. SmartArray.prototype.push = function (value) {
  4096. this.data[this.length++] = value;
  4097. if (this.length > this.data.length) {
  4098. this.data.length *= 2;
  4099. }
  4100. if (!value.__smartArrayFlags) {
  4101. value.__smartArrayFlags = {};
  4102. }
  4103. value.__smartArrayFlags[this._id] = this._duplicateId;
  4104. };
  4105. SmartArray.prototype.pushNoDuplicate = function (value) {
  4106. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4107. return;
  4108. }
  4109. this.push(value);
  4110. };
  4111. SmartArray.prototype.sort = function (compareFn) {
  4112. this.data.sort(compareFn);
  4113. };
  4114. SmartArray.prototype.reset = function () {
  4115. this.length = 0;
  4116. this._duplicateId++;
  4117. };
  4118. SmartArray.prototype.concat = function (array) {
  4119. if (array.length === 0) {
  4120. return;
  4121. }
  4122. if (this.length + array.length > this.data.length) {
  4123. this.data.length = (this.length + array.length) * 2;
  4124. }
  4125. for (var index = 0; index < array.length; index++) {
  4126. this.data[this.length++] = (array.data || array)[index];
  4127. }
  4128. };
  4129. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4130. if (array.length === 0) {
  4131. return;
  4132. }
  4133. if (this.length + array.length > this.data.length) {
  4134. this.data.length = (this.length + array.length) * 2;
  4135. }
  4136. for (var index = 0; index < array.length; index++) {
  4137. var item = (array.data || array)[index];
  4138. this.pushNoDuplicate(item);
  4139. }
  4140. };
  4141. SmartArray.prototype.indexOf = function (value) {
  4142. var position = this.data.indexOf(value);
  4143. if (position >= this.length) {
  4144. return -1;
  4145. }
  4146. return position;
  4147. };
  4148. // Statics
  4149. SmartArray._GlobalId = 0;
  4150. return SmartArray;
  4151. })();
  4152. BABYLON.SmartArray = SmartArray;
  4153. })(BABYLON || (BABYLON = {}));
  4154. var BABYLON;
  4155. (function (BABYLON) {
  4156. var SmartCollection = (function () {
  4157. function SmartCollection(capacity) {
  4158. if (capacity === void 0) { capacity = 10; }
  4159. this.count = 0;
  4160. this._initialCapacity = capacity;
  4161. this.items = {};
  4162. this._keys = new Array(this._initialCapacity);
  4163. }
  4164. SmartCollection.prototype.add = function (key, item) {
  4165. if (this.items[key] != undefined) {
  4166. return -1;
  4167. }
  4168. this.items[key] = item;
  4169. //literal keys are always strings, but we keep source type of key in _keys array
  4170. this._keys[this.count++] = key;
  4171. if (this.count > this._keys.length) {
  4172. this._keys.length *= 2;
  4173. }
  4174. return this.count;
  4175. };
  4176. SmartCollection.prototype.remove = function (key) {
  4177. if (this.items[key] == undefined) {
  4178. return -1;
  4179. }
  4180. return this.removeItemOfIndex(this.indexOf(key));
  4181. };
  4182. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4183. if (index < this.count && index > -1) {
  4184. delete this.items[this._keys[index]];
  4185. //here, shifting by hand is better optimised than .splice
  4186. while (index < this.count) {
  4187. this._keys[index] = this._keys[index + 1];
  4188. index++;
  4189. }
  4190. }
  4191. else {
  4192. return -1;
  4193. }
  4194. return --this.count;
  4195. };
  4196. SmartCollection.prototype.indexOf = function (key) {
  4197. for (var i = 0; i !== this.count; i++) {
  4198. if (this._keys[i] === key) {
  4199. return i;
  4200. }
  4201. }
  4202. return -1;
  4203. };
  4204. SmartCollection.prototype.item = function (key) {
  4205. return this.items[key];
  4206. };
  4207. SmartCollection.prototype.getAllKeys = function () {
  4208. if (this.count > 0) {
  4209. var keys = new Array(this.count);
  4210. for (var i = 0; i < this.count; i++) {
  4211. keys[i] = this._keys[i];
  4212. }
  4213. return keys;
  4214. }
  4215. else {
  4216. return undefined;
  4217. }
  4218. };
  4219. SmartCollection.prototype.getKeyByIndex = function (index) {
  4220. if (index < this.count && index > -1) {
  4221. return this._keys[index];
  4222. }
  4223. else {
  4224. return undefined;
  4225. }
  4226. };
  4227. SmartCollection.prototype.getItemByIndex = function (index) {
  4228. if (index < this.count && index > -1) {
  4229. return this.items[this._keys[index]];
  4230. }
  4231. else {
  4232. return undefined;
  4233. }
  4234. };
  4235. SmartCollection.prototype.empty = function () {
  4236. if (this.count > 0) {
  4237. this.count = 0;
  4238. this.items = {};
  4239. this._keys = new Array(this._initialCapacity);
  4240. }
  4241. };
  4242. SmartCollection.prototype.forEach = function (block) {
  4243. var key;
  4244. for (key in this.items) {
  4245. if (this.items.hasOwnProperty(key)) {
  4246. block(this.items[key]);
  4247. }
  4248. }
  4249. };
  4250. return SmartCollection;
  4251. })();
  4252. BABYLON.SmartCollection = SmartCollection;
  4253. })(BABYLON || (BABYLON = {}));
  4254. var BABYLON;
  4255. (function (BABYLON) {
  4256. // Screenshots
  4257. var screenshotCanvas;
  4258. var cloneValue = function (source, destinationObject) {
  4259. if (!source)
  4260. return null;
  4261. if (source instanceof BABYLON.Mesh) {
  4262. return null;
  4263. }
  4264. if (source instanceof BABYLON.SubMesh) {
  4265. return source.clone(destinationObject);
  4266. }
  4267. else if (source.clone) {
  4268. return source.clone();
  4269. }
  4270. return null;
  4271. };
  4272. var Tools = (function () {
  4273. function Tools() {
  4274. }
  4275. Tools.ToHex = function (i) {
  4276. var str = i.toString(16);
  4277. if (i <= 15) {
  4278. return ("0" + str).toUpperCase();
  4279. }
  4280. return str.toUpperCase();
  4281. };
  4282. Tools.SetImmediate = function (action) {
  4283. if (window.setImmediate) {
  4284. window.setImmediate(action);
  4285. }
  4286. else {
  4287. setTimeout(action, 1);
  4288. }
  4289. };
  4290. Tools.IsExponantOfTwo = function (value) {
  4291. var count = 1;
  4292. do {
  4293. count *= 2;
  4294. } while (count < value);
  4295. return count === value;
  4296. };
  4297. Tools.GetExponantOfTwo = function (value, max) {
  4298. var count = 1;
  4299. do {
  4300. count *= 2;
  4301. } while (count < value);
  4302. if (count > max)
  4303. count = max;
  4304. return count;
  4305. };
  4306. Tools.GetFilename = function (path) {
  4307. var index = path.lastIndexOf("/");
  4308. if (index < 0)
  4309. return path;
  4310. return path.substring(index + 1);
  4311. };
  4312. Tools.GetDOMTextContent = function (element) {
  4313. var result = "";
  4314. var child = element.firstChild;
  4315. while (child) {
  4316. if (child.nodeType === 3) {
  4317. result += child.textContent;
  4318. }
  4319. child = child.nextSibling;
  4320. }
  4321. return result;
  4322. };
  4323. Tools.ToDegrees = function (angle) {
  4324. return angle * 180 / Math.PI;
  4325. };
  4326. Tools.ToRadians = function (angle) {
  4327. return angle * Math.PI / 180;
  4328. };
  4329. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4330. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4331. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4332. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4333. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4334. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4335. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4336. }
  4337. return {
  4338. minimum: minimum,
  4339. maximum: maximum
  4340. };
  4341. };
  4342. Tools.ExtractMinAndMax = function (positions, start, count) {
  4343. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4344. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4345. for (var index = start; index < start + count; index++) {
  4346. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4347. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4348. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4349. }
  4350. return {
  4351. minimum: minimum,
  4352. maximum: maximum
  4353. };
  4354. };
  4355. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4356. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4357. return undefined;
  4358. return Array.isArray(obj) ? obj : [obj];
  4359. };
  4360. // Misc.
  4361. Tools.GetPointerPrefix = function () {
  4362. var eventPrefix = "pointer";
  4363. // Check if hand.js is referenced or if the browser natively supports pointer events
  4364. if (!navigator.pointerEnabled) {
  4365. eventPrefix = "mouse";
  4366. }
  4367. return eventPrefix;
  4368. };
  4369. Tools.QueueNewFrame = function (func) {
  4370. if (window.requestAnimationFrame)
  4371. window.requestAnimationFrame(func);
  4372. else if (window.msRequestAnimationFrame)
  4373. window.msRequestAnimationFrame(func);
  4374. else if (window.webkitRequestAnimationFrame)
  4375. window.webkitRequestAnimationFrame(func);
  4376. else if (window.mozRequestAnimationFrame)
  4377. window.mozRequestAnimationFrame(func);
  4378. else if (window.oRequestAnimationFrame)
  4379. window.oRequestAnimationFrame(func);
  4380. else {
  4381. window.setTimeout(func, 16);
  4382. }
  4383. };
  4384. Tools.RequestFullscreen = function (element) {
  4385. if (element.requestFullscreen)
  4386. element.requestFullscreen();
  4387. else if (element.msRequestFullscreen)
  4388. element.msRequestFullscreen();
  4389. else if (element.webkitRequestFullscreen)
  4390. element.webkitRequestFullscreen();
  4391. else if (element.mozRequestFullScreen)
  4392. element.mozRequestFullScreen();
  4393. };
  4394. Tools.ExitFullscreen = function () {
  4395. if (document.exitFullscreen) {
  4396. document.exitFullscreen();
  4397. }
  4398. else if (document.mozCancelFullScreen) {
  4399. document.mozCancelFullScreen();
  4400. }
  4401. else if (document.webkitCancelFullScreen) {
  4402. document.webkitCancelFullScreen();
  4403. }
  4404. else if (document.msCancelFullScreen) {
  4405. document.msCancelFullScreen();
  4406. }
  4407. };
  4408. // External files
  4409. Tools.CleanUrl = function (url) {
  4410. url = url.replace(/#/mg, "%23");
  4411. return url;
  4412. };
  4413. Tools.LoadImage = function (url, onload, onerror, database) {
  4414. url = Tools.CleanUrl(url);
  4415. var img = new Image();
  4416. if (url.substr(0, 5) !== "data:")
  4417. img.crossOrigin = 'anonymous';
  4418. img.onload = function () {
  4419. onload(img);
  4420. };
  4421. img.onerror = function (err) {
  4422. Tools.Error("Error while trying to load texture: " + url);
  4423. 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";
  4424. onload(img);
  4425. };
  4426. var noIndexedDB = function () {
  4427. img.src = url;
  4428. };
  4429. var loadFromIndexedDB = function () {
  4430. database.loadImageFromDB(url, img);
  4431. };
  4432. //ANY database to do!
  4433. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4434. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4435. }
  4436. else {
  4437. if (url.indexOf("file:") === -1) {
  4438. noIndexedDB();
  4439. }
  4440. else {
  4441. try {
  4442. var textureName = url.substring(5);
  4443. var blobURL;
  4444. try {
  4445. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4446. }
  4447. catch (ex) {
  4448. // Chrome doesn't support oneTimeOnly parameter
  4449. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4450. }
  4451. img.src = blobURL;
  4452. }
  4453. catch (e) {
  4454. img.src = null;
  4455. }
  4456. }
  4457. }
  4458. return img;
  4459. };
  4460. //ANY
  4461. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4462. url = Tools.CleanUrl(url);
  4463. var noIndexedDB = function () {
  4464. var request = new XMLHttpRequest();
  4465. var loadUrl = Tools.BaseUrl + url;
  4466. request.open('GET', loadUrl, true);
  4467. if (useArrayBuffer) {
  4468. request.responseType = "arraybuffer";
  4469. }
  4470. request.onprogress = progressCallBack;
  4471. request.onreadystatechange = function () {
  4472. if (request.readyState === 4) {
  4473. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4474. callback(!useArrayBuffer ? request.responseText : request.response);
  4475. }
  4476. else {
  4477. if (onError) {
  4478. onError();
  4479. }
  4480. else {
  4481. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4482. }
  4483. }
  4484. }
  4485. };
  4486. request.send(null);
  4487. };
  4488. var loadFromIndexedDB = function () {
  4489. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4490. };
  4491. if (url.indexOf("file:") !== -1) {
  4492. var fileName = url.substring(5);
  4493. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4494. }
  4495. else {
  4496. // Caching all files
  4497. if (database && database.enableSceneOffline) {
  4498. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4499. }
  4500. else {
  4501. noIndexedDB();
  4502. }
  4503. }
  4504. };
  4505. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4506. var reader = new FileReader();
  4507. reader.onload = function (e) {
  4508. //target doesn't have result from ts 1.3
  4509. callback(e.target['result']);
  4510. };
  4511. reader.onprogress = progressCallback;
  4512. reader.readAsDataURL(fileToLoad);
  4513. };
  4514. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4515. var reader = new FileReader();
  4516. reader.onerror = function (e) {
  4517. Tools.Log("Error while reading file: " + fileToLoad.name);
  4518. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4519. };
  4520. reader.onload = function (e) {
  4521. //target doesn't have result from ts 1.3
  4522. callback(e.target['result']);
  4523. };
  4524. reader.onprogress = progressCallBack;
  4525. if (!useArrayBuffer) {
  4526. // Asynchronous read
  4527. reader.readAsText(fileToLoad);
  4528. }
  4529. else {
  4530. reader.readAsArrayBuffer(fileToLoad);
  4531. }
  4532. };
  4533. // Misc.
  4534. Tools.Clamp = function (value, min, max) {
  4535. if (min === void 0) { min = 0; }
  4536. if (max === void 0) { max = 1; }
  4537. return Math.min(max, Math.max(min, value));
  4538. };
  4539. // Returns -1 when value is a negative number and
  4540. // +1 when value is a positive number.
  4541. Tools.Sign = function (value) {
  4542. value = +value; // convert to a number
  4543. if (value === 0 || isNaN(value))
  4544. return value;
  4545. return value > 0 ? 1 : -1;
  4546. };
  4547. Tools.Format = function (value, decimals) {
  4548. if (decimals === void 0) { decimals = 2; }
  4549. return value.toFixed(decimals);
  4550. };
  4551. Tools.CheckExtends = function (v, min, max) {
  4552. if (v.x < min.x)
  4553. min.x = v.x;
  4554. if (v.y < min.y)
  4555. min.y = v.y;
  4556. if (v.z < min.z)
  4557. min.z = v.z;
  4558. if (v.x > max.x)
  4559. max.x = v.x;
  4560. if (v.y > max.y)
  4561. max.y = v.y;
  4562. if (v.z > max.z)
  4563. max.z = v.z;
  4564. };
  4565. Tools.WithinEpsilon = function (a, b, epsilon) {
  4566. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4567. var num = a - b;
  4568. return -epsilon <= num && num <= epsilon;
  4569. };
  4570. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4571. for (var prop in source) {
  4572. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4573. continue;
  4574. }
  4575. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4576. continue;
  4577. }
  4578. var sourceValue = source[prop];
  4579. var typeOfSourceValue = typeof sourceValue;
  4580. if (typeOfSourceValue === "function") {
  4581. continue;
  4582. }
  4583. if (typeOfSourceValue === "object") {
  4584. if (sourceValue instanceof Array) {
  4585. destination[prop] = [];
  4586. if (sourceValue.length > 0) {
  4587. if (typeof sourceValue[0] == "object") {
  4588. for (var index = 0; index < sourceValue.length; index++) {
  4589. var clonedValue = cloneValue(sourceValue[index], destination);
  4590. if (destination[prop].indexOf(clonedValue) === -1) {
  4591. destination[prop].push(clonedValue);
  4592. }
  4593. }
  4594. }
  4595. else {
  4596. destination[prop] = sourceValue.slice(0);
  4597. }
  4598. }
  4599. }
  4600. else {
  4601. destination[prop] = cloneValue(sourceValue, destination);
  4602. }
  4603. }
  4604. else {
  4605. destination[prop] = sourceValue;
  4606. }
  4607. }
  4608. };
  4609. Tools.IsEmpty = function (obj) {
  4610. for (var i in obj) {
  4611. return false;
  4612. }
  4613. return true;
  4614. };
  4615. Tools.RegisterTopRootEvents = function (events) {
  4616. for (var index = 0; index < events.length; index++) {
  4617. var event = events[index];
  4618. window.addEventListener(event.name, event.handler, false);
  4619. try {
  4620. if (window.parent) {
  4621. window.parent.addEventListener(event.name, event.handler, false);
  4622. }
  4623. }
  4624. catch (e) {
  4625. }
  4626. }
  4627. };
  4628. Tools.UnregisterTopRootEvents = function (events) {
  4629. for (var index = 0; index < events.length; index++) {
  4630. var event = events[index];
  4631. window.removeEventListener(event.name, event.handler);
  4632. try {
  4633. if (window.parent) {
  4634. window.parent.removeEventListener(event.name, event.handler);
  4635. }
  4636. }
  4637. catch (e) {
  4638. }
  4639. }
  4640. };
  4641. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4642. // Read the contents of the framebuffer
  4643. var numberOfChannelsByLine = width * 4;
  4644. var halfHeight = height / 2;
  4645. //Reading datas from WebGL
  4646. var data = engine.readPixels(0, 0, width, height);
  4647. //To flip image on Y axis.
  4648. for (var i = 0; i < halfHeight; i++) {
  4649. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4650. var currentCell = j + i * numberOfChannelsByLine;
  4651. var targetLine = height - i - 1;
  4652. var targetCell = j + targetLine * numberOfChannelsByLine;
  4653. var temp = data[currentCell];
  4654. data[currentCell] = data[targetCell];
  4655. data[targetCell] = temp;
  4656. }
  4657. }
  4658. // Create a 2D canvas to store the result
  4659. if (!screenshotCanvas) {
  4660. screenshotCanvas = document.createElement('canvas');
  4661. }
  4662. screenshotCanvas.width = width;
  4663. screenshotCanvas.height = height;
  4664. var context = screenshotCanvas.getContext('2d');
  4665. // Copy the pixels to a 2D canvas
  4666. var imageData = context.createImageData(width, height);
  4667. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4668. var castData = imageData.data;
  4669. castData.set(data);
  4670. context.putImageData(imageData, 0, 0);
  4671. var base64Image = screenshotCanvas.toDataURL();
  4672. if (successCallback) {
  4673. successCallback(base64Image);
  4674. }
  4675. else {
  4676. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4677. if (("download" in document.createElement("a"))) {
  4678. var a = window.document.createElement("a");
  4679. a.href = base64Image;
  4680. var date = new Date();
  4681. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4682. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4683. window.document.body.appendChild(a);
  4684. a.addEventListener("click", function () {
  4685. a.parentElement.removeChild(a);
  4686. });
  4687. a.click();
  4688. }
  4689. else {
  4690. var newWindow = window.open("");
  4691. var img = newWindow.document.createElement("img");
  4692. img.src = base64Image;
  4693. newWindow.document.body.appendChild(img);
  4694. }
  4695. }
  4696. };
  4697. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4698. var width;
  4699. var height;
  4700. var scene = camera.getScene();
  4701. var previousCamera = null;
  4702. if (scene.activeCamera !== camera) {
  4703. previousCamera = scene.activeCamera;
  4704. scene.activeCamera = camera;
  4705. }
  4706. //If a precision value is specified
  4707. if (size.precision) {
  4708. width = Math.round(engine.getRenderWidth() * size.precision);
  4709. height = Math.round(width / engine.getAspectRatio(camera));
  4710. size = { width: width, height: height };
  4711. }
  4712. else if (size.width && size.height) {
  4713. width = size.width;
  4714. height = size.height;
  4715. }
  4716. else if (size.width && !size.height) {
  4717. width = size.width;
  4718. height = Math.round(width / engine.getAspectRatio(camera));
  4719. size = { width: width, height: height };
  4720. }
  4721. else if (size.height && !size.width) {
  4722. height = size.height;
  4723. width = Math.round(height * engine.getAspectRatio(camera));
  4724. size = { width: width, height: height };
  4725. }
  4726. else if (!isNaN(size)) {
  4727. height = size;
  4728. width = size;
  4729. }
  4730. else {
  4731. Tools.Error("Invalid 'size' parameter !");
  4732. return;
  4733. }
  4734. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4735. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4736. texture.renderList = scene.meshes;
  4737. texture.onAfterRender = function () {
  4738. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4739. };
  4740. scene.incrementRenderId();
  4741. texture.render(true);
  4742. texture.dispose();
  4743. if (previousCamera) {
  4744. scene.activeCamera = previousCamera;
  4745. }
  4746. };
  4747. // XHR response validator for local file scenario
  4748. Tools.ValidateXHRData = function (xhr, dataType) {
  4749. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4750. if (dataType === void 0) { dataType = 7; }
  4751. try {
  4752. if (dataType & 1) {
  4753. if (xhr.responseText && xhr.responseText.length > 0) {
  4754. return true;
  4755. }
  4756. else if (dataType === 1) {
  4757. return false;
  4758. }
  4759. }
  4760. if (dataType & 2) {
  4761. // Check header width and height since there is no "TGA" magic number
  4762. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4763. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4764. return true;
  4765. }
  4766. else if (dataType === 2) {
  4767. return false;
  4768. }
  4769. }
  4770. if (dataType & 4) {
  4771. // Check for the "DDS" magic number
  4772. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4773. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4774. return true;
  4775. }
  4776. else {
  4777. return false;
  4778. }
  4779. }
  4780. }
  4781. catch (e) {
  4782. }
  4783. return false;
  4784. };
  4785. Object.defineProperty(Tools, "NoneLogLevel", {
  4786. get: function () {
  4787. return Tools._NoneLogLevel;
  4788. },
  4789. enumerable: true,
  4790. configurable: true
  4791. });
  4792. Object.defineProperty(Tools, "MessageLogLevel", {
  4793. get: function () {
  4794. return Tools._MessageLogLevel;
  4795. },
  4796. enumerable: true,
  4797. configurable: true
  4798. });
  4799. Object.defineProperty(Tools, "WarningLogLevel", {
  4800. get: function () {
  4801. return Tools._WarningLogLevel;
  4802. },
  4803. enumerable: true,
  4804. configurable: true
  4805. });
  4806. Object.defineProperty(Tools, "ErrorLogLevel", {
  4807. get: function () {
  4808. return Tools._ErrorLogLevel;
  4809. },
  4810. enumerable: true,
  4811. configurable: true
  4812. });
  4813. Object.defineProperty(Tools, "AllLogLevel", {
  4814. get: function () {
  4815. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4816. },
  4817. enumerable: true,
  4818. configurable: true
  4819. });
  4820. Tools._AddLogEntry = function (entry) {
  4821. Tools._LogCache = entry + Tools._LogCache;
  4822. if (Tools.OnNewCacheEntry) {
  4823. Tools.OnNewCacheEntry(entry);
  4824. }
  4825. };
  4826. Tools._FormatMessage = function (message) {
  4827. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4828. var date = new Date();
  4829. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4830. };
  4831. Tools._LogDisabled = function (message) {
  4832. // nothing to do
  4833. };
  4834. Tools._LogEnabled = function (message) {
  4835. var formattedMessage = Tools._FormatMessage(message);
  4836. console.log("BJS - " + formattedMessage);
  4837. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4838. Tools._AddLogEntry(entry);
  4839. };
  4840. Tools._WarnDisabled = function (message) {
  4841. // nothing to do
  4842. };
  4843. Tools._WarnEnabled = function (message) {
  4844. var formattedMessage = Tools._FormatMessage(message);
  4845. console.warn("BJS - " + formattedMessage);
  4846. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4847. Tools._AddLogEntry(entry);
  4848. };
  4849. Tools._ErrorDisabled = function (message) {
  4850. // nothing to do
  4851. };
  4852. Tools._ErrorEnabled = function (message) {
  4853. Tools.errorsCount++;
  4854. var formattedMessage = Tools._FormatMessage(message);
  4855. console.error("BJS - " + formattedMessage);
  4856. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4857. Tools._AddLogEntry(entry);
  4858. };
  4859. Object.defineProperty(Tools, "LogCache", {
  4860. get: function () {
  4861. return Tools._LogCache;
  4862. },
  4863. enumerable: true,
  4864. configurable: true
  4865. });
  4866. Tools.ClearLogCache = function () {
  4867. Tools._LogCache = "";
  4868. Tools.errorsCount = 0;
  4869. };
  4870. Object.defineProperty(Tools, "LogLevels", {
  4871. set: function (level) {
  4872. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4873. Tools.Log = Tools._LogEnabled;
  4874. }
  4875. else {
  4876. Tools.Log = Tools._LogDisabled;
  4877. }
  4878. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4879. Tools.Warn = Tools._WarnEnabled;
  4880. }
  4881. else {
  4882. Tools.Warn = Tools._WarnDisabled;
  4883. }
  4884. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4885. Tools.Error = Tools._ErrorEnabled;
  4886. }
  4887. else {
  4888. Tools.Error = Tools._ErrorDisabled;
  4889. }
  4890. },
  4891. enumerable: true,
  4892. configurable: true
  4893. });
  4894. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4895. get: function () {
  4896. return Tools._PerformanceNoneLogLevel;
  4897. },
  4898. enumerable: true,
  4899. configurable: true
  4900. });
  4901. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4902. get: function () {
  4903. return Tools._PerformanceUserMarkLogLevel;
  4904. },
  4905. enumerable: true,
  4906. configurable: true
  4907. });
  4908. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4909. get: function () {
  4910. return Tools._PerformanceConsoleLogLevel;
  4911. },
  4912. enumerable: true,
  4913. configurable: true
  4914. });
  4915. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4916. set: function (level) {
  4917. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4918. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4919. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4920. return;
  4921. }
  4922. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4923. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4924. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4925. return;
  4926. }
  4927. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4928. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4929. },
  4930. enumerable: true,
  4931. configurable: true
  4932. });
  4933. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4934. };
  4935. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4936. };
  4937. Tools._StartUserMark = function (counterName, condition) {
  4938. if (condition === void 0) { condition = true; }
  4939. if (!condition || !Tools._performance.mark) {
  4940. return;
  4941. }
  4942. Tools._performance.mark(counterName + "-Begin");
  4943. };
  4944. Tools._EndUserMark = function (counterName, condition) {
  4945. if (condition === void 0) { condition = true; }
  4946. if (!condition || !Tools._performance.mark) {
  4947. return;
  4948. }
  4949. Tools._performance.mark(counterName + "-End");
  4950. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4951. };
  4952. Tools._StartPerformanceConsole = function (counterName, condition) {
  4953. if (condition === void 0) { condition = true; }
  4954. if (!condition) {
  4955. return;
  4956. }
  4957. Tools._StartUserMark(counterName, condition);
  4958. if (console.time) {
  4959. console.time(counterName);
  4960. }
  4961. };
  4962. Tools._EndPerformanceConsole = function (counterName, condition) {
  4963. if (condition === void 0) { condition = true; }
  4964. if (!condition) {
  4965. return;
  4966. }
  4967. Tools._EndUserMark(counterName, condition);
  4968. if (console.time) {
  4969. console.timeEnd(counterName);
  4970. }
  4971. };
  4972. Object.defineProperty(Tools, "Now", {
  4973. get: function () {
  4974. if (window.performance && window.performance.now) {
  4975. return window.performance.now();
  4976. }
  4977. return new Date().getTime();
  4978. },
  4979. enumerable: true,
  4980. configurable: true
  4981. });
  4982. // Deprecated
  4983. Tools.GetFps = function () {
  4984. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4985. return 0;
  4986. };
  4987. Tools.BaseUrl = "";
  4988. // Logs
  4989. Tools._NoneLogLevel = 0;
  4990. Tools._MessageLogLevel = 1;
  4991. Tools._WarningLogLevel = 2;
  4992. Tools._ErrorLogLevel = 4;
  4993. Tools._LogCache = "";
  4994. Tools.errorsCount = 0;
  4995. Tools.Log = Tools._LogEnabled;
  4996. Tools.Warn = Tools._WarnEnabled;
  4997. Tools.Error = Tools._ErrorEnabled;
  4998. // Performances
  4999. Tools._PerformanceNoneLogLevel = 0;
  5000. Tools._PerformanceUserMarkLogLevel = 1;
  5001. Tools._PerformanceConsoleLogLevel = 2;
  5002. Tools._performance = window.performance;
  5003. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5004. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5005. return Tools;
  5006. })();
  5007. BABYLON.Tools = Tools;
  5008. /**
  5009. * An implementation of a loop for asynchronous functions.
  5010. */
  5011. var AsyncLoop = (function () {
  5012. /**
  5013. * Constroctor.
  5014. * @param iterations the number of iterations.
  5015. * @param _fn the function to run each iteration
  5016. * @param _successCallback the callback that will be called upon succesful execution
  5017. * @param offset starting offset.
  5018. */
  5019. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5020. if (offset === void 0) { offset = 0; }
  5021. this.iterations = iterations;
  5022. this._fn = _fn;
  5023. this._successCallback = _successCallback;
  5024. this.index = offset - 1;
  5025. this._done = false;
  5026. }
  5027. /**
  5028. * Execute the next iteration. Must be called after the last iteration was finished.
  5029. */
  5030. AsyncLoop.prototype.executeNext = function () {
  5031. if (!this._done) {
  5032. if (this.index + 1 < this.iterations) {
  5033. ++this.index;
  5034. this._fn(this);
  5035. }
  5036. else {
  5037. this.breakLoop();
  5038. }
  5039. }
  5040. };
  5041. /**
  5042. * Break the loop and run the success callback.
  5043. */
  5044. AsyncLoop.prototype.breakLoop = function () {
  5045. this._done = true;
  5046. this._successCallback();
  5047. };
  5048. /**
  5049. * Helper function
  5050. */
  5051. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5052. if (offset === void 0) { offset = 0; }
  5053. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5054. loop.executeNext();
  5055. return loop;
  5056. };
  5057. /**
  5058. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5059. * @param iterations total number of iterations
  5060. * @param syncedIterations number of synchronous iterations in each async iteration.
  5061. * @param fn the function to call each iteration.
  5062. * @param callback a success call back that will be called when iterating stops.
  5063. * @param breakFunction a break condition (optional)
  5064. * @param timeout timeout settings for the setTimeout function. default - 0.
  5065. * @constructor
  5066. */
  5067. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5068. if (timeout === void 0) { timeout = 0; }
  5069. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5070. if (breakFunction && breakFunction())
  5071. loop.breakLoop();
  5072. else {
  5073. setTimeout(function () {
  5074. for (var i = 0; i < syncedIterations; ++i) {
  5075. var iteration = (loop.index * syncedIterations) + i;
  5076. if (iteration >= iterations)
  5077. break;
  5078. fn(iteration);
  5079. if (breakFunction && breakFunction()) {
  5080. loop.breakLoop();
  5081. break;
  5082. }
  5083. }
  5084. loop.executeNext();
  5085. }, timeout);
  5086. }
  5087. }, callback);
  5088. };
  5089. return AsyncLoop;
  5090. })();
  5091. BABYLON.AsyncLoop = AsyncLoop;
  5092. })(BABYLON || (BABYLON = {}));
  5093. var BABYLON;
  5094. (function (BABYLON) {
  5095. var _DepthCullingState = (function () {
  5096. function _DepthCullingState() {
  5097. this._isDepthTestDirty = false;
  5098. this._isDepthMaskDirty = false;
  5099. this._isDepthFuncDirty = false;
  5100. this._isCullFaceDirty = false;
  5101. this._isCullDirty = false;
  5102. this._isZOffsetDirty = false;
  5103. }
  5104. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5105. get: function () {
  5106. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5107. },
  5108. enumerable: true,
  5109. configurable: true
  5110. });
  5111. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5112. get: function () {
  5113. return this._zOffset;
  5114. },
  5115. set: function (value) {
  5116. if (this._zOffset === value) {
  5117. return;
  5118. }
  5119. this._zOffset = value;
  5120. this._isZOffsetDirty = true;
  5121. },
  5122. enumerable: true,
  5123. configurable: true
  5124. });
  5125. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5126. get: function () {
  5127. return this._cullFace;
  5128. },
  5129. set: function (value) {
  5130. if (this._cullFace === value) {
  5131. return;
  5132. }
  5133. this._cullFace = value;
  5134. this._isCullFaceDirty = true;
  5135. },
  5136. enumerable: true,
  5137. configurable: true
  5138. });
  5139. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5140. get: function () {
  5141. return this._cull;
  5142. },
  5143. set: function (value) {
  5144. if (this._cull === value) {
  5145. return;
  5146. }
  5147. this._cull = value;
  5148. this._isCullDirty = true;
  5149. },
  5150. enumerable: true,
  5151. configurable: true
  5152. });
  5153. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5154. get: function () {
  5155. return this._depthFunc;
  5156. },
  5157. set: function (value) {
  5158. if (this._depthFunc === value) {
  5159. return;
  5160. }
  5161. this._depthFunc = value;
  5162. this._isDepthFuncDirty = true;
  5163. },
  5164. enumerable: true,
  5165. configurable: true
  5166. });
  5167. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5168. get: function () {
  5169. return this._depthMask;
  5170. },
  5171. set: function (value) {
  5172. if (this._depthMask === value) {
  5173. return;
  5174. }
  5175. this._depthMask = value;
  5176. this._isDepthMaskDirty = true;
  5177. },
  5178. enumerable: true,
  5179. configurable: true
  5180. });
  5181. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5182. get: function () {
  5183. return this._depthTest;
  5184. },
  5185. set: function (value) {
  5186. if (this._depthTest === value) {
  5187. return;
  5188. }
  5189. this._depthTest = value;
  5190. this._isDepthTestDirty = true;
  5191. },
  5192. enumerable: true,
  5193. configurable: true
  5194. });
  5195. _DepthCullingState.prototype.reset = function () {
  5196. this._depthMask = true;
  5197. this._depthTest = true;
  5198. this._depthFunc = null;
  5199. this._cull = null;
  5200. this._cullFace = null;
  5201. this._zOffset = 0;
  5202. this._isDepthTestDirty = true;
  5203. this._isDepthMaskDirty = true;
  5204. this._isDepthFuncDirty = false;
  5205. this._isCullFaceDirty = false;
  5206. this._isCullDirty = false;
  5207. this._isZOffsetDirty = false;
  5208. };
  5209. _DepthCullingState.prototype.apply = function (gl) {
  5210. if (!this.isDirty) {
  5211. return;
  5212. }
  5213. // Cull
  5214. if (this._isCullDirty) {
  5215. if (this.cull) {
  5216. gl.enable(gl.CULL_FACE);
  5217. }
  5218. else {
  5219. gl.disable(gl.CULL_FACE);
  5220. }
  5221. this._isCullDirty = false;
  5222. }
  5223. // Cull face
  5224. if (this._isCullFaceDirty) {
  5225. gl.cullFace(this.cullFace);
  5226. this._isCullFaceDirty = false;
  5227. }
  5228. // Depth mask
  5229. if (this._isDepthMaskDirty) {
  5230. gl.depthMask(this.depthMask);
  5231. this._isDepthMaskDirty = false;
  5232. }
  5233. // Depth test
  5234. if (this._isDepthTestDirty) {
  5235. if (this.depthTest) {
  5236. gl.enable(gl.DEPTH_TEST);
  5237. }
  5238. else {
  5239. gl.disable(gl.DEPTH_TEST);
  5240. }
  5241. this._isDepthTestDirty = false;
  5242. }
  5243. // Depth func
  5244. if (this._isDepthFuncDirty) {
  5245. gl.depthFunc(this.depthFunc);
  5246. this._isDepthFuncDirty = false;
  5247. }
  5248. // zOffset
  5249. if (this._isZOffsetDirty) {
  5250. if (this.zOffset) {
  5251. gl.enable(gl.POLYGON_OFFSET_FILL);
  5252. gl.polygonOffset(this.zOffset, 0);
  5253. }
  5254. else {
  5255. gl.disable(gl.POLYGON_OFFSET_FILL);
  5256. }
  5257. this._isZOffsetDirty = false;
  5258. }
  5259. };
  5260. return _DepthCullingState;
  5261. })();
  5262. BABYLON._DepthCullingState = _DepthCullingState;
  5263. var _AlphaState = (function () {
  5264. function _AlphaState() {
  5265. this._isAlphaBlendDirty = false;
  5266. this._isBlendFunctionParametersDirty = false;
  5267. this._alphaBlend = false;
  5268. this._blendFunctionParameters = new Array(4);
  5269. }
  5270. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5271. get: function () {
  5272. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5273. },
  5274. enumerable: true,
  5275. configurable: true
  5276. });
  5277. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5278. get: function () {
  5279. return this._alphaBlend;
  5280. },
  5281. set: function (value) {
  5282. if (this._alphaBlend === value) {
  5283. return;
  5284. }
  5285. this._alphaBlend = value;
  5286. this._isAlphaBlendDirty = true;
  5287. },
  5288. enumerable: true,
  5289. configurable: true
  5290. });
  5291. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5292. if (this._blendFunctionParameters[0] === value0 &&
  5293. this._blendFunctionParameters[1] === value1 &&
  5294. this._blendFunctionParameters[2] === value2 &&
  5295. this._blendFunctionParameters[3] === value3) {
  5296. return;
  5297. }
  5298. this._blendFunctionParameters[0] = value0;
  5299. this._blendFunctionParameters[1] = value1;
  5300. this._blendFunctionParameters[2] = value2;
  5301. this._blendFunctionParameters[3] = value3;
  5302. this._isBlendFunctionParametersDirty = true;
  5303. };
  5304. _AlphaState.prototype.reset = function () {
  5305. this._alphaBlend = false;
  5306. this._blendFunctionParameters[0] = null;
  5307. this._blendFunctionParameters[1] = null;
  5308. this._blendFunctionParameters[2] = null;
  5309. this._blendFunctionParameters[3] = null;
  5310. this._isAlphaBlendDirty = true;
  5311. this._isBlendFunctionParametersDirty = false;
  5312. };
  5313. _AlphaState.prototype.apply = function (gl) {
  5314. if (!this.isDirty) {
  5315. return;
  5316. }
  5317. // Alpha blend
  5318. if (this._isAlphaBlendDirty) {
  5319. if (this._alphaBlend) {
  5320. gl.enable(gl.BLEND);
  5321. }
  5322. else {
  5323. gl.disable(gl.BLEND);
  5324. }
  5325. this._isAlphaBlendDirty = false;
  5326. }
  5327. // Alpha function
  5328. if (this._isBlendFunctionParametersDirty) {
  5329. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5330. this._isBlendFunctionParametersDirty = false;
  5331. }
  5332. };
  5333. return _AlphaState;
  5334. })();
  5335. BABYLON._AlphaState = _AlphaState;
  5336. var compileShader = function (gl, source, type, defines) {
  5337. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5338. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5339. gl.compileShader(shader);
  5340. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5341. throw new Error(gl.getShaderInfoLog(shader));
  5342. }
  5343. return shader;
  5344. };
  5345. var getWebGLTextureType = function (gl, type) {
  5346. var textureType = gl.UNSIGNED_BYTE;
  5347. if (type === Engine.TEXTURETYPE_FLOAT)
  5348. textureType = gl.FLOAT;
  5349. return textureType;
  5350. };
  5351. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5352. var magFilter = gl.NEAREST;
  5353. var minFilter = gl.NEAREST;
  5354. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5355. magFilter = gl.LINEAR;
  5356. if (generateMipMaps) {
  5357. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5358. }
  5359. else {
  5360. minFilter = gl.LINEAR;
  5361. }
  5362. }
  5363. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5364. magFilter = gl.LINEAR;
  5365. if (generateMipMaps) {
  5366. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5367. }
  5368. else {
  5369. minFilter = gl.LINEAR;
  5370. }
  5371. }
  5372. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5373. magFilter = gl.NEAREST;
  5374. if (generateMipMaps) {
  5375. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5376. }
  5377. else {
  5378. minFilter = gl.NEAREST;
  5379. }
  5380. }
  5381. return {
  5382. min: minFilter,
  5383. mag: magFilter
  5384. };
  5385. };
  5386. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5387. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5388. var engine = scene.getEngine();
  5389. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5390. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5391. gl.bindTexture(gl.TEXTURE_2D, texture);
  5392. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5393. texture._baseWidth = width;
  5394. texture._baseHeight = height;
  5395. texture._width = potWidth;
  5396. texture._height = potHeight;
  5397. texture.isReady = true;
  5398. processFunction(potWidth, potHeight);
  5399. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5400. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5401. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5402. if (!noMipmap && !isCompressed) {
  5403. gl.generateMipmap(gl.TEXTURE_2D);
  5404. }
  5405. gl.bindTexture(gl.TEXTURE_2D, null);
  5406. engine._activeTexturesCache = [];
  5407. scene._removePendingData(texture);
  5408. };
  5409. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5410. var onload = function () {
  5411. loadedImages[index] = img;
  5412. loadedImages._internalCount++;
  5413. scene._removePendingData(img);
  5414. if (loadedImages._internalCount === 6) {
  5415. onfinish(loadedImages);
  5416. }
  5417. };
  5418. var onerror = function () {
  5419. scene._removePendingData(img);
  5420. };
  5421. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5422. scene._addPendingData(img);
  5423. };
  5424. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5425. var loadedImages = [];
  5426. loadedImages._internalCount = 0;
  5427. for (var index = 0; index < 6; index++) {
  5428. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5429. }
  5430. };
  5431. var EngineCapabilities = (function () {
  5432. function EngineCapabilities() {
  5433. }
  5434. return EngineCapabilities;
  5435. })();
  5436. BABYLON.EngineCapabilities = EngineCapabilities;
  5437. /**
  5438. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5439. */
  5440. var Engine = (function () {
  5441. /**
  5442. * @constructor
  5443. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5444. * @param {boolean} [antialias] - enable antialias
  5445. * @param options - further options to be sent to the getContext function
  5446. */
  5447. function Engine(canvas, antialias, options) {
  5448. var _this = this;
  5449. // Public members
  5450. this.isFullscreen = false;
  5451. this.isPointerLock = false;
  5452. this.cullBackFaces = true;
  5453. this.renderEvenInBackground = true;
  5454. // To enable/disable IDB support and avoid XHR on .manifest
  5455. this.enableOfflineSupport = true;
  5456. this.scenes = new Array();
  5457. this._windowIsBackground = false;
  5458. this._loadingDivBackgroundColor = "black";
  5459. this._drawCalls = 0;
  5460. this._renderingQueueLaunched = false;
  5461. this._activeRenderLoops = [];
  5462. // FPS
  5463. this.fpsRange = 60;
  5464. this.previousFramesDuration = [];
  5465. this.fps = 60;
  5466. this.deltaTime = 0;
  5467. // States
  5468. this._depthCullingState = new _DepthCullingState();
  5469. this._alphaState = new _AlphaState();
  5470. this._alphaMode = Engine.ALPHA_DISABLE;
  5471. // Cache
  5472. this._loadedTexturesCache = new Array();
  5473. this._activeTexturesCache = new Array();
  5474. this._compiledEffects = {};
  5475. this._uintIndicesCurrentlySet = false;
  5476. this._renderingCanvas = canvas;
  5477. options = options || {};
  5478. options.antialias = antialias;
  5479. if (options.preserveDrawingBuffer === undefined) {
  5480. options.preserveDrawingBuffer = false;
  5481. }
  5482. // GL
  5483. try {
  5484. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5485. }
  5486. catch (e) {
  5487. throw new Error("WebGL not supported");
  5488. }
  5489. if (!this._gl) {
  5490. throw new Error("WebGL not supported");
  5491. }
  5492. this._onBlur = function () {
  5493. _this._windowIsBackground = true;
  5494. };
  5495. this._onFocus = function () {
  5496. _this._windowIsBackground = false;
  5497. };
  5498. window.addEventListener("blur", this._onBlur);
  5499. window.addEventListener("focus", this._onFocus);
  5500. // Viewport
  5501. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5502. this.resize();
  5503. // Caps
  5504. this._caps = new EngineCapabilities();
  5505. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5506. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5507. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5508. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5509. // Infos
  5510. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5511. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5512. if (rendererInfo != null) {
  5513. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5514. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5515. }
  5516. if (!this._glVendor) {
  5517. this._glVendor = "Unknown vendor";
  5518. }
  5519. if (!this._glRenderer) {
  5520. this._glRenderer = "Unknown renderer";
  5521. }
  5522. // Extensions
  5523. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5524. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5525. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5526. 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');
  5527. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5528. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5529. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5530. this._caps.highPrecisionShaderSupported = true;
  5531. if (this._gl.getShaderPrecisionFormat) {
  5532. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5533. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5534. }
  5535. // Depth buffer
  5536. this.setDepthBuffer(true);
  5537. this.setDepthFunctionToLessOrEqual();
  5538. this.setDepthWrite(true);
  5539. // Fullscreen
  5540. this._onFullscreenChange = function () {
  5541. if (document.fullscreen !== undefined) {
  5542. _this.isFullscreen = document.fullscreen;
  5543. }
  5544. else if (document.mozFullScreen !== undefined) {
  5545. _this.isFullscreen = document.mozFullScreen;
  5546. }
  5547. else if (document.webkitIsFullScreen !== undefined) {
  5548. _this.isFullscreen = document.webkitIsFullScreen;
  5549. }
  5550. else if (document.msIsFullScreen !== undefined) {
  5551. _this.isFullscreen = document.msIsFullScreen;
  5552. }
  5553. // Pointer lock
  5554. if (_this.isFullscreen && _this._pointerLockRequested) {
  5555. canvas.requestPointerLock = canvas.requestPointerLock ||
  5556. canvas.msRequestPointerLock ||
  5557. canvas.mozRequestPointerLock ||
  5558. canvas.webkitRequestPointerLock;
  5559. if (canvas.requestPointerLock) {
  5560. canvas.requestPointerLock();
  5561. }
  5562. }
  5563. };
  5564. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5565. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5566. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5567. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5568. // Pointer lock
  5569. this._onPointerLockChange = function () {
  5570. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5571. document.webkitPointerLockElement === canvas ||
  5572. document.msPointerLockElement === canvas ||
  5573. document.pointerLockElement === canvas);
  5574. };
  5575. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5576. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5577. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5578. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5579. if (!Engine.audioEngine) {
  5580. Engine.audioEngine = new BABYLON.AudioEngine();
  5581. }
  5582. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5583. }
  5584. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5585. get: function () {
  5586. return Engine._ALPHA_DISABLE;
  5587. },
  5588. enumerable: true,
  5589. configurable: true
  5590. });
  5591. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5592. get: function () {
  5593. return Engine._ALPHA_ONEONE;
  5594. },
  5595. enumerable: true,
  5596. configurable: true
  5597. });
  5598. Object.defineProperty(Engine, "ALPHA_ADD", {
  5599. get: function () {
  5600. return Engine._ALPHA_ADD;
  5601. },
  5602. enumerable: true,
  5603. configurable: true
  5604. });
  5605. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5606. get: function () {
  5607. return Engine._ALPHA_COMBINE;
  5608. },
  5609. enumerable: true,
  5610. configurable: true
  5611. });
  5612. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5613. get: function () {
  5614. return Engine._ALPHA_SUBTRACT;
  5615. },
  5616. enumerable: true,
  5617. configurable: true
  5618. });
  5619. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5620. get: function () {
  5621. return Engine._ALPHA_MULTIPLY;
  5622. },
  5623. enumerable: true,
  5624. configurable: true
  5625. });
  5626. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5627. get: function () {
  5628. return Engine._ALPHA_MAXIMIZED;
  5629. },
  5630. enumerable: true,
  5631. configurable: true
  5632. });
  5633. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5634. get: function () {
  5635. return Engine._DELAYLOADSTATE_NONE;
  5636. },
  5637. enumerable: true,
  5638. configurable: true
  5639. });
  5640. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5641. get: function () {
  5642. return Engine._DELAYLOADSTATE_LOADED;
  5643. },
  5644. enumerable: true,
  5645. configurable: true
  5646. });
  5647. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5648. get: function () {
  5649. return Engine._DELAYLOADSTATE_LOADING;
  5650. },
  5651. enumerable: true,
  5652. configurable: true
  5653. });
  5654. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5655. get: function () {
  5656. return Engine._DELAYLOADSTATE_NOTLOADED;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5662. get: function () {
  5663. return Engine._TEXTUREFORMAT_ALPHA;
  5664. },
  5665. enumerable: true,
  5666. configurable: true
  5667. });
  5668. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5669. get: function () {
  5670. return Engine._TEXTUREFORMAT_LUMINANCE;
  5671. },
  5672. enumerable: true,
  5673. configurable: true
  5674. });
  5675. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5676. get: function () {
  5677. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5678. },
  5679. enumerable: true,
  5680. configurable: true
  5681. });
  5682. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5683. get: function () {
  5684. return Engine._TEXTUREFORMAT_RGB;
  5685. },
  5686. enumerable: true,
  5687. configurable: true
  5688. });
  5689. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5690. get: function () {
  5691. return Engine._TEXTUREFORMAT_RGBA;
  5692. },
  5693. enumerable: true,
  5694. configurable: true
  5695. });
  5696. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5697. get: function () {
  5698. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5699. },
  5700. enumerable: true,
  5701. configurable: true
  5702. });
  5703. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5704. get: function () {
  5705. return Engine._TEXTURETYPE_FLOAT;
  5706. },
  5707. enumerable: true,
  5708. configurable: true
  5709. });
  5710. Object.defineProperty(Engine, "Version", {
  5711. get: function () {
  5712. return "2.2.0-beta";
  5713. },
  5714. enumerable: true,
  5715. configurable: true
  5716. });
  5717. Engine.prototype._prepareWorkingCanvas = function () {
  5718. if (this._workingCanvas) {
  5719. return;
  5720. }
  5721. this._workingCanvas = document.createElement("canvas");
  5722. this._workingContext = this._workingCanvas.getContext("2d");
  5723. };
  5724. Engine.prototype.getGlInfo = function () {
  5725. return {
  5726. vendor: this._glVendor,
  5727. renderer: this._glRenderer,
  5728. version: this._glVersion
  5729. };
  5730. };
  5731. Engine.prototype.getAspectRatio = function (camera) {
  5732. var viewport = camera.viewport;
  5733. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5734. };
  5735. Engine.prototype.getRenderWidth = function () {
  5736. if (this._currentRenderTarget) {
  5737. return this._currentRenderTarget._width;
  5738. }
  5739. return this._renderingCanvas.width;
  5740. };
  5741. Engine.prototype.getRenderHeight = function () {
  5742. if (this._currentRenderTarget) {
  5743. return this._currentRenderTarget._height;
  5744. }
  5745. return this._renderingCanvas.height;
  5746. };
  5747. Engine.prototype.getRenderingCanvas = function () {
  5748. return this._renderingCanvas;
  5749. };
  5750. Engine.prototype.getRenderingCanvasClientRect = function () {
  5751. return this._renderingCanvas.getBoundingClientRect();
  5752. };
  5753. Engine.prototype.setHardwareScalingLevel = function (level) {
  5754. this._hardwareScalingLevel = level;
  5755. this.resize();
  5756. };
  5757. Engine.prototype.getHardwareScalingLevel = function () {
  5758. return this._hardwareScalingLevel;
  5759. };
  5760. Engine.prototype.getLoadedTexturesCache = function () {
  5761. return this._loadedTexturesCache;
  5762. };
  5763. Engine.prototype.getCaps = function () {
  5764. return this._caps;
  5765. };
  5766. Object.defineProperty(Engine.prototype, "drawCalls", {
  5767. get: function () {
  5768. return this._drawCalls;
  5769. },
  5770. enumerable: true,
  5771. configurable: true
  5772. });
  5773. // Methods
  5774. Engine.prototype.resetDrawCalls = function () {
  5775. this._drawCalls = 0;
  5776. };
  5777. Engine.prototype.setDepthFunctionToGreater = function () {
  5778. this._depthCullingState.depthFunc = this._gl.GREATER;
  5779. };
  5780. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5781. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5782. };
  5783. Engine.prototype.setDepthFunctionToLess = function () {
  5784. this._depthCullingState.depthFunc = this._gl.LESS;
  5785. };
  5786. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5787. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5788. };
  5789. /**
  5790. * stop executing a render loop function and remove it from the execution array
  5791. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5792. */
  5793. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5794. if (!renderFunction) {
  5795. this._activeRenderLoops = [];
  5796. return;
  5797. }
  5798. var index = this._activeRenderLoops.indexOf(renderFunction);
  5799. if (index >= 0) {
  5800. this._activeRenderLoops.splice(index, 1);
  5801. }
  5802. };
  5803. Engine.prototype._renderLoop = function () {
  5804. var _this = this;
  5805. var shouldRender = true;
  5806. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5807. shouldRender = false;
  5808. }
  5809. if (shouldRender) {
  5810. // Start new frame
  5811. this.beginFrame();
  5812. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5813. var renderFunction = this._activeRenderLoops[index];
  5814. renderFunction();
  5815. }
  5816. // Present
  5817. this.endFrame();
  5818. }
  5819. if (this._activeRenderLoops.length > 0) {
  5820. // Register new frame
  5821. BABYLON.Tools.QueueNewFrame(function () {
  5822. _this._renderLoop();
  5823. });
  5824. }
  5825. else {
  5826. this._renderingQueueLaunched = false;
  5827. }
  5828. };
  5829. /**
  5830. * Register and execute a render loop. The engine can have more than one render function.
  5831. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5832. * @example
  5833. * engine.runRenderLoop(function () {
  5834. * scene.render()
  5835. * })
  5836. */
  5837. Engine.prototype.runRenderLoop = function (renderFunction) {
  5838. var _this = this;
  5839. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5840. return;
  5841. }
  5842. this._activeRenderLoops.push(renderFunction);
  5843. if (!this._renderingQueueLaunched) {
  5844. this._renderingQueueLaunched = true;
  5845. BABYLON.Tools.QueueNewFrame(function () {
  5846. _this._renderLoop();
  5847. });
  5848. }
  5849. };
  5850. /**
  5851. * Toggle full screen mode.
  5852. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5853. */
  5854. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5855. if (this.isFullscreen) {
  5856. BABYLON.Tools.ExitFullscreen();
  5857. }
  5858. else {
  5859. this._pointerLockRequested = requestPointerLock;
  5860. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5861. }
  5862. };
  5863. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5864. this.applyStates();
  5865. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5866. if (this._depthCullingState.depthMask) {
  5867. this._gl.clearDepth(1.0);
  5868. }
  5869. var mode = 0;
  5870. if (backBuffer)
  5871. mode |= this._gl.COLOR_BUFFER_BIT;
  5872. if (depthStencil && this._depthCullingState.depthMask)
  5873. mode |= this._gl.DEPTH_BUFFER_BIT;
  5874. this._gl.clear(mode);
  5875. };
  5876. /**
  5877. * Set the WebGL's viewport
  5878. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5879. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5880. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5881. */
  5882. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5883. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5884. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5885. var x = viewport.x || 0;
  5886. var y = viewport.y || 0;
  5887. this._cachedViewport = viewport;
  5888. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5889. };
  5890. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5891. this._cachedViewport = null;
  5892. this._gl.viewport(x, y, width, height);
  5893. };
  5894. Engine.prototype.beginFrame = function () {
  5895. this._measureFps();
  5896. };
  5897. Engine.prototype.endFrame = function () {
  5898. //this.flushFramebuffer();
  5899. };
  5900. /**
  5901. * resize the view according to the canvas' size.
  5902. * @example
  5903. * window.addEventListener("resize", function () {
  5904. * engine.resize();
  5905. * });
  5906. */
  5907. Engine.prototype.resize = function () {
  5908. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5909. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5910. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5911. };
  5912. /**
  5913. * force a specific size of the canvas
  5914. * @param {number} width - the new canvas' width
  5915. * @param {number} height - the new canvas' height
  5916. */
  5917. Engine.prototype.setSize = function (width, height) {
  5918. this._renderingCanvas.width = width;
  5919. this._renderingCanvas.height = height;
  5920. for (var index = 0; index < this.scenes.length; index++) {
  5921. var scene = this.scenes[index];
  5922. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5923. var cam = scene.cameras[camIndex];
  5924. cam._currentRenderId = 0;
  5925. }
  5926. }
  5927. };
  5928. Engine.prototype.bindFramebuffer = function (texture) {
  5929. this._currentRenderTarget = texture;
  5930. var gl = this._gl;
  5931. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5932. this._gl.viewport(0, 0, texture._width, texture._height);
  5933. this.wipeCaches();
  5934. };
  5935. Engine.prototype.unBindFramebuffer = function (texture) {
  5936. this._currentRenderTarget = null;
  5937. if (texture.generateMipMaps) {
  5938. var gl = this._gl;
  5939. gl.bindTexture(gl.TEXTURE_2D, texture);
  5940. gl.generateMipmap(gl.TEXTURE_2D);
  5941. gl.bindTexture(gl.TEXTURE_2D, null);
  5942. }
  5943. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5944. };
  5945. Engine.prototype.flushFramebuffer = function () {
  5946. this._gl.flush();
  5947. };
  5948. Engine.prototype.restoreDefaultFramebuffer = function () {
  5949. this._currentRenderTarget = null;
  5950. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5951. this.setViewport(this._cachedViewport);
  5952. this.wipeCaches();
  5953. };
  5954. // VBOs
  5955. Engine.prototype._resetVertexBufferBinding = function () {
  5956. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5957. this._cachedVertexBuffers = null;
  5958. };
  5959. Engine.prototype.createVertexBuffer = function (vertices) {
  5960. var vbo = this._gl.createBuffer();
  5961. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5962. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5963. this._resetVertexBufferBinding();
  5964. vbo.references = 1;
  5965. return vbo;
  5966. };
  5967. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5968. var vbo = this._gl.createBuffer();
  5969. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5970. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5971. this._resetVertexBufferBinding();
  5972. vbo.references = 1;
  5973. return vbo;
  5974. };
  5975. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5976. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5977. if (offset === undefined) {
  5978. offset = 0;
  5979. }
  5980. if (vertices instanceof Float32Array) {
  5981. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5982. }
  5983. else {
  5984. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5985. }
  5986. this._resetVertexBufferBinding();
  5987. };
  5988. Engine.prototype._resetIndexBufferBinding = function () {
  5989. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5990. this._cachedIndexBuffer = null;
  5991. };
  5992. Engine.prototype.createIndexBuffer = function (indices) {
  5993. var vbo = this._gl.createBuffer();
  5994. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5995. // Check for 32 bits indices
  5996. var arrayBuffer;
  5997. var need32Bits = false;
  5998. if (this._caps.uintIndices) {
  5999. for (var index = 0; index < indices.length; index++) {
  6000. if (indices[index] > 65535) {
  6001. need32Bits = true;
  6002. break;
  6003. }
  6004. }
  6005. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6006. }
  6007. else {
  6008. arrayBuffer = new Uint16Array(indices);
  6009. }
  6010. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6011. this._resetIndexBufferBinding();
  6012. vbo.references = 1;
  6013. vbo.is32Bits = need32Bits;
  6014. return vbo;
  6015. };
  6016. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6017. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6018. this._cachedVertexBuffers = vertexBuffer;
  6019. this._cachedEffectForVertexBuffers = effect;
  6020. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6021. var offset = 0;
  6022. for (var index = 0; index < vertexDeclaration.length; index++) {
  6023. var order = effect.getAttributeLocation(index);
  6024. if (order >= 0) {
  6025. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6026. }
  6027. offset += vertexDeclaration[index] * 4;
  6028. }
  6029. }
  6030. if (this._cachedIndexBuffer !== indexBuffer) {
  6031. this._cachedIndexBuffer = indexBuffer;
  6032. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6033. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6034. }
  6035. };
  6036. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6037. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6038. this._cachedVertexBuffers = vertexBuffers;
  6039. this._cachedEffectForVertexBuffers = effect;
  6040. var attributes = effect.getAttributesNames();
  6041. for (var index = 0; index < attributes.length; index++) {
  6042. var order = effect.getAttributeLocation(index);
  6043. if (order >= 0) {
  6044. var vertexBuffer = vertexBuffers[attributes[index]];
  6045. if (!vertexBuffer) {
  6046. continue;
  6047. }
  6048. var stride = vertexBuffer.getStrideSize();
  6049. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6050. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6051. }
  6052. }
  6053. }
  6054. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6055. this._cachedIndexBuffer = indexBuffer;
  6056. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6057. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6058. }
  6059. };
  6060. Engine.prototype._releaseBuffer = function (buffer) {
  6061. buffer.references--;
  6062. if (buffer.references === 0) {
  6063. this._gl.deleteBuffer(buffer);
  6064. return true;
  6065. }
  6066. return false;
  6067. };
  6068. Engine.prototype.createInstancesBuffer = function (capacity) {
  6069. var buffer = this._gl.createBuffer();
  6070. buffer.capacity = capacity;
  6071. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6072. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6073. return buffer;
  6074. };
  6075. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6076. this._gl.deleteBuffer(buffer);
  6077. };
  6078. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6079. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6080. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6081. for (var index = 0; index < 4; index++) {
  6082. var offsetLocation = offsetLocations[index];
  6083. this._gl.enableVertexAttribArray(offsetLocation);
  6084. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6085. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6086. }
  6087. };
  6088. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6089. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6090. for (var index = 0; index < 4; index++) {
  6091. var offsetLocation = offsetLocations[index];
  6092. this._gl.disableVertexAttribArray(offsetLocation);
  6093. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6094. }
  6095. };
  6096. Engine.prototype.applyStates = function () {
  6097. this._depthCullingState.apply(this._gl);
  6098. this._alphaState.apply(this._gl);
  6099. };
  6100. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6101. // Apply states
  6102. this.applyStates();
  6103. this._drawCalls++;
  6104. // Render
  6105. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6106. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6107. if (instancesCount) {
  6108. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6109. return;
  6110. }
  6111. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6112. };
  6113. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6114. // Apply states
  6115. this.applyStates();
  6116. this._drawCalls++;
  6117. if (instancesCount) {
  6118. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6119. return;
  6120. }
  6121. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6122. };
  6123. // Shaders
  6124. Engine.prototype._releaseEffect = function (effect) {
  6125. if (this._compiledEffects[effect._key]) {
  6126. delete this._compiledEffects[effect._key];
  6127. if (effect.getProgram()) {
  6128. this._gl.deleteProgram(effect.getProgram());
  6129. }
  6130. }
  6131. };
  6132. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6133. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6134. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6135. var name = vertex + "+" + fragment + "@" + defines;
  6136. if (this._compiledEffects[name]) {
  6137. return this._compiledEffects[name];
  6138. }
  6139. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6140. effect._key = name;
  6141. this._compiledEffects[name] = effect;
  6142. return effect;
  6143. };
  6144. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6145. if (uniformsNames === void 0) { uniformsNames = []; }
  6146. if (samplers === void 0) { samplers = []; }
  6147. if (defines === void 0) { defines = ""; }
  6148. return this.createEffect({
  6149. vertex: "particles",
  6150. fragmentElement: fragmentName
  6151. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6152. };
  6153. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6154. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6155. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6156. var shaderProgram = this._gl.createProgram();
  6157. this._gl.attachShader(shaderProgram, vertexShader);
  6158. this._gl.attachShader(shaderProgram, fragmentShader);
  6159. this._gl.linkProgram(shaderProgram);
  6160. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6161. if (!linked) {
  6162. var error = this._gl.getProgramInfoLog(shaderProgram);
  6163. if (error) {
  6164. throw new Error(error);
  6165. }
  6166. }
  6167. this._gl.deleteShader(vertexShader);
  6168. this._gl.deleteShader(fragmentShader);
  6169. return shaderProgram;
  6170. };
  6171. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6172. var results = [];
  6173. for (var index = 0; index < uniformsNames.length; index++) {
  6174. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6175. }
  6176. return results;
  6177. };
  6178. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6179. var results = [];
  6180. for (var index = 0; index < attributesNames.length; index++) {
  6181. try {
  6182. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6183. }
  6184. catch (e) {
  6185. results.push(-1);
  6186. }
  6187. }
  6188. return results;
  6189. };
  6190. Engine.prototype.enableEffect = function (effect) {
  6191. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6192. if (effect && effect.onBind) {
  6193. effect.onBind(effect);
  6194. }
  6195. return;
  6196. }
  6197. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6198. // Use program
  6199. this._gl.useProgram(effect.getProgram());
  6200. for (var i in this._vertexAttribArrays) {
  6201. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6202. continue;
  6203. }
  6204. this._vertexAttribArrays[i] = false;
  6205. this._gl.disableVertexAttribArray(i);
  6206. }
  6207. var attributesCount = effect.getAttributesCount();
  6208. for (var index = 0; index < attributesCount; index++) {
  6209. // Attributes
  6210. var order = effect.getAttributeLocation(index);
  6211. if (order >= 0) {
  6212. this._vertexAttribArrays[order] = true;
  6213. this._gl.enableVertexAttribArray(order);
  6214. }
  6215. }
  6216. this._currentEffect = effect;
  6217. if (effect.onBind) {
  6218. effect.onBind(effect);
  6219. }
  6220. };
  6221. Engine.prototype.setArray = function (uniform, array) {
  6222. if (!uniform)
  6223. return;
  6224. this._gl.uniform1fv(uniform, array);
  6225. };
  6226. Engine.prototype.setArray2 = function (uniform, array) {
  6227. if (!uniform || array.length % 2 !== 0)
  6228. return;
  6229. this._gl.uniform2fv(uniform, array);
  6230. };
  6231. Engine.prototype.setArray3 = function (uniform, array) {
  6232. if (!uniform || array.length % 3 !== 0)
  6233. return;
  6234. this._gl.uniform3fv(uniform, array);
  6235. };
  6236. Engine.prototype.setArray4 = function (uniform, array) {
  6237. if (!uniform || array.length % 4 !== 0)
  6238. return;
  6239. this._gl.uniform4fv(uniform, array);
  6240. };
  6241. Engine.prototype.setMatrices = function (uniform, matrices) {
  6242. if (!uniform)
  6243. return;
  6244. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6245. };
  6246. Engine.prototype.setMatrix = function (uniform, matrix) {
  6247. if (!uniform)
  6248. return;
  6249. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6250. };
  6251. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6252. if (!uniform)
  6253. return;
  6254. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6255. };
  6256. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6257. if (!uniform)
  6258. return;
  6259. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6260. };
  6261. Engine.prototype.setFloat = function (uniform, value) {
  6262. if (!uniform)
  6263. return;
  6264. this._gl.uniform1f(uniform, value);
  6265. };
  6266. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6267. if (!uniform)
  6268. return;
  6269. this._gl.uniform2f(uniform, x, y);
  6270. };
  6271. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6272. if (!uniform)
  6273. return;
  6274. this._gl.uniform3f(uniform, x, y, z);
  6275. };
  6276. Engine.prototype.setBool = function (uniform, bool) {
  6277. if (!uniform)
  6278. return;
  6279. this._gl.uniform1i(uniform, bool);
  6280. };
  6281. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6282. if (!uniform)
  6283. return;
  6284. this._gl.uniform4f(uniform, x, y, z, w);
  6285. };
  6286. Engine.prototype.setColor3 = function (uniform, color3) {
  6287. if (!uniform)
  6288. return;
  6289. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6290. };
  6291. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6292. if (!uniform)
  6293. return;
  6294. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6295. };
  6296. // States
  6297. Engine.prototype.setState = function (culling, zOffset, force) {
  6298. if (zOffset === void 0) { zOffset = 0; }
  6299. // Culling
  6300. if (this._depthCullingState.cull !== culling || force) {
  6301. if (culling) {
  6302. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6303. this._depthCullingState.cull = true;
  6304. }
  6305. else {
  6306. this._depthCullingState.cull = false;
  6307. }
  6308. }
  6309. // Z offset
  6310. this._depthCullingState.zOffset = zOffset;
  6311. };
  6312. Engine.prototype.setDepthBuffer = function (enable) {
  6313. this._depthCullingState.depthTest = enable;
  6314. };
  6315. Engine.prototype.getDepthWrite = function () {
  6316. return this._depthCullingState.depthMask;
  6317. };
  6318. Engine.prototype.setDepthWrite = function (enable) {
  6319. this._depthCullingState.depthMask = enable;
  6320. };
  6321. Engine.prototype.setColorWrite = function (enable) {
  6322. this._gl.colorMask(enable, enable, enable, enable);
  6323. };
  6324. Engine.prototype.setAlphaMode = function (mode) {
  6325. if (this._alphaMode == mode) {
  6326. return;
  6327. }
  6328. switch (mode) {
  6329. case Engine.ALPHA_DISABLE:
  6330. this.setDepthWrite(true);
  6331. this._alphaState.alphaBlend = false;
  6332. break;
  6333. case Engine.ALPHA_COMBINE:
  6334. this.setDepthWrite(false);
  6335. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6336. this._alphaState.alphaBlend = true;
  6337. break;
  6338. case Engine.ALPHA_ONEONE:
  6339. this.setDepthWrite(false);
  6340. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6341. this._alphaState.alphaBlend = true;
  6342. break;
  6343. case Engine.ALPHA_ADD:
  6344. this.setDepthWrite(false);
  6345. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6346. this._alphaState.alphaBlend = true;
  6347. break;
  6348. case Engine.ALPHA_SUBTRACT:
  6349. this.setDepthWrite(false);
  6350. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6351. this._alphaState.alphaBlend = true;
  6352. break;
  6353. case Engine.ALPHA_MULTIPLY:
  6354. this.setDepthWrite(false);
  6355. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6356. this._alphaState.alphaBlend = true;
  6357. break;
  6358. case Engine.ALPHA_MAXIMIZED:
  6359. this.setDepthWrite(false);
  6360. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6361. this._alphaState.alphaBlend = true;
  6362. break;
  6363. }
  6364. this._alphaMode = mode;
  6365. };
  6366. Engine.prototype.getAlphaMode = function () {
  6367. return this._alphaMode;
  6368. };
  6369. Engine.prototype.setAlphaTesting = function (enable) {
  6370. this._alphaTest = enable;
  6371. };
  6372. Engine.prototype.getAlphaTesting = function () {
  6373. return this._alphaTest;
  6374. };
  6375. // Textures
  6376. Engine.prototype.wipeCaches = function () {
  6377. this._activeTexturesCache = [];
  6378. this._currentEffect = null;
  6379. this._depthCullingState.reset();
  6380. this._alphaState.reset();
  6381. this._cachedVertexBuffers = null;
  6382. this._cachedIndexBuffer = null;
  6383. this._cachedEffectForVertexBuffers = null;
  6384. };
  6385. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6386. var gl = this._gl;
  6387. gl.bindTexture(gl.TEXTURE_2D, texture);
  6388. var magFilter = gl.NEAREST;
  6389. var minFilter = gl.NEAREST;
  6390. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6391. magFilter = gl.LINEAR;
  6392. minFilter = gl.LINEAR;
  6393. }
  6394. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6395. magFilter = gl.LINEAR;
  6396. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6397. }
  6398. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6399. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6400. gl.bindTexture(gl.TEXTURE_2D, null);
  6401. texture.samplingMode = samplingMode;
  6402. };
  6403. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6404. var _this = this;
  6405. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6406. if (onLoad === void 0) { onLoad = null; }
  6407. if (onError === void 0) { onError = null; }
  6408. if (buffer === void 0) { buffer = null; }
  6409. var texture = this._gl.createTexture();
  6410. var extension;
  6411. var fromData = false;
  6412. if (url.substr(0, 5) === "data:") {
  6413. fromData = true;
  6414. }
  6415. if (!fromData)
  6416. extension = url.substr(url.length - 4, 4).toLowerCase();
  6417. else {
  6418. var oldUrl = url;
  6419. fromData = oldUrl.split(':');
  6420. url = oldUrl;
  6421. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6422. }
  6423. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6424. var isTGA = (extension === ".tga");
  6425. scene._addPendingData(texture);
  6426. texture.url = url;
  6427. texture.noMipmap = noMipmap;
  6428. texture.references = 1;
  6429. texture.samplingMode = samplingMode;
  6430. this._loadedTexturesCache.push(texture);
  6431. var onerror = function () {
  6432. scene._removePendingData(texture);
  6433. if (onError) {
  6434. onError();
  6435. }
  6436. };
  6437. if (isTGA) {
  6438. var callback = function (arrayBuffer) {
  6439. var data = new Uint8Array(arrayBuffer);
  6440. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6441. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6442. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6443. if (onLoad) {
  6444. onLoad();
  6445. }
  6446. }, samplingMode);
  6447. };
  6448. if (!(fromData instanceof Array))
  6449. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6450. callback(arrayBuffer);
  6451. }, onerror, scene.database, true);
  6452. else
  6453. callback(buffer);
  6454. }
  6455. else if (isDDS) {
  6456. callback = function (data) {
  6457. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6458. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6459. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6460. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6461. if (onLoad) {
  6462. onLoad();
  6463. }
  6464. }, samplingMode);
  6465. };
  6466. if (!(fromData instanceof Array))
  6467. BABYLON.Tools.LoadFile(url, function (data) {
  6468. callback(data);
  6469. }, onerror, scene.database, true);
  6470. else
  6471. callback(buffer);
  6472. }
  6473. else {
  6474. var onload = function (img) {
  6475. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6476. var isPot = (img.width === potWidth && img.height === potHeight);
  6477. if (!isPot) {
  6478. _this._prepareWorkingCanvas();
  6479. _this._workingCanvas.width = potWidth;
  6480. _this._workingCanvas.height = potHeight;
  6481. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6482. _this._workingContext.imageSmoothingEnabled = false;
  6483. _this._workingContext.mozImageSmoothingEnabled = false;
  6484. _this._workingContext.oImageSmoothingEnabled = false;
  6485. _this._workingContext.webkitImageSmoothingEnabled = false;
  6486. _this._workingContext.msImageSmoothingEnabled = false;
  6487. }
  6488. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6489. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6490. _this._workingContext.imageSmoothingEnabled = true;
  6491. _this._workingContext.mozImageSmoothingEnabled = true;
  6492. _this._workingContext.oImageSmoothingEnabled = true;
  6493. _this._workingContext.webkitImageSmoothingEnabled = true;
  6494. _this._workingContext.msImageSmoothingEnabled = true;
  6495. }
  6496. }
  6497. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6498. if (onLoad) {
  6499. onLoad();
  6500. }
  6501. }, samplingMode);
  6502. };
  6503. if (!(fromData instanceof Array))
  6504. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6505. else
  6506. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6507. }
  6508. return texture;
  6509. };
  6510. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6511. if (compression === void 0) { compression = null; }
  6512. var internalFormat = this._gl.RGBA;
  6513. switch (format) {
  6514. case Engine.TEXTUREFORMAT_ALPHA:
  6515. internalFormat = this._gl.ALPHA;
  6516. break;
  6517. case Engine.TEXTUREFORMAT_LUMINANCE:
  6518. internalFormat = this._gl.LUMINANCE;
  6519. break;
  6520. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6521. internalFormat = this._gl.LUMINANCE_ALPHA;
  6522. break;
  6523. case Engine.TEXTUREFORMAT_RGB:
  6524. internalFormat = this._gl.RGB;
  6525. break;
  6526. case Engine.TEXTUREFORMAT_RGBA:
  6527. internalFormat = this._gl.RGBA;
  6528. break;
  6529. }
  6530. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6531. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6532. if (compression) {
  6533. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6534. }
  6535. else {
  6536. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6537. }
  6538. if (texture.generateMipMaps) {
  6539. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6540. }
  6541. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6542. this._activeTexturesCache = [];
  6543. texture.isReady = true;
  6544. };
  6545. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6546. if (compression === void 0) { compression = null; }
  6547. var texture = this._gl.createTexture();
  6548. texture._baseWidth = width;
  6549. texture._baseHeight = height;
  6550. texture._width = width;
  6551. texture._height = height;
  6552. texture.references = 1;
  6553. this.updateRawTexture(texture, data, format, invertY, compression);
  6554. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6555. // Filters
  6556. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6557. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6558. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6559. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6560. texture.samplingMode = samplingMode;
  6561. this._loadedTexturesCache.push(texture);
  6562. return texture;
  6563. };
  6564. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6565. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6566. var texture = this._gl.createTexture();
  6567. texture._baseWidth = width;
  6568. texture._baseHeight = height;
  6569. if (forceExponantOfTwo) {
  6570. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6571. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6572. }
  6573. this._activeTexturesCache = [];
  6574. texture._width = width;
  6575. texture._height = height;
  6576. texture.isReady = false;
  6577. texture.generateMipMaps = generateMipMaps;
  6578. texture.references = 1;
  6579. texture.samplingMode = samplingMode;
  6580. this.updateTextureSamplingMode(samplingMode, texture);
  6581. this._loadedTexturesCache.push(texture);
  6582. return texture;
  6583. };
  6584. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6585. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6586. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6587. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6588. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6589. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6590. };
  6591. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6592. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6593. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6594. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6595. if (texture.generateMipMaps) {
  6596. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6597. }
  6598. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6599. this._activeTexturesCache = [];
  6600. texture.isReady = true;
  6601. };
  6602. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6603. if (texture._isDisabled) {
  6604. return;
  6605. }
  6606. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6607. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6608. try {
  6609. // Testing video texture support
  6610. if (this._videoTextureSupported === undefined) {
  6611. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6612. if (this._gl.getError() !== 0) {
  6613. this._videoTextureSupported = false;
  6614. }
  6615. else {
  6616. this._videoTextureSupported = true;
  6617. }
  6618. }
  6619. // Copy video through the current working canvas if video texture is not supported
  6620. if (!this._videoTextureSupported) {
  6621. if (!texture._workingCanvas) {
  6622. texture._workingCanvas = document.createElement("canvas");
  6623. texture._workingContext = texture._workingCanvas.getContext("2d");
  6624. texture._workingCanvas.width = texture._width;
  6625. texture._workingCanvas.height = texture._height;
  6626. }
  6627. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6628. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6629. }
  6630. else {
  6631. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6632. }
  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. catch (ex) {
  6641. // Something unexpected
  6642. // Let's disable the texture
  6643. texture._isDisabled = true;
  6644. }
  6645. };
  6646. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6647. // old version had a "generateMipMaps" arg instead of options.
  6648. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6649. // in the same way, generateDepthBuffer is defaulted to true
  6650. var generateMipMaps = false;
  6651. var generateDepthBuffer = true;
  6652. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6653. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6654. if (options !== undefined) {
  6655. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6656. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6657. type = options.type === undefined ? type : options.type;
  6658. if (options.samplingMode !== undefined) {
  6659. samplingMode = options.samplingMode;
  6660. }
  6661. if (type === Engine.TEXTURETYPE_FLOAT) {
  6662. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6663. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6664. }
  6665. }
  6666. var gl = this._gl;
  6667. var texture = gl.createTexture();
  6668. gl.bindTexture(gl.TEXTURE_2D, texture);
  6669. var width = size.width || size;
  6670. var height = size.height || size;
  6671. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6672. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6673. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6674. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6675. }
  6676. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6677. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6678. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6679. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6680. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6681. var depthBuffer;
  6682. // Create the depth buffer
  6683. if (generateDepthBuffer) {
  6684. depthBuffer = gl.createRenderbuffer();
  6685. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6686. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6687. }
  6688. // Create the framebuffer
  6689. var framebuffer = gl.createFramebuffer();
  6690. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6691. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6692. if (generateDepthBuffer) {
  6693. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6694. }
  6695. if (generateMipMaps) {
  6696. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6697. }
  6698. // Unbind
  6699. gl.bindTexture(gl.TEXTURE_2D, null);
  6700. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6701. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6702. texture._framebuffer = framebuffer;
  6703. if (generateDepthBuffer) {
  6704. texture._depthBuffer = depthBuffer;
  6705. }
  6706. texture._width = width;
  6707. texture._height = height;
  6708. texture.isReady = true;
  6709. texture.generateMipMaps = generateMipMaps;
  6710. texture.references = 1;
  6711. texture.samplingMode = samplingMode;
  6712. this._activeTexturesCache = [];
  6713. this._loadedTexturesCache.push(texture);
  6714. return texture;
  6715. };
  6716. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6717. var _this = this;
  6718. var gl = this._gl;
  6719. var texture = gl.createTexture();
  6720. texture.isCube = true;
  6721. texture.url = rootUrl;
  6722. texture.references = 1;
  6723. this._loadedTexturesCache.push(texture);
  6724. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6725. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6726. if (isDDS) {
  6727. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6728. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6729. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6730. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6731. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6732. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6733. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6734. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6735. }
  6736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6737. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6738. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6739. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6740. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6741. _this._activeTexturesCache = [];
  6742. texture._width = info.width;
  6743. texture._height = info.height;
  6744. texture.isReady = true;
  6745. }, null, null, true);
  6746. }
  6747. else {
  6748. cascadeLoad(rootUrl, scene, function (imgs) {
  6749. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6750. var height = width;
  6751. _this._prepareWorkingCanvas();
  6752. _this._workingCanvas.width = width;
  6753. _this._workingCanvas.height = height;
  6754. var faces = [
  6755. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6756. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6757. ];
  6758. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6759. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6760. for (var index = 0; index < faces.length; index++) {
  6761. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6762. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6763. }
  6764. if (!noMipmap) {
  6765. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6766. }
  6767. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6768. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6771. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6772. _this._activeTexturesCache = [];
  6773. texture._width = width;
  6774. texture._height = height;
  6775. texture.isReady = true;
  6776. }, extensions);
  6777. }
  6778. return texture;
  6779. };
  6780. Engine.prototype._releaseTexture = function (texture) {
  6781. var gl = this._gl;
  6782. if (texture._framebuffer) {
  6783. gl.deleteFramebuffer(texture._framebuffer);
  6784. }
  6785. if (texture._depthBuffer) {
  6786. gl.deleteRenderbuffer(texture._depthBuffer);
  6787. }
  6788. gl.deleteTexture(texture);
  6789. // Unbind channels
  6790. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6791. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6792. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6793. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6794. this._activeTexturesCache[channel] = null;
  6795. }
  6796. var index = this._loadedTexturesCache.indexOf(texture);
  6797. if (index !== -1) {
  6798. this._loadedTexturesCache.splice(index, 1);
  6799. }
  6800. };
  6801. Engine.prototype.bindSamplers = function (effect) {
  6802. this._gl.useProgram(effect.getProgram());
  6803. var samplers = effect.getSamplers();
  6804. for (var index = 0; index < samplers.length; index++) {
  6805. var uniform = effect.getUniform(samplers[index]);
  6806. this._gl.uniform1i(uniform, index);
  6807. }
  6808. this._currentEffect = null;
  6809. };
  6810. Engine.prototype._bindTexture = function (channel, texture) {
  6811. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6812. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6813. this._activeTexturesCache[channel] = null;
  6814. };
  6815. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6816. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6817. };
  6818. Engine.prototype.setTexture = function (channel, texture) {
  6819. if (channel < 0) {
  6820. return;
  6821. }
  6822. // Not ready?
  6823. if (!texture || !texture.isReady()) {
  6824. if (this._activeTexturesCache[channel] != null) {
  6825. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6826. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6827. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6828. this._activeTexturesCache[channel] = null;
  6829. }
  6830. return;
  6831. }
  6832. // Video
  6833. if (texture instanceof BABYLON.VideoTexture) {
  6834. if (texture.update()) {
  6835. this._activeTexturesCache[channel] = null;
  6836. }
  6837. }
  6838. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6839. texture.delayLoad();
  6840. return;
  6841. }
  6842. if (this._activeTexturesCache[channel] === texture) {
  6843. return;
  6844. }
  6845. this._activeTexturesCache[channel] = texture;
  6846. var internalTexture = texture.getInternalTexture();
  6847. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6848. if (internalTexture.isCube) {
  6849. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6850. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6851. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6852. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6853. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6854. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6855. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6856. }
  6857. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6858. }
  6859. else {
  6860. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6861. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6862. internalTexture._cachedWrapU = texture.wrapU;
  6863. switch (texture.wrapU) {
  6864. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6865. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6866. break;
  6867. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6868. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6869. break;
  6870. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6871. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6872. break;
  6873. }
  6874. }
  6875. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6876. internalTexture._cachedWrapV = texture.wrapV;
  6877. switch (texture.wrapV) {
  6878. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6879. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6880. break;
  6881. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6882. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6883. break;
  6884. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6885. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6886. break;
  6887. }
  6888. }
  6889. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6890. }
  6891. };
  6892. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6893. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6894. var value = texture.anisotropicFilteringLevel;
  6895. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6896. value = 1;
  6897. }
  6898. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6899. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6900. texture._cachedAnisotropicFilteringLevel = value;
  6901. }
  6902. };
  6903. Engine.prototype.readPixels = function (x, y, width, height) {
  6904. var data = new Uint8Array(height * width * 4);
  6905. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6906. return data;
  6907. };
  6908. // Dispose
  6909. Engine.prototype.dispose = function () {
  6910. this.hideLoadingUI();
  6911. this.stopRenderLoop();
  6912. // Release scenes
  6913. while (this.scenes.length) {
  6914. this.scenes[0].dispose();
  6915. }
  6916. // Release audio engine
  6917. Engine.audioEngine.dispose();
  6918. // Release effects
  6919. for (var name in this._compiledEffects) {
  6920. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6921. }
  6922. // Unbind
  6923. for (var i in this._vertexAttribArrays) {
  6924. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6925. continue;
  6926. }
  6927. this._gl.disableVertexAttribArray(i);
  6928. }
  6929. this._gl = null;
  6930. // Events
  6931. window.removeEventListener("blur", this._onBlur);
  6932. window.removeEventListener("focus", this._onFocus);
  6933. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6934. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6935. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6936. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6937. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6938. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6939. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6940. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6941. };
  6942. // Loading screen
  6943. Engine.prototype.displayLoadingUI = function () {
  6944. var _this = this;
  6945. this._loadingDiv = document.createElement("div");
  6946. this._loadingDiv.style.opacity = "0";
  6947. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6948. // Loading text
  6949. this._loadingTextDiv = document.createElement("div");
  6950. this._loadingTextDiv.style.position = "absolute";
  6951. this._loadingTextDiv.style.left = "0";
  6952. this._loadingTextDiv.style.top = "50%";
  6953. this._loadingTextDiv.style.marginTop = "80px";
  6954. this._loadingTextDiv.style.width = "100%";
  6955. this._loadingTextDiv.style.height = "20px";
  6956. this._loadingTextDiv.style.fontFamily = "Arial";
  6957. this._loadingTextDiv.style.fontSize = "14px";
  6958. this._loadingTextDiv.style.color = "white";
  6959. this._loadingTextDiv.style.textAlign = "center";
  6960. this._loadingTextDiv.innerHTML = "Loading";
  6961. this._loadingDiv.appendChild(this._loadingTextDiv);
  6962. // Loading img
  6963. var imgBack = new Image();
  6964. 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==";
  6965. imgBack.style.position = "absolute";
  6966. imgBack.style.left = "50%";
  6967. imgBack.style.top = "50%";
  6968. imgBack.style.marginLeft = "-50px";
  6969. imgBack.style.marginTop = "-50px";
  6970. imgBack.style.transition = "transform 1.0s ease";
  6971. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6972. var deg = 360;
  6973. var onTransitionEnd = function () {
  6974. deg += 360;
  6975. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6976. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6977. };
  6978. imgBack.addEventListener("transitionend", onTransitionEnd);
  6979. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6980. this._loadingDiv.appendChild(imgBack);
  6981. // front image
  6982. var imgFront = new Image();
  6983. 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=";
  6984. imgFront.style.position = "absolute";
  6985. imgFront.style.left = "50%";
  6986. imgFront.style.top = "50%";
  6987. imgFront.style.marginLeft = "-50px";
  6988. imgFront.style.marginTop = "-50px";
  6989. this._loadingDiv.appendChild(imgFront);
  6990. // Resize
  6991. this._resizeLoadingUI = function () {
  6992. var canvasRect = _this.getRenderingCanvasClientRect();
  6993. _this._loadingDiv.style.position = "absolute";
  6994. _this._loadingDiv.style.left = canvasRect.left + "px";
  6995. _this._loadingDiv.style.top = canvasRect.top + "px";
  6996. _this._loadingDiv.style.width = canvasRect.width + "px";
  6997. _this._loadingDiv.style.height = canvasRect.height + "px";
  6998. };
  6999. this._resizeLoadingUI();
  7000. window.addEventListener("resize", this._resizeLoadingUI);
  7001. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  7002. document.body.appendChild(this._loadingDiv);
  7003. setTimeout(function () {
  7004. _this._loadingDiv.style.opacity = "1";
  7005. imgBack.style.transform = "rotateZ(360deg)";
  7006. imgBack.style.webkitTransform = "rotateZ(360deg)";
  7007. }, 0);
  7008. };
  7009. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7010. set: function (text) {
  7011. if (!this._loadingDiv) {
  7012. return;
  7013. }
  7014. this._loadingTextDiv.innerHTML = text;
  7015. },
  7016. enumerable: true,
  7017. configurable: true
  7018. });
  7019. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7020. get: function () {
  7021. return this._loadingDivBackgroundColor;
  7022. },
  7023. set: function (color) {
  7024. this._loadingDivBackgroundColor = color;
  7025. if (!this._loadingDiv) {
  7026. return;
  7027. }
  7028. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  7029. },
  7030. enumerable: true,
  7031. configurable: true
  7032. });
  7033. Engine.prototype.hideLoadingUI = function () {
  7034. var _this = this;
  7035. if (!this._loadingDiv) {
  7036. return;
  7037. }
  7038. var onTransitionEnd = function () {
  7039. if (!_this._loadingDiv) {
  7040. return;
  7041. }
  7042. document.body.removeChild(_this._loadingDiv);
  7043. window.removeEventListener("resize", _this._resizeLoadingUI);
  7044. _this._loadingDiv = null;
  7045. };
  7046. this._loadingDiv.style.opacity = "0";
  7047. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  7048. };
  7049. // FPS
  7050. Engine.prototype.getFps = function () {
  7051. return this.fps;
  7052. };
  7053. Engine.prototype.getDeltaTime = function () {
  7054. return this.deltaTime;
  7055. };
  7056. Engine.prototype._measureFps = function () {
  7057. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7058. var length = this.previousFramesDuration.length;
  7059. if (length >= 2) {
  7060. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7061. }
  7062. if (length >= this.fpsRange) {
  7063. if (length > this.fpsRange) {
  7064. this.previousFramesDuration.splice(0, 1);
  7065. length = this.previousFramesDuration.length;
  7066. }
  7067. var sum = 0;
  7068. for (var id = 0; id < length - 1; id++) {
  7069. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7070. }
  7071. this.fps = 1000.0 / (sum / (length - 1));
  7072. }
  7073. };
  7074. // Statics
  7075. Engine.isSupported = function () {
  7076. try {
  7077. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7078. if (navigator.isCocoonJS) {
  7079. return true;
  7080. }
  7081. var tempcanvas = document.createElement("canvas");
  7082. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7083. return gl != null && !!window.WebGLRenderingContext;
  7084. }
  7085. catch (e) {
  7086. return false;
  7087. }
  7088. };
  7089. // Const statics
  7090. Engine._ALPHA_DISABLE = 0;
  7091. Engine._ALPHA_ADD = 1;
  7092. Engine._ALPHA_COMBINE = 2;
  7093. Engine._ALPHA_SUBTRACT = 3;
  7094. Engine._ALPHA_MULTIPLY = 4;
  7095. Engine._ALPHA_MAXIMIZED = 5;
  7096. Engine._ALPHA_ONEONE = 6;
  7097. Engine._DELAYLOADSTATE_NONE = 0;
  7098. Engine._DELAYLOADSTATE_LOADED = 1;
  7099. Engine._DELAYLOADSTATE_LOADING = 2;
  7100. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7101. Engine._TEXTUREFORMAT_ALPHA = 0;
  7102. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7103. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7104. Engine._TEXTUREFORMAT_RGB = 4;
  7105. Engine._TEXTUREFORMAT_RGBA = 5;
  7106. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7107. Engine._TEXTURETYPE_FLOAT = 1;
  7108. // Updatable statics so stick with vars here
  7109. Engine.Epsilon = 0.001;
  7110. Engine.CollisionsEpsilon = 0.001;
  7111. Engine.CodeRepository = "src/";
  7112. Engine.ShadersRepository = "src/Shaders/";
  7113. return Engine;
  7114. })();
  7115. BABYLON.Engine = Engine;
  7116. })(BABYLON || (BABYLON = {}));
  7117. var BABYLON;
  7118. (function (BABYLON) {
  7119. /**
  7120. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7121. */
  7122. var Node = (function () {
  7123. /**
  7124. * @constructor
  7125. * @param {string} name - the name and id to be given to this node
  7126. * @param {BABYLON.Scene} the scene this node will be added to
  7127. */
  7128. function Node(name, scene) {
  7129. this.state = "";
  7130. this.animations = new Array();
  7131. this._childrenFlag = -1;
  7132. this._isEnabled = true;
  7133. this._isReady = true;
  7134. this._currentRenderId = -1;
  7135. this._parentRenderId = -1;
  7136. this.name = name;
  7137. this.id = name;
  7138. this._scene = scene;
  7139. this._initCache();
  7140. }
  7141. Node.prototype.getScene = function () {
  7142. return this._scene;
  7143. };
  7144. Node.prototype.getEngine = function () {
  7145. return this._scene.getEngine();
  7146. };
  7147. // override it in derived class
  7148. Node.prototype.getWorldMatrix = function () {
  7149. return BABYLON.Matrix.Identity();
  7150. };
  7151. // override it in derived class if you add new variables to the cache
  7152. // and call the parent class method
  7153. Node.prototype._initCache = function () {
  7154. this._cache = {};
  7155. this._cache.parent = undefined;
  7156. };
  7157. Node.prototype.updateCache = function (force) {
  7158. if (!force && this.isSynchronized())
  7159. return;
  7160. this._cache.parent = this.parent;
  7161. this._updateCache();
  7162. };
  7163. // override it in derived class if you add new variables to the cache
  7164. // and call the parent class method if !ignoreParentClass
  7165. Node.prototype._updateCache = function (ignoreParentClass) {
  7166. };
  7167. // override it in derived class if you add new variables to the cache
  7168. Node.prototype._isSynchronized = function () {
  7169. return true;
  7170. };
  7171. Node.prototype._markSyncedWithParent = function () {
  7172. this._parentRenderId = this.parent._currentRenderId;
  7173. };
  7174. Node.prototype.isSynchronizedWithParent = function () {
  7175. if (!this.parent) {
  7176. return true;
  7177. }
  7178. if (this._parentRenderId !== this.parent._currentRenderId) {
  7179. return false;
  7180. }
  7181. return this.parent.isSynchronized();
  7182. };
  7183. Node.prototype.isSynchronized = function (updateCache) {
  7184. var check = this.hasNewParent();
  7185. check = check || !this.isSynchronizedWithParent();
  7186. check = check || !this._isSynchronized();
  7187. if (updateCache)
  7188. this.updateCache(true);
  7189. return !check;
  7190. };
  7191. Node.prototype.hasNewParent = function (update) {
  7192. if (this._cache.parent === this.parent)
  7193. return false;
  7194. if (update)
  7195. this._cache.parent = this.parent;
  7196. return true;
  7197. };
  7198. /**
  7199. * Is this node ready to be used/rendered
  7200. * @return {boolean} is it ready
  7201. */
  7202. Node.prototype.isReady = function () {
  7203. return this._isReady;
  7204. };
  7205. /**
  7206. * Is this node enabled.
  7207. * If the node has a parent and is enabled, the parent will be inspected as well.
  7208. * @return {boolean} whether this node (and its parent) is enabled.
  7209. * @see setEnabled
  7210. */
  7211. Node.prototype.isEnabled = function () {
  7212. if (!this._isEnabled) {
  7213. return false;
  7214. }
  7215. if (this.parent) {
  7216. return this.parent.isEnabled();
  7217. }
  7218. return true;
  7219. };
  7220. /**
  7221. * Set the enabled state of this node.
  7222. * @param {boolean} value - the new enabled state
  7223. * @see isEnabled
  7224. */
  7225. Node.prototype.setEnabled = function (value) {
  7226. this._isEnabled = value;
  7227. };
  7228. /**
  7229. * Is this node a descendant of the given node.
  7230. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7231. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7232. * @see parent
  7233. */
  7234. Node.prototype.isDescendantOf = function (ancestor) {
  7235. if (this.parent) {
  7236. if (this.parent === ancestor) {
  7237. return true;
  7238. }
  7239. return this.parent.isDescendantOf(ancestor);
  7240. }
  7241. return false;
  7242. };
  7243. Node.prototype._getDescendants = function (list, results) {
  7244. for (var index = 0; index < list.length; index++) {
  7245. var item = list[index];
  7246. if (item.isDescendantOf(this)) {
  7247. results.push(item);
  7248. }
  7249. }
  7250. };
  7251. /**
  7252. * Will return all nodes that have this node as parent.
  7253. * @return {BABYLON.Node[]} all children nodes of all types.
  7254. */
  7255. Node.prototype.getDescendants = function () {
  7256. var results = [];
  7257. this._getDescendants(this._scene.meshes, results);
  7258. this._getDescendants(this._scene.lights, results);
  7259. this._getDescendants(this._scene.cameras, results);
  7260. return results;
  7261. };
  7262. Node.prototype._setReady = function (state) {
  7263. if (state == this._isReady) {
  7264. return;
  7265. }
  7266. if (!state) {
  7267. this._isReady = false;
  7268. return;
  7269. }
  7270. this._isReady = true;
  7271. if (this.onReady) {
  7272. this.onReady(this);
  7273. }
  7274. };
  7275. return Node;
  7276. })();
  7277. BABYLON.Node = Node;
  7278. })(BABYLON || (BABYLON = {}));
  7279. var BABYLON;
  7280. (function (BABYLON) {
  7281. var FilesInput = (function () {
  7282. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7283. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7284. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7285. this._engine = p_engine;
  7286. this._canvas = p_canvas;
  7287. this._currentScene = p_scene;
  7288. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7289. this._progressCallback = p_progressCallback;
  7290. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7291. this._textureLoadingCallback = p_textureLoadingCallback;
  7292. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7293. }
  7294. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7295. var _this = this;
  7296. if (p_elementToMonitor) {
  7297. this._elementToMonitor = p_elementToMonitor;
  7298. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7299. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7300. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7301. }
  7302. };
  7303. FilesInput.prototype.renderFunction = function () {
  7304. if (this._additionnalRenderLoopLogicCallback) {
  7305. this._additionnalRenderLoopLogicCallback();
  7306. }
  7307. if (this._currentScene) {
  7308. if (this._textureLoadingCallback) {
  7309. var remaining = this._currentScene.getWaitingItemsCount();
  7310. if (remaining > 0) {
  7311. this._textureLoadingCallback(remaining);
  7312. }
  7313. }
  7314. this._currentScene.render();
  7315. }
  7316. };
  7317. FilesInput.prototype.drag = function (e) {
  7318. e.stopPropagation();
  7319. e.preventDefault();
  7320. };
  7321. FilesInput.prototype.drop = function (eventDrop) {
  7322. eventDrop.stopPropagation();
  7323. eventDrop.preventDefault();
  7324. this.loadFiles(eventDrop);
  7325. };
  7326. FilesInput.prototype.loadFiles = function (event) {
  7327. if (this._startingProcessingFilesCallback)
  7328. this._startingProcessingFilesCallback();
  7329. // Handling data transfer via drag'n'drop
  7330. if (event && event.dataTransfer && event.dataTransfer.files) {
  7331. this._filesToLoad = event.dataTransfer.files;
  7332. }
  7333. // Handling files from input files
  7334. if (event && event.target && event.target.files) {
  7335. this._filesToLoad = event.target.files;
  7336. }
  7337. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7338. for (var i = 0; i < this._filesToLoad.length; i++) {
  7339. switch (this._filesToLoad[i].type) {
  7340. case "image/jpeg":
  7341. case "image/png":
  7342. case "image/bmp":
  7343. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7344. break;
  7345. case "image/targa":
  7346. case "image/vnd.ms-dds":
  7347. case "audio/wav":
  7348. case "audio/x-wav":
  7349. case "audio/mp3":
  7350. case "audio/mpeg":
  7351. case "audio/mpeg3":
  7352. case "audio/x-mpeg-3":
  7353. case "audio/ogg":
  7354. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7355. break;
  7356. default:
  7357. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7358. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7359. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7360. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7361. this._sceneFileToLoad = this._filesToLoad[i];
  7362. }
  7363. break;
  7364. }
  7365. }
  7366. this.reload();
  7367. }
  7368. };
  7369. FilesInput.prototype.reload = function () {
  7370. var _this = this;
  7371. var that = this;
  7372. // If a ".babylon" file has been provided
  7373. if (this._sceneFileToLoad) {
  7374. if (this._currentScene) {
  7375. if (BABYLON.Tools.errorsCount > 0) {
  7376. BABYLON.Tools.ClearLogCache();
  7377. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7378. }
  7379. this._engine.stopRenderLoop();
  7380. this._currentScene.dispose();
  7381. }
  7382. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7383. that._currentScene = newScene;
  7384. // Wait for textures and shaders to be ready
  7385. that._currentScene.executeWhenReady(function () {
  7386. // Attach camera to canvas inputs
  7387. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7388. that._currentScene.createDefaultCameraOrLight();
  7389. }
  7390. that._currentScene.activeCamera.attachControl(that._canvas);
  7391. if (that._sceneLoadedCallback) {
  7392. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7393. }
  7394. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7395. });
  7396. }, function (progress) {
  7397. if (_this._progressCallback) {
  7398. _this._progressCallback(progress);
  7399. }
  7400. });
  7401. }
  7402. else {
  7403. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7404. }
  7405. };
  7406. FilesInput.FilesTextures = new Array();
  7407. FilesInput.FilesToLoad = new Array();
  7408. return FilesInput;
  7409. })();
  7410. BABYLON.FilesInput = FilesInput;
  7411. })(BABYLON || (BABYLON = {}));
  7412. var BABYLON;
  7413. (function (BABYLON) {
  7414. var IntersectionInfo = (function () {
  7415. function IntersectionInfo(bu, bv, distance) {
  7416. this.bu = bu;
  7417. this.bv = bv;
  7418. this.distance = distance;
  7419. this.faceId = 0;
  7420. this.subMeshId = 0;
  7421. }
  7422. return IntersectionInfo;
  7423. })();
  7424. BABYLON.IntersectionInfo = IntersectionInfo;
  7425. var PickingInfo = (function () {
  7426. function PickingInfo() {
  7427. this.hit = false;
  7428. this.distance = 0;
  7429. this.pickedPoint = null;
  7430. this.pickedMesh = null;
  7431. this.bu = 0;
  7432. this.bv = 0;
  7433. this.faceId = -1;
  7434. this.subMeshId = 0;
  7435. }
  7436. // Methods
  7437. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7438. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7439. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7440. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7441. return null;
  7442. }
  7443. var indices = this.pickedMesh.getIndices();
  7444. var result;
  7445. if (useVerticesNormals) {
  7446. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7447. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7448. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7449. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7450. normal0 = normal0.scale(this.bu);
  7451. normal1 = normal1.scale(this.bv);
  7452. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7453. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7454. }
  7455. else {
  7456. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7457. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7458. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7459. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7460. var p1p2 = vertex1.subtract(vertex2);
  7461. var p3p2 = vertex3.subtract(vertex2);
  7462. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7463. }
  7464. if (useWorldCoordinates) {
  7465. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7466. }
  7467. return BABYLON.Vector3.Normalize(result);
  7468. };
  7469. PickingInfo.prototype.getTextureCoordinates = function () {
  7470. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7471. return null;
  7472. }
  7473. var indices = this.pickedMesh.getIndices();
  7474. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7475. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7476. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7477. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7478. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7479. uv1 = uv1.scale(this.bu);
  7480. uv2 = uv2.scale(this.bv);
  7481. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7482. };
  7483. return PickingInfo;
  7484. })();
  7485. BABYLON.PickingInfo = PickingInfo;
  7486. })(BABYLON || (BABYLON = {}));
  7487. var BABYLON;
  7488. (function (BABYLON) {
  7489. var BoundingSphere = (function () {
  7490. function BoundingSphere(minimum, maximum) {
  7491. this.minimum = minimum;
  7492. this.maximum = maximum;
  7493. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7494. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7495. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7496. this.radius = distance * 0.5;
  7497. this.centerWorld = BABYLON.Vector3.Zero();
  7498. this._update(BABYLON.Matrix.Identity());
  7499. }
  7500. // Methods
  7501. BoundingSphere.prototype._update = function (world) {
  7502. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7503. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7504. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7505. };
  7506. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7507. for (var i = 0; i < 6; i++) {
  7508. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7509. return false;
  7510. }
  7511. return true;
  7512. };
  7513. BoundingSphere.prototype.intersectsPoint = function (point) {
  7514. var x = this.centerWorld.x - point.x;
  7515. var y = this.centerWorld.y - point.y;
  7516. var z = this.centerWorld.z - point.z;
  7517. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7518. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7519. return false;
  7520. return true;
  7521. };
  7522. // Statics
  7523. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7524. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7525. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7526. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7527. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7528. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7529. return false;
  7530. return true;
  7531. };
  7532. return BoundingSphere;
  7533. })();
  7534. BABYLON.BoundingSphere = BoundingSphere;
  7535. })(BABYLON || (BABYLON = {}));
  7536. var BABYLON;
  7537. (function (BABYLON) {
  7538. var BoundingBox = (function () {
  7539. function BoundingBox(minimum, maximum) {
  7540. this.minimum = minimum;
  7541. this.maximum = maximum;
  7542. this.vectors = new Array();
  7543. this.vectorsWorld = new Array();
  7544. // Bounding vectors
  7545. this.vectors.push(this.minimum.clone());
  7546. this.vectors.push(this.maximum.clone());
  7547. this.vectors.push(this.minimum.clone());
  7548. this.vectors[2].x = this.maximum.x;
  7549. this.vectors.push(this.minimum.clone());
  7550. this.vectors[3].y = this.maximum.y;
  7551. this.vectors.push(this.minimum.clone());
  7552. this.vectors[4].z = this.maximum.z;
  7553. this.vectors.push(this.maximum.clone());
  7554. this.vectors[5].z = this.minimum.z;
  7555. this.vectors.push(this.maximum.clone());
  7556. this.vectors[6].x = this.minimum.x;
  7557. this.vectors.push(this.maximum.clone());
  7558. this.vectors[7].y = this.minimum.y;
  7559. // OBB
  7560. this.center = this.maximum.add(this.minimum).scale(0.5);
  7561. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7562. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7563. // World
  7564. for (var index = 0; index < this.vectors.length; index++) {
  7565. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7566. }
  7567. this.minimumWorld = BABYLON.Vector3.Zero();
  7568. this.maximumWorld = BABYLON.Vector3.Zero();
  7569. this._update(BABYLON.Matrix.Identity());
  7570. }
  7571. // Methods
  7572. BoundingBox.prototype.getWorldMatrix = function () {
  7573. return this._worldMatrix;
  7574. };
  7575. BoundingBox.prototype._update = function (world) {
  7576. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7577. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7578. for (var index = 0; index < this.vectors.length; index++) {
  7579. var v = this.vectorsWorld[index];
  7580. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7581. if (v.x < this.minimumWorld.x)
  7582. this.minimumWorld.x = v.x;
  7583. if (v.y < this.minimumWorld.y)
  7584. this.minimumWorld.y = v.y;
  7585. if (v.z < this.minimumWorld.z)
  7586. this.minimumWorld.z = v.z;
  7587. if (v.x > this.maximumWorld.x)
  7588. this.maximumWorld.x = v.x;
  7589. if (v.y > this.maximumWorld.y)
  7590. this.maximumWorld.y = v.y;
  7591. if (v.z > this.maximumWorld.z)
  7592. this.maximumWorld.z = v.z;
  7593. }
  7594. // OBB
  7595. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7596. this.center.scaleInPlace(0.5);
  7597. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7598. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7599. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7600. this._worldMatrix = world;
  7601. };
  7602. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7603. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7604. };
  7605. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7606. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7607. };
  7608. BoundingBox.prototype.intersectsPoint = function (point) {
  7609. var delta = -BABYLON.Engine.Epsilon;
  7610. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7611. return false;
  7612. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7613. return false;
  7614. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7615. return false;
  7616. return true;
  7617. };
  7618. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7619. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7620. };
  7621. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7622. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7623. return false;
  7624. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7625. return false;
  7626. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7627. return false;
  7628. return true;
  7629. };
  7630. // Statics
  7631. BoundingBox.Intersects = function (box0, box1) {
  7632. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7633. return false;
  7634. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7635. return false;
  7636. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7637. return false;
  7638. return true;
  7639. };
  7640. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7641. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7642. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7643. return (num <= (sphereRadius * sphereRadius));
  7644. };
  7645. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7646. for (var p = 0; p < 6; p++) {
  7647. for (var i = 0; i < 8; i++) {
  7648. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7649. return false;
  7650. }
  7651. }
  7652. }
  7653. return true;
  7654. };
  7655. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7656. for (var p = 0; p < 6; p++) {
  7657. var inCount = 8;
  7658. for (var i = 0; i < 8; i++) {
  7659. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7660. --inCount;
  7661. }
  7662. else {
  7663. break;
  7664. }
  7665. }
  7666. if (inCount === 0)
  7667. return false;
  7668. }
  7669. return true;
  7670. };
  7671. return BoundingBox;
  7672. })();
  7673. BABYLON.BoundingBox = BoundingBox;
  7674. })(BABYLON || (BABYLON = {}));
  7675. var BABYLON;
  7676. (function (BABYLON) {
  7677. var computeBoxExtents = function (axis, box) {
  7678. var p = BABYLON.Vector3.Dot(box.center, axis);
  7679. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7680. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7681. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7682. var r = r0 + r1 + r2;
  7683. return {
  7684. min: p - r,
  7685. max: p + r
  7686. };
  7687. };
  7688. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7689. var axisOverlap = function (axis, box0, box1) {
  7690. var result0 = computeBoxExtents(axis, box0);
  7691. var result1 = computeBoxExtents(axis, box1);
  7692. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7693. };
  7694. var BoundingInfo = (function () {
  7695. function BoundingInfo(minimum, maximum) {
  7696. this.minimum = minimum;
  7697. this.maximum = maximum;
  7698. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7699. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7700. }
  7701. // Methods
  7702. BoundingInfo.prototype._update = function (world) {
  7703. this.boundingBox._update(world);
  7704. this.boundingSphere._update(world);
  7705. };
  7706. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7707. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7708. return false;
  7709. return this.boundingBox.isInFrustum(frustumPlanes);
  7710. };
  7711. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7712. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7713. };
  7714. BoundingInfo.prototype._checkCollision = function (collider) {
  7715. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7716. };
  7717. BoundingInfo.prototype.intersectsPoint = function (point) {
  7718. if (!this.boundingSphere.centerWorld) {
  7719. return false;
  7720. }
  7721. if (!this.boundingSphere.intersectsPoint(point)) {
  7722. return false;
  7723. }
  7724. if (!this.boundingBox.intersectsPoint(point)) {
  7725. return false;
  7726. }
  7727. return true;
  7728. };
  7729. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7730. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7731. return false;
  7732. }
  7733. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7734. return false;
  7735. }
  7736. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7737. return false;
  7738. }
  7739. if (!precise) {
  7740. return true;
  7741. }
  7742. var box0 = this.boundingBox;
  7743. var box1 = boundingInfo.boundingBox;
  7744. if (!axisOverlap(box0.directions[0], box0, box1))
  7745. return false;
  7746. if (!axisOverlap(box0.directions[1], box0, box1))
  7747. return false;
  7748. if (!axisOverlap(box0.directions[2], box0, box1))
  7749. return false;
  7750. if (!axisOverlap(box1.directions[0], box0, box1))
  7751. return false;
  7752. if (!axisOverlap(box1.directions[1], box0, box1))
  7753. return false;
  7754. if (!axisOverlap(box1.directions[2], box0, box1))
  7755. return false;
  7756. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7757. return false;
  7758. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7759. return false;
  7760. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7761. return false;
  7762. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7763. return false;
  7764. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7765. return false;
  7766. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7767. return false;
  7768. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7769. return false;
  7770. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7771. return false;
  7772. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7773. return false;
  7774. return true;
  7775. };
  7776. return BoundingInfo;
  7777. })();
  7778. BABYLON.BoundingInfo = BoundingInfo;
  7779. })(BABYLON || (BABYLON = {}));
  7780. var BABYLON;
  7781. (function (BABYLON) {
  7782. var AbstractMesh = (function (_super) {
  7783. __extends(AbstractMesh, _super);
  7784. function AbstractMesh(name, scene) {
  7785. var _this = this;
  7786. _super.call(this, name, scene);
  7787. // Properties
  7788. this.definedFacingForward = true; // orientation for POV movement & rotation
  7789. this.position = new BABYLON.Vector3(0, 0, 0);
  7790. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7791. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7792. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7793. this.visibility = 1.0;
  7794. this.alphaIndex = Number.MAX_VALUE;
  7795. this.infiniteDistance = false;
  7796. this.isVisible = true;
  7797. this.isPickable = true;
  7798. this.showBoundingBox = false;
  7799. this.showSubMeshesBoundingBox = false;
  7800. this.onDispose = null;
  7801. this.isBlocker = false;
  7802. this.renderingGroupId = 0;
  7803. this.receiveShadows = false;
  7804. this.renderOutline = false;
  7805. this.outlineColor = BABYLON.Color3.Red();
  7806. this.outlineWidth = 0.02;
  7807. this.renderOverlay = false;
  7808. this.overlayColor = BABYLON.Color3.Red();
  7809. this.overlayAlpha = 0.5;
  7810. this.hasVertexAlpha = false;
  7811. this.useVertexColors = true;
  7812. this.applyFog = true;
  7813. this.computeBonesUsingShaders = true;
  7814. this.useOctreeForRenderingSelection = true;
  7815. this.useOctreeForPicking = true;
  7816. this.useOctreeForCollisions = true;
  7817. this.layerMask = 0x0FFFFFFF;
  7818. this.alwaysSelectAsActiveMesh = false;
  7819. // Physics
  7820. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7821. // Collisions
  7822. this._checkCollisions = false;
  7823. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7824. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7825. this._collider = new BABYLON.Collider();
  7826. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7827. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7828. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7829. // Edges
  7830. this.edgesWidth = 1;
  7831. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7832. // Cache
  7833. this._localScaling = BABYLON.Matrix.Zero();
  7834. this._localRotation = BABYLON.Matrix.Zero();
  7835. this._localTranslation = BABYLON.Matrix.Zero();
  7836. this._localBillboard = BABYLON.Matrix.Zero();
  7837. this._localPivotScaling = BABYLON.Matrix.Zero();
  7838. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7839. this._localWorld = BABYLON.Matrix.Zero();
  7840. this._worldMatrix = BABYLON.Matrix.Zero();
  7841. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7842. this._absolutePosition = BABYLON.Vector3.Zero();
  7843. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7844. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7845. this._isDirty = false;
  7846. this._pivotMatrix = BABYLON.Matrix.Identity();
  7847. this._isDisposed = false;
  7848. this._renderId = 0;
  7849. this._intersectionsInProgress = new Array();
  7850. this._onAfterWorldMatrixUpdate = new Array();
  7851. this._isWorldMatrixFrozen = false;
  7852. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7853. if (collidedMesh === void 0) { collidedMesh = null; }
  7854. //TODO move this to the collision coordinator!
  7855. if (_this.getScene().workerCollisions)
  7856. newPosition.multiplyInPlace(_this._collider.radius);
  7857. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7858. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7859. _this.position.addInPlace(_this._diffPositionForCollisions);
  7860. }
  7861. if (_this.onCollide && collidedMesh) {
  7862. _this.onCollide(collidedMesh);
  7863. }
  7864. };
  7865. scene.addMesh(this);
  7866. }
  7867. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7868. get: function () {
  7869. return AbstractMesh._BILLBOARDMODE_NONE;
  7870. },
  7871. enumerable: true,
  7872. configurable: true
  7873. });
  7874. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7875. get: function () {
  7876. return AbstractMesh._BILLBOARDMODE_X;
  7877. },
  7878. enumerable: true,
  7879. configurable: true
  7880. });
  7881. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7882. get: function () {
  7883. return AbstractMesh._BILLBOARDMODE_Y;
  7884. },
  7885. enumerable: true,
  7886. configurable: true
  7887. });
  7888. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7889. get: function () {
  7890. return AbstractMesh._BILLBOARDMODE_Z;
  7891. },
  7892. enumerable: true,
  7893. configurable: true
  7894. });
  7895. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7896. get: function () {
  7897. return AbstractMesh._BILLBOARDMODE_ALL;
  7898. },
  7899. enumerable: true,
  7900. configurable: true
  7901. });
  7902. // Methods
  7903. AbstractMesh.prototype.disableEdgesRendering = function () {
  7904. if (this._edgesRenderer !== undefined) {
  7905. this._edgesRenderer.dispose();
  7906. this._edgesRenderer = undefined;
  7907. }
  7908. };
  7909. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7910. if (epsilon === void 0) { epsilon = 0.95; }
  7911. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7912. this.disableEdgesRendering();
  7913. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7914. };
  7915. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7916. get: function () {
  7917. return false;
  7918. },
  7919. enumerable: true,
  7920. configurable: true
  7921. });
  7922. AbstractMesh.prototype.getLOD = function (camera) {
  7923. return this;
  7924. };
  7925. AbstractMesh.prototype.getTotalVertices = function () {
  7926. return 0;
  7927. };
  7928. AbstractMesh.prototype.getIndices = function () {
  7929. return null;
  7930. };
  7931. AbstractMesh.prototype.getVerticesData = function (kind) {
  7932. return null;
  7933. };
  7934. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7935. return false;
  7936. };
  7937. AbstractMesh.prototype.getBoundingInfo = function () {
  7938. if (this._masterMesh) {
  7939. return this._masterMesh.getBoundingInfo();
  7940. }
  7941. if (!this._boundingInfo) {
  7942. this._updateBoundingInfo();
  7943. }
  7944. return this._boundingInfo;
  7945. };
  7946. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7947. get: function () {
  7948. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7949. },
  7950. enumerable: true,
  7951. configurable: true
  7952. });
  7953. AbstractMesh.prototype._preActivate = function () {
  7954. };
  7955. AbstractMesh.prototype._activate = function (renderId) {
  7956. this._renderId = renderId;
  7957. };
  7958. AbstractMesh.prototype.getWorldMatrix = function () {
  7959. if (this._masterMesh) {
  7960. return this._masterMesh.getWorldMatrix();
  7961. }
  7962. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7963. this.computeWorldMatrix();
  7964. }
  7965. return this._worldMatrix;
  7966. };
  7967. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7968. get: function () {
  7969. return this._worldMatrix;
  7970. },
  7971. enumerable: true,
  7972. configurable: true
  7973. });
  7974. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7975. get: function () {
  7976. return this._absolutePosition;
  7977. },
  7978. enumerable: true,
  7979. configurable: true
  7980. });
  7981. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7982. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7983. this.computeWorldMatrix(true);
  7984. this._isWorldMatrixFrozen = true;
  7985. };
  7986. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7987. this._isWorldMatrixFrozen = false;
  7988. this.computeWorldMatrix(true);
  7989. };
  7990. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7991. get: function () {
  7992. return this._isWorldMatrixFrozen;
  7993. },
  7994. enumerable: true,
  7995. configurable: true
  7996. });
  7997. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7998. axis.normalize();
  7999. if (!this.rotationQuaternion) {
  8000. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8001. this.rotation = BABYLON.Vector3.Zero();
  8002. }
  8003. if (!space || space === BABYLON.Space.LOCAL) {
  8004. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8005. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8006. }
  8007. else {
  8008. if (this.parent) {
  8009. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8010. invertParentWorldMatrix.invert();
  8011. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8012. }
  8013. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8014. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8015. }
  8016. };
  8017. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8018. var displacementVector = axis.scale(distance);
  8019. if (!space || space === BABYLON.Space.LOCAL) {
  8020. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8021. this.setPositionWithLocalVector(tempV3);
  8022. }
  8023. else {
  8024. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8025. }
  8026. };
  8027. AbstractMesh.prototype.getAbsolutePosition = function () {
  8028. this.computeWorldMatrix();
  8029. return this._absolutePosition;
  8030. };
  8031. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8032. if (!absolutePosition) {
  8033. return;
  8034. }
  8035. var absolutePositionX;
  8036. var absolutePositionY;
  8037. var absolutePositionZ;
  8038. if (absolutePosition.x === undefined) {
  8039. if (arguments.length < 3) {
  8040. return;
  8041. }
  8042. absolutePositionX = arguments[0];
  8043. absolutePositionY = arguments[1];
  8044. absolutePositionZ = arguments[2];
  8045. }
  8046. else {
  8047. absolutePositionX = absolutePosition.x;
  8048. absolutePositionY = absolutePosition.y;
  8049. absolutePositionZ = absolutePosition.z;
  8050. }
  8051. if (this.parent) {
  8052. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8053. invertParentWorldMatrix.invert();
  8054. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8055. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8056. }
  8057. else {
  8058. this.position.x = absolutePositionX;
  8059. this.position.y = absolutePositionY;
  8060. this.position.z = absolutePositionZ;
  8061. }
  8062. };
  8063. // ================================== Point of View Movement =================================
  8064. /**
  8065. * Perform relative position change from the point of view of behind the front of the mesh.
  8066. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8067. * Supports definition of mesh facing forward or backward.
  8068. * @param {number} amountRight
  8069. * @param {number} amountUp
  8070. * @param {number} amountForward
  8071. */
  8072. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8073. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8074. };
  8075. /**
  8076. * Calculate relative position change from the point of view of behind the front of the mesh.
  8077. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8078. * Supports definition of mesh facing forward or backward.
  8079. * @param {number} amountRight
  8080. * @param {number} amountUp
  8081. * @param {number} amountForward
  8082. */
  8083. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8084. var rotMatrix = new BABYLON.Matrix();
  8085. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8086. rotQuaternion.toRotationMatrix(rotMatrix);
  8087. var translationDelta = BABYLON.Vector3.Zero();
  8088. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8089. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8090. return translationDelta;
  8091. };
  8092. // ================================== Point of View Rotation =================================
  8093. /**
  8094. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8095. * Supports definition of mesh facing forward or backward.
  8096. * @param {number} flipBack
  8097. * @param {number} twirlClockwise
  8098. * @param {number} tiltRight
  8099. */
  8100. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8101. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8102. };
  8103. /**
  8104. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8105. * Supports definition of mesh facing forward or backward.
  8106. * @param {number} flipBack
  8107. * @param {number} twirlClockwise
  8108. * @param {number} tiltRight
  8109. */
  8110. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8111. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8112. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8113. };
  8114. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8115. this._pivotMatrix = matrix;
  8116. this._cache.pivotMatrixUpdated = true;
  8117. };
  8118. AbstractMesh.prototype.getPivotMatrix = function () {
  8119. return this._pivotMatrix;
  8120. };
  8121. AbstractMesh.prototype._isSynchronized = function () {
  8122. if (this._isDirty) {
  8123. return false;
  8124. }
  8125. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8126. return false;
  8127. if (this._cache.pivotMatrixUpdated) {
  8128. return false;
  8129. }
  8130. if (this.infiniteDistance) {
  8131. return false;
  8132. }
  8133. if (!this._cache.position.equals(this.position))
  8134. return false;
  8135. if (this.rotationQuaternion) {
  8136. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8137. return false;
  8138. }
  8139. else {
  8140. if (!this._cache.rotation.equals(this.rotation))
  8141. return false;
  8142. }
  8143. if (!this._cache.scaling.equals(this.scaling))
  8144. return false;
  8145. return true;
  8146. };
  8147. AbstractMesh.prototype._initCache = function () {
  8148. _super.prototype._initCache.call(this);
  8149. this._cache.localMatrixUpdated = false;
  8150. this._cache.position = BABYLON.Vector3.Zero();
  8151. this._cache.scaling = BABYLON.Vector3.Zero();
  8152. this._cache.rotation = BABYLON.Vector3.Zero();
  8153. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8154. };
  8155. AbstractMesh.prototype.markAsDirty = function (property) {
  8156. if (property === "rotation") {
  8157. this.rotationQuaternion = null;
  8158. }
  8159. this._currentRenderId = Number.MAX_VALUE;
  8160. this._isDirty = true;
  8161. };
  8162. AbstractMesh.prototype._updateBoundingInfo = function () {
  8163. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8164. this._boundingInfo._update(this.worldMatrixFromCache);
  8165. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8166. };
  8167. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8168. if (!this.subMeshes) {
  8169. return;
  8170. }
  8171. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8172. var subMesh = this.subMeshes[subIndex];
  8173. subMesh.updateBoundingInfo(matrix);
  8174. }
  8175. };
  8176. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8177. if (this._isWorldMatrixFrozen) {
  8178. return this._worldMatrix;
  8179. }
  8180. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8181. return this._worldMatrix;
  8182. }
  8183. this._cache.position.copyFrom(this.position);
  8184. this._cache.scaling.copyFrom(this.scaling);
  8185. this._cache.pivotMatrixUpdated = false;
  8186. this._currentRenderId = this.getScene().getRenderId();
  8187. this._isDirty = false;
  8188. // Scaling
  8189. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8190. // Rotation
  8191. if (this.rotationQuaternion) {
  8192. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8193. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8194. }
  8195. else {
  8196. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8197. this._cache.rotation.copyFrom(this.rotation);
  8198. }
  8199. // Translation
  8200. if (this.infiniteDistance && !this.parent) {
  8201. var camera = this.getScene().activeCamera;
  8202. if (camera) {
  8203. var cameraWorldMatrix = camera.getWorldMatrix();
  8204. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8205. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8206. }
  8207. }
  8208. else {
  8209. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8210. }
  8211. // Composing transformations
  8212. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8213. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8214. // Billboarding
  8215. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8216. var localPosition = this.position.clone();
  8217. var zero = this.getScene().activeCamera.globalPosition.clone();
  8218. if (this.parent && this.parent.position) {
  8219. localPosition.addInPlace(this.parent.position);
  8220. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8221. }
  8222. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  8223. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8224. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8225. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8226. zero.y = localPosition.y + 0.001;
  8227. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8228. zero.z = localPosition.z + 0.001;
  8229. }
  8230. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8231. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8232. this._localBillboard.invert();
  8233. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8234. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8235. }
  8236. // Local world
  8237. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8238. // Parent
  8239. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8240. this._markSyncedWithParent();
  8241. if (this._meshToBoneReferal) {
  8242. if (!this._localMeshReferalTransform) {
  8243. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8244. }
  8245. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8246. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8247. }
  8248. else {
  8249. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8250. }
  8251. }
  8252. else {
  8253. this._worldMatrix.copyFrom(this._localWorld);
  8254. }
  8255. // Bounding info
  8256. this._updateBoundingInfo();
  8257. // Absolute position
  8258. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8259. // Callbacks
  8260. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8261. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8262. }
  8263. return this._worldMatrix;
  8264. };
  8265. /**
  8266. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8267. * @param func: callback function to add
  8268. */
  8269. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8270. this._onAfterWorldMatrixUpdate.push(func);
  8271. };
  8272. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8273. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8274. if (index > -1) {
  8275. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8276. }
  8277. };
  8278. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8279. this.computeWorldMatrix();
  8280. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8281. };
  8282. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8283. this.computeWorldMatrix();
  8284. var invLocalWorldMatrix = this._localWorld.clone();
  8285. invLocalWorldMatrix.invert();
  8286. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8287. };
  8288. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8289. this.computeWorldMatrix(true);
  8290. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8291. };
  8292. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8293. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8294. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8295. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8296. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8297. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8298. /// <returns>Mesh oriented towards targetMesh</returns>
  8299. yawCor = yawCor || 0; // default to zero if undefined
  8300. pitchCor = pitchCor || 0;
  8301. rollCor = rollCor || 0;
  8302. var dv = targetPoint.subtract(this.position);
  8303. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8304. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8305. var pitch = Math.atan2(dv.y, len);
  8306. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8307. };
  8308. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8309. this._meshToBoneReferal = affectedMesh;
  8310. this.parent = bone;
  8311. };
  8312. AbstractMesh.prototype.detachFromBone = function () {
  8313. this._meshToBoneReferal = null;
  8314. this.parent = null;
  8315. };
  8316. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8317. return this._boundingInfo.isInFrustum(frustumPlanes);
  8318. };
  8319. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8320. if (!camera) {
  8321. camera = this.getScene().activeCamera;
  8322. }
  8323. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8324. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8325. return false;
  8326. }
  8327. return true;
  8328. };
  8329. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8330. if (!this._boundingInfo || !mesh._boundingInfo) {
  8331. return false;
  8332. }
  8333. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8334. };
  8335. AbstractMesh.prototype.intersectsPoint = function (point) {
  8336. if (!this._boundingInfo) {
  8337. return false;
  8338. }
  8339. return this._boundingInfo.intersectsPoint(point);
  8340. };
  8341. // Physics
  8342. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8343. var physicsEngine = this.getScene().getPhysicsEngine();
  8344. if (!physicsEngine) {
  8345. return;
  8346. }
  8347. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8348. if (impostor.impostor) {
  8349. // Old API
  8350. options = impostor;
  8351. impostor = impostor.impostor;
  8352. }
  8353. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8354. physicsEngine._unregisterMesh(this);
  8355. return;
  8356. }
  8357. if (!options) {
  8358. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8359. }
  8360. else {
  8361. if (!options.mass && options.mass !== 0)
  8362. options.mass = 0;
  8363. if (!options.friction && options.friction !== 0)
  8364. options.friction = 0.2;
  8365. if (!options.restitution && options.restitution !== 0)
  8366. options.restitution = 0.2;
  8367. }
  8368. this._physicImpostor = impostor;
  8369. this._physicsMass = options.mass;
  8370. this._physicsFriction = options.friction;
  8371. this._physicRestitution = options.restitution;
  8372. return physicsEngine._registerMesh(this, impostor, options);
  8373. };
  8374. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8375. if (!this._physicImpostor) {
  8376. return BABYLON.PhysicsEngine.NoImpostor;
  8377. }
  8378. return this._physicImpostor;
  8379. };
  8380. AbstractMesh.prototype.getPhysicsMass = function () {
  8381. if (!this._physicsMass) {
  8382. return 0;
  8383. }
  8384. return this._physicsMass;
  8385. };
  8386. AbstractMesh.prototype.getPhysicsFriction = function () {
  8387. if (!this._physicsFriction) {
  8388. return 0;
  8389. }
  8390. return this._physicsFriction;
  8391. };
  8392. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8393. if (!this._physicRestitution) {
  8394. return 0;
  8395. }
  8396. return this._physicRestitution;
  8397. };
  8398. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8399. if (!camera) {
  8400. camera = this.getScene().activeCamera;
  8401. }
  8402. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8403. };
  8404. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8405. if (!camera) {
  8406. camera = this.getScene().activeCamera;
  8407. }
  8408. return this.absolutePosition.subtract(camera.position).length();
  8409. };
  8410. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8411. if (!this._physicImpostor) {
  8412. return;
  8413. }
  8414. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8415. };
  8416. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8417. if (!this._physicImpostor) {
  8418. return;
  8419. }
  8420. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8421. };
  8422. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8423. if (!this._physicImpostor) {
  8424. return;
  8425. }
  8426. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8427. };
  8428. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8429. // Collisions
  8430. get: function () {
  8431. return this._checkCollisions;
  8432. },
  8433. set: function (collisionEnabled) {
  8434. this._checkCollisions = collisionEnabled;
  8435. if (this.getScene().workerCollisions) {
  8436. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8437. }
  8438. },
  8439. enumerable: true,
  8440. configurable: true
  8441. });
  8442. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8443. var globalPosition = this.getAbsolutePosition();
  8444. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8445. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8446. this._collider.radius = this.ellipsoid;
  8447. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8448. };
  8449. // Submeshes octree
  8450. /**
  8451. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8452. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8453. */
  8454. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8455. if (maxCapacity === void 0) { maxCapacity = 64; }
  8456. if (maxDepth === void 0) { maxDepth = 2; }
  8457. if (!this._submeshesOctree) {
  8458. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8459. }
  8460. this.computeWorldMatrix(true);
  8461. // Update octree
  8462. var bbox = this.getBoundingInfo().boundingBox;
  8463. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8464. return this._submeshesOctree;
  8465. };
  8466. // Collisions
  8467. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8468. this._generatePointsArray();
  8469. // Transformation
  8470. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8471. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8472. subMesh._lastColliderWorldVertices = [];
  8473. subMesh._trianglePlanes = [];
  8474. var start = subMesh.verticesStart;
  8475. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8476. for (var i = start; i < end; i++) {
  8477. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8478. }
  8479. }
  8480. // Collide
  8481. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8482. if (collider.collisionFound) {
  8483. collider.collidedMesh = this;
  8484. }
  8485. };
  8486. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8487. var subMeshes;
  8488. var len;
  8489. // Octrees
  8490. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8491. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8492. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8493. len = intersections.length;
  8494. subMeshes = intersections.data;
  8495. }
  8496. else {
  8497. subMeshes = this.subMeshes;
  8498. len = subMeshes.length;
  8499. }
  8500. for (var index = 0; index < len; index++) {
  8501. var subMesh = subMeshes[index];
  8502. // Bounding test
  8503. if (len > 1 && !subMesh._checkCollision(collider))
  8504. continue;
  8505. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8506. }
  8507. };
  8508. AbstractMesh.prototype._checkCollision = function (collider) {
  8509. // Bounding box test
  8510. if (!this._boundingInfo._checkCollision(collider))
  8511. return;
  8512. // Transformation matrix
  8513. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8514. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8515. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8516. };
  8517. // Picking
  8518. AbstractMesh.prototype._generatePointsArray = function () {
  8519. return false;
  8520. };
  8521. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8522. var pickingInfo = new BABYLON.PickingInfo();
  8523. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8524. return pickingInfo;
  8525. }
  8526. if (!this._generatePointsArray()) {
  8527. return pickingInfo;
  8528. }
  8529. var intersectInfo = null;
  8530. // Octrees
  8531. var subMeshes;
  8532. var len;
  8533. if (this._submeshesOctree && this.useOctreeForPicking) {
  8534. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8535. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8536. len = intersections.length;
  8537. subMeshes = intersections.data;
  8538. }
  8539. else {
  8540. subMeshes = this.subMeshes;
  8541. len = subMeshes.length;
  8542. }
  8543. for (var index = 0; index < len; index++) {
  8544. var subMesh = subMeshes[index];
  8545. // Bounding test
  8546. if (len > 1 && !subMesh.canIntersects(ray))
  8547. continue;
  8548. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8549. if (currentIntersectInfo) {
  8550. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8551. intersectInfo = currentIntersectInfo;
  8552. intersectInfo.subMeshId = index;
  8553. if (fastCheck) {
  8554. break;
  8555. }
  8556. }
  8557. }
  8558. }
  8559. if (intersectInfo) {
  8560. // Get picked point
  8561. var world = this.getWorldMatrix();
  8562. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8563. var direction = ray.direction.clone();
  8564. direction = direction.scale(intersectInfo.distance);
  8565. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8566. var pickedPoint = worldOrigin.add(worldDirection);
  8567. // Return result
  8568. pickingInfo.hit = true;
  8569. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8570. pickingInfo.pickedPoint = pickedPoint;
  8571. pickingInfo.pickedMesh = this;
  8572. pickingInfo.bu = intersectInfo.bu;
  8573. pickingInfo.bv = intersectInfo.bv;
  8574. pickingInfo.faceId = intersectInfo.faceId;
  8575. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8576. return pickingInfo;
  8577. }
  8578. return pickingInfo;
  8579. };
  8580. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8581. return null;
  8582. };
  8583. AbstractMesh.prototype.releaseSubMeshes = function () {
  8584. if (this.subMeshes) {
  8585. while (this.subMeshes.length) {
  8586. this.subMeshes[0].dispose();
  8587. }
  8588. }
  8589. else {
  8590. this.subMeshes = new Array();
  8591. }
  8592. };
  8593. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8594. var index;
  8595. // Physics
  8596. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8597. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8598. }
  8599. // Intersections in progress
  8600. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8601. var other = this._intersectionsInProgress[index];
  8602. var pos = other._intersectionsInProgress.indexOf(this);
  8603. other._intersectionsInProgress.splice(pos, 1);
  8604. }
  8605. this._intersectionsInProgress = [];
  8606. // Edges
  8607. if (this._edgesRenderer) {
  8608. this._edgesRenderer.dispose();
  8609. this._edgesRenderer = null;
  8610. }
  8611. // SubMeshes
  8612. this.releaseSubMeshes();
  8613. // Remove from scene
  8614. this.getScene().removeMesh(this);
  8615. if (!doNotRecurse) {
  8616. // Particles
  8617. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8618. if (this.getScene().particleSystems[index].emitter === this) {
  8619. this.getScene().particleSystems[index].dispose();
  8620. index--;
  8621. }
  8622. }
  8623. // Children
  8624. var objects = this.getScene().meshes.slice(0);
  8625. for (index = 0; index < objects.length; index++) {
  8626. if (objects[index].parent === this) {
  8627. objects[index].dispose();
  8628. }
  8629. }
  8630. }
  8631. else {
  8632. for (index = 0; index < this.getScene().meshes.length; index++) {
  8633. var obj = this.getScene().meshes[index];
  8634. if (obj.parent === this) {
  8635. obj.parent = null;
  8636. obj.computeWorldMatrix(true);
  8637. }
  8638. }
  8639. }
  8640. this._onAfterWorldMatrixUpdate = [];
  8641. this._isDisposed = true;
  8642. // Callback
  8643. if (this.onDispose) {
  8644. this.onDispose();
  8645. }
  8646. };
  8647. // Statics
  8648. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8649. AbstractMesh._BILLBOARDMODE_X = 1;
  8650. AbstractMesh._BILLBOARDMODE_Y = 2;
  8651. AbstractMesh._BILLBOARDMODE_Z = 4;
  8652. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8653. return AbstractMesh;
  8654. })(BABYLON.Node);
  8655. BABYLON.AbstractMesh = AbstractMesh;
  8656. })(BABYLON || (BABYLON = {}));
  8657. var BABYLON;
  8658. (function (BABYLON) {
  8659. var Light = (function (_super) {
  8660. __extends(Light, _super);
  8661. function Light(name, scene) {
  8662. _super.call(this, name, scene);
  8663. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8664. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8665. this.intensity = 1.0;
  8666. this.range = Number.MAX_VALUE;
  8667. this.includeOnlyWithLayerMask = 0;
  8668. this.includedOnlyMeshes = new Array();
  8669. this.excludedMeshes = new Array();
  8670. this.excludeWithLayerMask = 0;
  8671. this._excludedMeshesIds = new Array();
  8672. this._includedOnlyMeshesIds = new Array();
  8673. scene.addLight(this);
  8674. }
  8675. Light.prototype.getShadowGenerator = function () {
  8676. return this._shadowGenerator;
  8677. };
  8678. Light.prototype.getAbsolutePosition = function () {
  8679. return BABYLON.Vector3.Zero();
  8680. };
  8681. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8682. };
  8683. Light.prototype._getWorldMatrix = function () {
  8684. return BABYLON.Matrix.Identity();
  8685. };
  8686. Light.prototype.canAffectMesh = function (mesh) {
  8687. if (!mesh) {
  8688. return true;
  8689. }
  8690. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8691. return false;
  8692. }
  8693. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8694. return false;
  8695. }
  8696. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8697. return false;
  8698. }
  8699. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8700. return false;
  8701. }
  8702. return true;
  8703. };
  8704. Light.prototype.getWorldMatrix = function () {
  8705. this._currentRenderId = this.getScene().getRenderId();
  8706. var worldMatrix = this._getWorldMatrix();
  8707. if (this.parent && this.parent.getWorldMatrix) {
  8708. if (!this._parentedWorldMatrix) {
  8709. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8710. }
  8711. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8712. this._markSyncedWithParent();
  8713. return this._parentedWorldMatrix;
  8714. }
  8715. return worldMatrix;
  8716. };
  8717. Light.prototype.dispose = function () {
  8718. if (this._shadowGenerator) {
  8719. this._shadowGenerator.dispose();
  8720. this._shadowGenerator = null;
  8721. }
  8722. // Remove from scene
  8723. this.getScene().removeLight(this);
  8724. };
  8725. return Light;
  8726. })(BABYLON.Node);
  8727. BABYLON.Light = Light;
  8728. })(BABYLON || (BABYLON = {}));
  8729. var BABYLON;
  8730. (function (BABYLON) {
  8731. var PointLight = (function (_super) {
  8732. __extends(PointLight, _super);
  8733. function PointLight(name, position, scene) {
  8734. _super.call(this, name, scene);
  8735. this.position = position;
  8736. }
  8737. PointLight.prototype.getAbsolutePosition = function () {
  8738. return this._transformedPosition ? this._transformedPosition : this.position;
  8739. };
  8740. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8741. if (this.parent && this.parent.getWorldMatrix) {
  8742. if (!this._transformedPosition) {
  8743. this._transformedPosition = BABYLON.Vector3.Zero();
  8744. }
  8745. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8746. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8747. return;
  8748. }
  8749. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8750. };
  8751. PointLight.prototype.getShadowGenerator = function () {
  8752. return null;
  8753. };
  8754. PointLight.prototype._getWorldMatrix = function () {
  8755. if (!this._worldMatrix) {
  8756. this._worldMatrix = BABYLON.Matrix.Identity();
  8757. }
  8758. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8759. return this._worldMatrix;
  8760. };
  8761. return PointLight;
  8762. })(BABYLON.Light);
  8763. BABYLON.PointLight = PointLight;
  8764. })(BABYLON || (BABYLON = {}));
  8765. var BABYLON;
  8766. (function (BABYLON) {
  8767. var SpotLight = (function (_super) {
  8768. __extends(SpotLight, _super);
  8769. function SpotLight(name, position, direction, angle, exponent, scene) {
  8770. _super.call(this, name, scene);
  8771. this.position = position;
  8772. this.direction = direction;
  8773. this.angle = angle;
  8774. this.exponent = exponent;
  8775. }
  8776. SpotLight.prototype.getAbsolutePosition = function () {
  8777. return this.transformedPosition ? this.transformedPosition : this.position;
  8778. };
  8779. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8780. var activeCamera = this.getScene().activeCamera;
  8781. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8782. };
  8783. SpotLight.prototype.supportsVSM = function () {
  8784. return true;
  8785. };
  8786. SpotLight.prototype.needRefreshPerFrame = function () {
  8787. return false;
  8788. };
  8789. SpotLight.prototype.setDirectionToTarget = function (target) {
  8790. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8791. return this.direction;
  8792. };
  8793. SpotLight.prototype.computeTransformedPosition = function () {
  8794. if (this.parent && this.parent.getWorldMatrix) {
  8795. if (!this.transformedPosition) {
  8796. this.transformedPosition = BABYLON.Vector3.Zero();
  8797. }
  8798. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8799. return true;
  8800. }
  8801. return false;
  8802. };
  8803. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8804. var normalizeDirection;
  8805. if (this.parent && this.parent.getWorldMatrix) {
  8806. if (!this._transformedDirection) {
  8807. this._transformedDirection = BABYLON.Vector3.Zero();
  8808. }
  8809. this.computeTransformedPosition();
  8810. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8811. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8812. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8813. }
  8814. else {
  8815. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8816. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8817. }
  8818. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8819. };
  8820. SpotLight.prototype._getWorldMatrix = function () {
  8821. if (!this._worldMatrix) {
  8822. this._worldMatrix = BABYLON.Matrix.Identity();
  8823. }
  8824. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8825. return this._worldMatrix;
  8826. };
  8827. return SpotLight;
  8828. })(BABYLON.Light);
  8829. BABYLON.SpotLight = SpotLight;
  8830. })(BABYLON || (BABYLON = {}));
  8831. var BABYLON;
  8832. (function (BABYLON) {
  8833. var HemisphericLight = (function (_super) {
  8834. __extends(HemisphericLight, _super);
  8835. function HemisphericLight(name, direction, scene) {
  8836. _super.call(this, name, scene);
  8837. this.direction = direction;
  8838. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8839. }
  8840. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8841. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8842. return this.direction;
  8843. };
  8844. HemisphericLight.prototype.getShadowGenerator = function () {
  8845. return null;
  8846. };
  8847. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8848. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8849. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8850. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8851. };
  8852. HemisphericLight.prototype._getWorldMatrix = function () {
  8853. if (!this._worldMatrix) {
  8854. this._worldMatrix = BABYLON.Matrix.Identity();
  8855. }
  8856. return this._worldMatrix;
  8857. };
  8858. return HemisphericLight;
  8859. })(BABYLON.Light);
  8860. BABYLON.HemisphericLight = HemisphericLight;
  8861. })(BABYLON || (BABYLON = {}));
  8862. var BABYLON;
  8863. (function (BABYLON) {
  8864. var DirectionalLight = (function (_super) {
  8865. __extends(DirectionalLight, _super);
  8866. function DirectionalLight(name, direction, scene) {
  8867. _super.call(this, name, scene);
  8868. this.direction = direction;
  8869. this.shadowOrthoScale = 0.5;
  8870. this.position = direction.scale(-1);
  8871. }
  8872. DirectionalLight.prototype.getAbsolutePosition = function () {
  8873. return this.transformedPosition ? this.transformedPosition : this.position;
  8874. };
  8875. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8876. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8877. return this.direction;
  8878. };
  8879. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8880. var orthoLeft = Number.MAX_VALUE;
  8881. var orthoRight = Number.MIN_VALUE;
  8882. var orthoTop = Number.MIN_VALUE;
  8883. var orthoBottom = Number.MAX_VALUE;
  8884. var tempVector3 = BABYLON.Vector3.Zero();
  8885. var activeCamera = this.getScene().activeCamera;
  8886. // Check extends
  8887. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8888. var mesh = renderList[meshIndex];
  8889. if (!mesh) {
  8890. continue;
  8891. }
  8892. var boundingInfo = mesh.getBoundingInfo();
  8893. if (!boundingInfo) {
  8894. continue;
  8895. }
  8896. var boundingBox = boundingInfo.boundingBox;
  8897. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8898. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8899. if (tempVector3.x < orthoLeft)
  8900. orthoLeft = tempVector3.x;
  8901. if (tempVector3.y < orthoBottom)
  8902. orthoBottom = tempVector3.y;
  8903. if (tempVector3.x > orthoRight)
  8904. orthoRight = tempVector3.x;
  8905. if (tempVector3.y > orthoTop)
  8906. orthoTop = tempVector3.y;
  8907. }
  8908. }
  8909. var xOffset = orthoRight - orthoLeft;
  8910. var yOffset = orthoTop - orthoBottom;
  8911. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8912. };
  8913. DirectionalLight.prototype.supportsVSM = function () {
  8914. return true;
  8915. };
  8916. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8917. return true;
  8918. };
  8919. DirectionalLight.prototype.computeTransformedPosition = function () {
  8920. if (this.parent && this.parent.getWorldMatrix) {
  8921. if (!this.transformedPosition) {
  8922. this.transformedPosition = BABYLON.Vector3.Zero();
  8923. }
  8924. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8925. return true;
  8926. }
  8927. return false;
  8928. };
  8929. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8930. if (this.parent && this.parent.getWorldMatrix) {
  8931. if (!this._transformedDirection) {
  8932. this._transformedDirection = BABYLON.Vector3.Zero();
  8933. }
  8934. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8935. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8936. return;
  8937. }
  8938. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8939. };
  8940. DirectionalLight.prototype._getWorldMatrix = function () {
  8941. if (!this._worldMatrix) {
  8942. this._worldMatrix = BABYLON.Matrix.Identity();
  8943. }
  8944. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8945. return this._worldMatrix;
  8946. };
  8947. return DirectionalLight;
  8948. })(BABYLON.Light);
  8949. BABYLON.DirectionalLight = DirectionalLight;
  8950. })(BABYLON || (BABYLON = {}));
  8951. var BABYLON;
  8952. (function (BABYLON) {
  8953. var ShadowGenerator = (function () {
  8954. function ShadowGenerator(mapSize, light) {
  8955. var _this = this;
  8956. // Members
  8957. this._filter = ShadowGenerator.FILTER_NONE;
  8958. this.blurScale = 2;
  8959. this._blurBoxOffset = 0;
  8960. this._bias = 0.00005;
  8961. this._lightDirection = BABYLON.Vector3.Zero();
  8962. this._darkness = 0;
  8963. this._transparencyShadow = false;
  8964. this._viewMatrix = BABYLON.Matrix.Zero();
  8965. this._projectionMatrix = BABYLON.Matrix.Zero();
  8966. this._transformMatrix = BABYLON.Matrix.Zero();
  8967. this._worldViewProjection = BABYLON.Matrix.Zero();
  8968. this._light = light;
  8969. this._scene = light.getScene();
  8970. this._mapSize = mapSize;
  8971. light._shadowGenerator = this;
  8972. // Render target
  8973. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8974. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8975. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8976. this._shadowMap.anisotropicFilteringLevel = 1;
  8977. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8978. this._shadowMap.renderParticles = false;
  8979. this._shadowMap.onAfterUnbind = function () {
  8980. if (!_this.useBlurVarianceShadowMap) {
  8981. return;
  8982. }
  8983. if (!_this._shadowMap2) {
  8984. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8985. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8986. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8987. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8988. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8989. _this._downSamplePostprocess.onApply = function (effect) {
  8990. effect.setTexture("textureSampler", _this._shadowMap);
  8991. };
  8992. _this.blurBoxOffset = 1;
  8993. }
  8994. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8995. };
  8996. // Custom render function
  8997. var renderSubMesh = function (subMesh) {
  8998. var mesh = subMesh.getRenderingMesh();
  8999. var scene = _this._scene;
  9000. var engine = scene.getEngine();
  9001. // Culling
  9002. engine.setState(subMesh.getMaterial().backFaceCulling);
  9003. // Managing instances
  9004. var batch = mesh._getInstancesRenderList(subMesh._id);
  9005. if (batch.mustReturn) {
  9006. return;
  9007. }
  9008. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  9009. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9010. engine.enableEffect(_this._effect);
  9011. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9012. var material = subMesh.getMaterial();
  9013. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9014. // Alpha test
  9015. if (material && material.needAlphaTesting()) {
  9016. var alphaTexture = material.getAlphaTestTexture();
  9017. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9018. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9019. }
  9020. // Bones
  9021. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9022. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  9023. }
  9024. // Draw
  9025. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9026. }
  9027. else {
  9028. // Need to reset refresh rate of the shadowMap
  9029. _this._shadowMap.resetRefreshCounter();
  9030. }
  9031. };
  9032. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9033. var index;
  9034. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9035. renderSubMesh(opaqueSubMeshes.data[index]);
  9036. }
  9037. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9038. renderSubMesh(alphaTestSubMeshes.data[index]);
  9039. }
  9040. if (_this._transparencyShadow) {
  9041. for (index = 0; index < transparentSubMeshes.length; index++) {
  9042. renderSubMesh(transparentSubMeshes.data[index]);
  9043. }
  9044. }
  9045. };
  9046. this._shadowMap.onClear = function (engine) {
  9047. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9048. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9049. }
  9050. else {
  9051. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9052. }
  9053. };
  9054. }
  9055. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9056. // Static
  9057. get: function () {
  9058. return ShadowGenerator._FILTER_NONE;
  9059. },
  9060. enumerable: true,
  9061. configurable: true
  9062. });
  9063. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9064. get: function () {
  9065. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9066. },
  9067. enumerable: true,
  9068. configurable: true
  9069. });
  9070. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9071. get: function () {
  9072. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9073. },
  9074. enumerable: true,
  9075. configurable: true
  9076. });
  9077. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9078. get: function () {
  9079. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9080. },
  9081. enumerable: true,
  9082. configurable: true
  9083. });
  9084. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9085. get: function () {
  9086. return this._bias;
  9087. },
  9088. set: function (bias) {
  9089. this._bias = bias;
  9090. },
  9091. enumerable: true,
  9092. configurable: true
  9093. });
  9094. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9095. get: function () {
  9096. return this._blurBoxOffset;
  9097. },
  9098. set: function (value) {
  9099. var _this = this;
  9100. if (this._blurBoxOffset === value) {
  9101. return;
  9102. }
  9103. this._blurBoxOffset = value;
  9104. if (this._boxBlurPostprocess) {
  9105. this._boxBlurPostprocess.dispose();
  9106. }
  9107. 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);
  9108. this._boxBlurPostprocess.onApply = function (effect) {
  9109. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9110. };
  9111. },
  9112. enumerable: true,
  9113. configurable: true
  9114. });
  9115. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9116. get: function () {
  9117. return this._filter;
  9118. },
  9119. set: function (value) {
  9120. if (this._filter === value) {
  9121. return;
  9122. }
  9123. this._filter = value;
  9124. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9125. this._shadowMap.anisotropicFilteringLevel = 16;
  9126. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9127. }
  9128. else {
  9129. this._shadowMap.anisotropicFilteringLevel = 1;
  9130. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9131. }
  9132. },
  9133. enumerable: true,
  9134. configurable: true
  9135. });
  9136. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9137. get: function () {
  9138. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9139. },
  9140. set: function (value) {
  9141. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9142. },
  9143. enumerable: true,
  9144. configurable: true
  9145. });
  9146. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9147. get: function () {
  9148. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9149. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9150. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9151. },
  9152. set: function (value) {
  9153. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9154. },
  9155. enumerable: true,
  9156. configurable: true
  9157. });
  9158. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9159. get: function () {
  9160. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9161. },
  9162. set: function (value) {
  9163. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9164. },
  9165. enumerable: true,
  9166. configurable: true
  9167. });
  9168. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9169. var defines = [];
  9170. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9171. defines.push("#define VSM");
  9172. }
  9173. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9174. var mesh = subMesh.getMesh();
  9175. var material = subMesh.getMaterial();
  9176. // Alpha test
  9177. if (material && material.needAlphaTesting()) {
  9178. defines.push("#define ALPHATEST");
  9179. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9180. attribs.push(BABYLON.VertexBuffer.UVKind);
  9181. defines.push("#define UV1");
  9182. }
  9183. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9184. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9185. defines.push("#define UV2");
  9186. }
  9187. }
  9188. // Bones
  9189. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9190. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9191. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9192. defines.push("#define BONES");
  9193. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9194. }
  9195. // Instances
  9196. if (useInstances) {
  9197. defines.push("#define INSTANCES");
  9198. attribs.push("world0");
  9199. attribs.push("world1");
  9200. attribs.push("world2");
  9201. attribs.push("world3");
  9202. }
  9203. // Get correct effect
  9204. var join = defines.join("\n");
  9205. if (this._cachedDefines !== join) {
  9206. this._cachedDefines = join;
  9207. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9208. }
  9209. return this._effect.isReady();
  9210. };
  9211. ShadowGenerator.prototype.getShadowMap = function () {
  9212. return this._shadowMap;
  9213. };
  9214. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9215. if (this._shadowMap2) {
  9216. return this._shadowMap2;
  9217. }
  9218. return this._shadowMap;
  9219. };
  9220. ShadowGenerator.prototype.getLight = function () {
  9221. return this._light;
  9222. };
  9223. // Methods
  9224. ShadowGenerator.prototype.getTransformMatrix = function () {
  9225. var scene = this._scene;
  9226. if (this._currentRenderID === scene.getRenderId()) {
  9227. return this._transformMatrix;
  9228. }
  9229. this._currentRenderID = scene.getRenderId();
  9230. var lightPosition = this._light.position;
  9231. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9232. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9233. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9234. }
  9235. if (this._light.computeTransformedPosition()) {
  9236. lightPosition = this._light.transformedPosition;
  9237. }
  9238. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9239. this._cachedPosition = lightPosition.clone();
  9240. this._cachedDirection = this._lightDirection.clone();
  9241. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9242. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9243. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9244. }
  9245. return this._transformMatrix;
  9246. };
  9247. ShadowGenerator.prototype.getDarkness = function () {
  9248. return this._darkness;
  9249. };
  9250. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9251. if (darkness >= 1.0)
  9252. this._darkness = 1.0;
  9253. else if (darkness <= 0.0)
  9254. this._darkness = 0.0;
  9255. else
  9256. this._darkness = darkness;
  9257. };
  9258. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9259. this._transparencyShadow = hasShadow;
  9260. };
  9261. ShadowGenerator.prototype._packHalf = function (depth) {
  9262. var scale = depth * 255.0;
  9263. var fract = scale - Math.floor(scale);
  9264. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9265. };
  9266. ShadowGenerator.prototype.dispose = function () {
  9267. this._shadowMap.dispose();
  9268. if (this._shadowMap2) {
  9269. this._shadowMap2.dispose();
  9270. }
  9271. if (this._downSamplePostprocess) {
  9272. this._downSamplePostprocess.dispose();
  9273. }
  9274. if (this._boxBlurPostprocess) {
  9275. this._boxBlurPostprocess.dispose();
  9276. }
  9277. };
  9278. ShadowGenerator._FILTER_NONE = 0;
  9279. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9280. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9281. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9282. return ShadowGenerator;
  9283. })();
  9284. BABYLON.ShadowGenerator = ShadowGenerator;
  9285. })(BABYLON || (BABYLON = {}));
  9286. var BABYLON;
  9287. (function (BABYLON) {
  9288. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9289. if (boxMin.x > sphereCenter.x + sphereRadius)
  9290. return false;
  9291. if (sphereCenter.x - sphereRadius > boxMax.x)
  9292. return false;
  9293. if (boxMin.y > sphereCenter.y + sphereRadius)
  9294. return false;
  9295. if (sphereCenter.y - sphereRadius > boxMax.y)
  9296. return false;
  9297. if (boxMin.z > sphereCenter.z + sphereRadius)
  9298. return false;
  9299. if (sphereCenter.z - sphereRadius > boxMax.z)
  9300. return false;
  9301. return true;
  9302. };
  9303. var getLowestRoot = function (a, b, c, maxR) {
  9304. var determinant = b * b - 4.0 * a * c;
  9305. var result = { root: 0, found: false };
  9306. if (determinant < 0)
  9307. return result;
  9308. var sqrtD = Math.sqrt(determinant);
  9309. var r1 = (-b - sqrtD) / (2.0 * a);
  9310. var r2 = (-b + sqrtD) / (2.0 * a);
  9311. if (r1 > r2) {
  9312. var temp = r2;
  9313. r2 = r1;
  9314. r1 = temp;
  9315. }
  9316. if (r1 > 0 && r1 < maxR) {
  9317. result.root = r1;
  9318. result.found = true;
  9319. return result;
  9320. }
  9321. if (r2 > 0 && r2 < maxR) {
  9322. result.root = r2;
  9323. result.found = true;
  9324. return result;
  9325. }
  9326. return result;
  9327. };
  9328. var Collider = (function () {
  9329. function Collider() {
  9330. this.radius = new BABYLON.Vector3(1, 1, 1);
  9331. this.retry = 0;
  9332. this.basePointWorld = BABYLON.Vector3.Zero();
  9333. this.velocityWorld = BABYLON.Vector3.Zero();
  9334. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9335. this._collisionPoint = BABYLON.Vector3.Zero();
  9336. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9337. this._tempVector = BABYLON.Vector3.Zero();
  9338. this._tempVector2 = BABYLON.Vector3.Zero();
  9339. this._tempVector3 = BABYLON.Vector3.Zero();
  9340. this._tempVector4 = BABYLON.Vector3.Zero();
  9341. this._edge = BABYLON.Vector3.Zero();
  9342. this._baseToVertex = BABYLON.Vector3.Zero();
  9343. this._destinationPoint = BABYLON.Vector3.Zero();
  9344. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9345. this._displacementVector = BABYLON.Vector3.Zero();
  9346. }
  9347. // Methods
  9348. Collider.prototype._initialize = function (source, dir, e) {
  9349. this.velocity = dir;
  9350. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9351. this.basePoint = source;
  9352. source.multiplyToRef(this.radius, this.basePointWorld);
  9353. dir.multiplyToRef(this.radius, this.velocityWorld);
  9354. this.velocityWorldLength = this.velocityWorld.length();
  9355. this.epsilon = e;
  9356. this.collisionFound = false;
  9357. };
  9358. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9359. pa.subtractToRef(point, this._tempVector);
  9360. pb.subtractToRef(point, this._tempVector2);
  9361. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9362. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9363. if (d < 0)
  9364. return false;
  9365. pc.subtractToRef(point, this._tempVector3);
  9366. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9367. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9368. if (d < 0)
  9369. return false;
  9370. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9371. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9372. return d >= 0;
  9373. };
  9374. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9375. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9376. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9377. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9378. return false;
  9379. }
  9380. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9381. return false;
  9382. return true;
  9383. };
  9384. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9385. var t0;
  9386. var embeddedInPlane = false;
  9387. //defensive programming, actually not needed.
  9388. if (!trianglePlaneArray) {
  9389. trianglePlaneArray = [];
  9390. }
  9391. if (!trianglePlaneArray[faceIndex]) {
  9392. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9393. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9394. }
  9395. var trianglePlane = trianglePlaneArray[faceIndex];
  9396. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9397. return;
  9398. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9399. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9400. if (normalDotVelocity == 0) {
  9401. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9402. return;
  9403. embeddedInPlane = true;
  9404. t0 = 0;
  9405. }
  9406. else {
  9407. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9408. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9409. if (t0 > t1) {
  9410. var temp = t1;
  9411. t1 = t0;
  9412. t0 = temp;
  9413. }
  9414. if (t0 > 1.0 || t1 < 0.0)
  9415. return;
  9416. if (t0 < 0)
  9417. t0 = 0;
  9418. if (t0 > 1.0)
  9419. t0 = 1.0;
  9420. }
  9421. this._collisionPoint.copyFromFloats(0, 0, 0);
  9422. var found = false;
  9423. var t = 1.0;
  9424. if (!embeddedInPlane) {
  9425. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9426. this.velocity.scaleToRef(t0, this._tempVector);
  9427. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9428. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9429. found = true;
  9430. t = t0;
  9431. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9432. }
  9433. }
  9434. if (!found) {
  9435. var velocitySquaredLength = this.velocity.lengthSquared();
  9436. var a = velocitySquaredLength;
  9437. this.basePoint.subtractToRef(p1, this._tempVector);
  9438. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9439. var c = this._tempVector.lengthSquared() - 1.0;
  9440. var lowestRoot = getLowestRoot(a, b, c, t);
  9441. if (lowestRoot.found) {
  9442. t = lowestRoot.root;
  9443. found = true;
  9444. this._collisionPoint.copyFrom(p1);
  9445. }
  9446. this.basePoint.subtractToRef(p2, this._tempVector);
  9447. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9448. c = this._tempVector.lengthSquared() - 1.0;
  9449. lowestRoot = getLowestRoot(a, b, c, t);
  9450. if (lowestRoot.found) {
  9451. t = lowestRoot.root;
  9452. found = true;
  9453. this._collisionPoint.copyFrom(p2);
  9454. }
  9455. this.basePoint.subtractToRef(p3, this._tempVector);
  9456. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9457. c = this._tempVector.lengthSquared() - 1.0;
  9458. lowestRoot = getLowestRoot(a, b, c, t);
  9459. if (lowestRoot.found) {
  9460. t = lowestRoot.root;
  9461. found = true;
  9462. this._collisionPoint.copyFrom(p3);
  9463. }
  9464. p2.subtractToRef(p1, this._edge);
  9465. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9466. var edgeSquaredLength = this._edge.lengthSquared();
  9467. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9468. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9469. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9470. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9471. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9472. lowestRoot = getLowestRoot(a, b, c, t);
  9473. if (lowestRoot.found) {
  9474. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9475. if (f >= 0.0 && f <= 1.0) {
  9476. t = lowestRoot.root;
  9477. found = true;
  9478. this._edge.scaleInPlace(f);
  9479. p1.addToRef(this._edge, this._collisionPoint);
  9480. }
  9481. }
  9482. p3.subtractToRef(p2, this._edge);
  9483. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9484. edgeSquaredLength = this._edge.lengthSquared();
  9485. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9486. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9487. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9488. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9489. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9490. lowestRoot = getLowestRoot(a, b, c, t);
  9491. if (lowestRoot.found) {
  9492. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9493. if (f >= 0.0 && f <= 1.0) {
  9494. t = lowestRoot.root;
  9495. found = true;
  9496. this._edge.scaleInPlace(f);
  9497. p2.addToRef(this._edge, this._collisionPoint);
  9498. }
  9499. }
  9500. p1.subtractToRef(p3, this._edge);
  9501. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9502. edgeSquaredLength = this._edge.lengthSquared();
  9503. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9504. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9505. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9506. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9507. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9508. lowestRoot = getLowestRoot(a, b, c, t);
  9509. if (lowestRoot.found) {
  9510. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9511. if (f >= 0.0 && f <= 1.0) {
  9512. t = lowestRoot.root;
  9513. found = true;
  9514. this._edge.scaleInPlace(f);
  9515. p3.addToRef(this._edge, this._collisionPoint);
  9516. }
  9517. }
  9518. }
  9519. if (found) {
  9520. var distToCollision = t * this.velocity.length();
  9521. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9522. if (!this.intersectionPoint) {
  9523. this.intersectionPoint = this._collisionPoint.clone();
  9524. }
  9525. else {
  9526. this.intersectionPoint.copyFrom(this._collisionPoint);
  9527. }
  9528. this.nearestDistance = distToCollision;
  9529. this.collisionFound = true;
  9530. }
  9531. }
  9532. };
  9533. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9534. for (var i = indexStart; i < indexEnd; i += 3) {
  9535. var p1 = pts[indices[i] - decal];
  9536. var p2 = pts[indices[i + 1] - decal];
  9537. var p3 = pts[indices[i + 2] - decal];
  9538. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9539. }
  9540. };
  9541. Collider.prototype._getResponse = function (pos, vel) {
  9542. pos.addToRef(vel, this._destinationPoint);
  9543. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9544. this.basePoint.addToRef(vel, pos);
  9545. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9546. this._slidePlaneNormal.normalize();
  9547. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9548. pos.addInPlace(this._displacementVector);
  9549. this.intersectionPoint.addInPlace(this._displacementVector);
  9550. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9551. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9552. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9553. };
  9554. return Collider;
  9555. })();
  9556. BABYLON.Collider = Collider;
  9557. })(BABYLON || (BABYLON = {}));
  9558. var BABYLON;
  9559. (function (BABYLON) {
  9560. //WebWorker code will be inserted to this variable.
  9561. BABYLON.CollisionWorker = "";
  9562. (function (WorkerTaskType) {
  9563. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9564. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9565. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9566. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9567. var WorkerTaskType = BABYLON.WorkerTaskType;
  9568. (function (WorkerReplyType) {
  9569. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9570. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9571. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9572. var WorkerReplyType = BABYLON.WorkerReplyType;
  9573. var CollisionCoordinatorWorker = (function () {
  9574. function CollisionCoordinatorWorker() {
  9575. var _this = this;
  9576. this._scaledPosition = BABYLON.Vector3.Zero();
  9577. this._scaledVelocity = BABYLON.Vector3.Zero();
  9578. this.onMeshUpdated = function (mesh) {
  9579. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9580. };
  9581. this.onGeometryUpdated = function (geometry) {
  9582. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9583. };
  9584. this._afterRender = function () {
  9585. if (!_this._init)
  9586. return;
  9587. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9588. return;
  9589. }
  9590. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9591. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9592. if (_this._runningUpdated > 4) {
  9593. return;
  9594. }
  9595. ++_this._runningUpdated;
  9596. var payload = {
  9597. updatedMeshes: _this._addUpdateMeshesList,
  9598. updatedGeometries: _this._addUpdateGeometriesList,
  9599. removedGeometries: _this._toRemoveGeometryArray,
  9600. removedMeshes: _this._toRemoveMeshesArray
  9601. };
  9602. var message = {
  9603. payload: payload,
  9604. taskType: WorkerTaskType.UPDATE
  9605. };
  9606. var serializable = [];
  9607. for (var id in payload.updatedGeometries) {
  9608. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9609. //prepare transferables
  9610. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9611. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9612. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9613. }
  9614. }
  9615. _this._worker.postMessage(message, serializable);
  9616. _this._addUpdateMeshesList = {};
  9617. _this._addUpdateGeometriesList = {};
  9618. _this._toRemoveGeometryArray = [];
  9619. _this._toRemoveMeshesArray = [];
  9620. };
  9621. this._onMessageFromWorker = function (e) {
  9622. var returnData = e.data;
  9623. if (returnData.error != WorkerReplyType.SUCCESS) {
  9624. //TODO what errors can be returned from the worker?
  9625. BABYLON.Tools.Warn("error returned from worker!");
  9626. return;
  9627. }
  9628. switch (returnData.taskType) {
  9629. case WorkerTaskType.INIT:
  9630. _this._init = true;
  9631. //Update the worked with ALL of the scene's current state
  9632. _this._scene.meshes.forEach(function (mesh) {
  9633. _this.onMeshAdded(mesh);
  9634. });
  9635. _this._scene.getGeometries().forEach(function (geometry) {
  9636. _this.onGeometryAdded(geometry);
  9637. });
  9638. break;
  9639. case WorkerTaskType.UPDATE:
  9640. _this._runningUpdated--;
  9641. break;
  9642. case WorkerTaskType.COLLIDE:
  9643. _this._runningCollisionTask = false;
  9644. var returnPayload = returnData.payload;
  9645. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9646. return;
  9647. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9648. //cleanup
  9649. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9650. break;
  9651. }
  9652. };
  9653. this._collisionsCallbackArray = [];
  9654. this._init = false;
  9655. this._runningUpdated = 0;
  9656. this._runningCollisionTask = false;
  9657. this._addUpdateMeshesList = {};
  9658. this._addUpdateGeometriesList = {};
  9659. this._toRemoveGeometryArray = [];
  9660. this._toRemoveMeshesArray = [];
  9661. }
  9662. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9663. if (!this._init)
  9664. return;
  9665. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9666. return;
  9667. position.divideToRef(collider.radius, this._scaledPosition);
  9668. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9669. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9670. var payload = {
  9671. collider: {
  9672. position: this._scaledPosition.asArray(),
  9673. velocity: this._scaledVelocity.asArray(),
  9674. radius: collider.radius.asArray()
  9675. },
  9676. collisionId: collisionIndex,
  9677. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9678. maximumRetry: maximumRetry
  9679. };
  9680. var message = {
  9681. payload: payload,
  9682. taskType: WorkerTaskType.COLLIDE
  9683. };
  9684. this._worker.postMessage(message);
  9685. };
  9686. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9687. this._scene = scene;
  9688. this._scene.registerAfterRender(this._afterRender);
  9689. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9690. this._worker = new Worker(workerUrl);
  9691. this._worker.onmessage = this._onMessageFromWorker;
  9692. var message = {
  9693. payload: {},
  9694. taskType: WorkerTaskType.INIT
  9695. };
  9696. this._worker.postMessage(message);
  9697. };
  9698. CollisionCoordinatorWorker.prototype.destroy = function () {
  9699. this._scene.unregisterAfterRender(this._afterRender);
  9700. this._worker.terminate();
  9701. };
  9702. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9703. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9704. this.onMeshUpdated(mesh);
  9705. };
  9706. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9707. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9708. };
  9709. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9710. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9711. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9712. this.onGeometryUpdated(geometry);
  9713. };
  9714. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9715. this._toRemoveGeometryArray.push(geometry.id);
  9716. };
  9717. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9718. var submeshes = [];
  9719. if (mesh.subMeshes) {
  9720. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9721. return {
  9722. position: idx,
  9723. verticesStart: sm.verticesStart,
  9724. verticesCount: sm.verticesCount,
  9725. indexStart: sm.indexStart,
  9726. indexCount: sm.indexCount,
  9727. hasMaterial: !!sm.getMaterial(),
  9728. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9729. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9730. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9731. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9732. };
  9733. });
  9734. }
  9735. var geometryId = null;
  9736. if (mesh instanceof BABYLON.Mesh) {
  9737. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9738. }
  9739. else if (mesh instanceof BABYLON.InstancedMesh) {
  9740. geometryId = mesh.sourceMesh.geometry ? mesh.sourceMesh.geometry.id : null;
  9741. }
  9742. return {
  9743. uniqueId: mesh.uniqueId,
  9744. id: mesh.id,
  9745. name: mesh.name,
  9746. geometryId: geometryId,
  9747. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9748. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9749. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9750. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9751. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9752. subMeshes: submeshes,
  9753. checkCollisions: mesh.checkCollisions
  9754. };
  9755. };
  9756. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9757. return {
  9758. id: geometry.id,
  9759. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9760. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9761. indices: new Int32Array(geometry.getIndices() || []),
  9762. };
  9763. };
  9764. return CollisionCoordinatorWorker;
  9765. })();
  9766. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9767. var CollisionCoordinatorLegacy = (function () {
  9768. function CollisionCoordinatorLegacy() {
  9769. this._scaledPosition = BABYLON.Vector3.Zero();
  9770. this._scaledVelocity = BABYLON.Vector3.Zero();
  9771. this._finalPosition = BABYLON.Vector3.Zero();
  9772. }
  9773. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9774. position.divideToRef(collider.radius, this._scaledPosition);
  9775. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9776. collider.collidedMesh = null;
  9777. collider.retry = 0;
  9778. collider.initialVelocity = this._scaledVelocity;
  9779. collider.initialPosition = this._scaledPosition;
  9780. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9781. this._finalPosition.multiplyInPlace(collider.radius);
  9782. //run the callback
  9783. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9784. };
  9785. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9786. this._scene = scene;
  9787. };
  9788. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9789. //Legacy need no destruction method.
  9790. };
  9791. //No update in legacy mode
  9792. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9793. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9794. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9795. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9796. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9797. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9798. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9799. if (excludedMesh === void 0) { excludedMesh = null; }
  9800. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9801. if (collider.retry >= maximumRetry) {
  9802. finalPosition.copyFrom(position);
  9803. return;
  9804. }
  9805. collider._initialize(position, velocity, closeDistance);
  9806. // Check all meshes
  9807. for (var index = 0; index < this._scene.meshes.length; index++) {
  9808. var mesh = this._scene.meshes[index];
  9809. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9810. mesh._checkCollision(collider);
  9811. }
  9812. }
  9813. if (!collider.collisionFound) {
  9814. position.addToRef(velocity, finalPosition);
  9815. return;
  9816. }
  9817. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9818. collider._getResponse(position, velocity);
  9819. }
  9820. if (velocity.length() <= closeDistance) {
  9821. finalPosition.copyFrom(position);
  9822. return;
  9823. }
  9824. collider.retry++;
  9825. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9826. };
  9827. return CollisionCoordinatorLegacy;
  9828. })();
  9829. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9830. })(BABYLON || (BABYLON = {}));
  9831. var BABYLON;
  9832. (function (BABYLON) {
  9833. var VRCameraMetrics = (function () {
  9834. function VRCameraMetrics() {
  9835. this.compensateDistorsion = true;
  9836. }
  9837. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9838. get: function () {
  9839. return this.hResolution / (2 * this.vResolution);
  9840. },
  9841. enumerable: true,
  9842. configurable: true
  9843. });
  9844. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9845. get: function () {
  9846. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9852. get: function () {
  9853. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9854. var h = (4 * meters) / this.hScreenSize;
  9855. return BABYLON.Matrix.Translation(h, 0, 0);
  9856. },
  9857. enumerable: true,
  9858. configurable: true
  9859. });
  9860. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9861. get: function () {
  9862. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9863. var h = (4 * meters) / this.hScreenSize;
  9864. return BABYLON.Matrix.Translation(-h, 0, 0);
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9870. get: function () {
  9871. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9877. get: function () {
  9878. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. VRCameraMetrics.GetDefault = function () {
  9884. var result = new VRCameraMetrics();
  9885. result.hResolution = 1280;
  9886. result.vResolution = 800;
  9887. result.hScreenSize = 0.149759993;
  9888. result.vScreenSize = 0.0935999975;
  9889. result.vScreenCenter = 0.0467999987,
  9890. result.eyeToScreenDistance = 0.0410000011;
  9891. result.lensSeparationDistance = 0.0635000020;
  9892. result.interpupillaryDistance = 0.0640000030;
  9893. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9894. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9895. result.postProcessScaleFactor = 1.714605507808412;
  9896. result.lensCenterOffset = 0.151976421;
  9897. return result;
  9898. };
  9899. return VRCameraMetrics;
  9900. })();
  9901. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9902. var Camera = (function (_super) {
  9903. __extends(Camera, _super);
  9904. function Camera(name, position, scene) {
  9905. _super.call(this, name, scene);
  9906. this.position = position;
  9907. // Members
  9908. this.upVector = BABYLON.Vector3.Up();
  9909. this.orthoLeft = null;
  9910. this.orthoRight = null;
  9911. this.orthoBottom = null;
  9912. this.orthoTop = null;
  9913. this.fov = 0.8;
  9914. this.minZ = 1.0;
  9915. this.maxZ = 10000.0;
  9916. this.inertia = 0.9;
  9917. this.mode = Camera.PERSPECTIVE_CAMERA;
  9918. this.isIntermediate = false;
  9919. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9920. this.layerMask = 0x0FFFFFFF;
  9921. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9922. // Camera rig members
  9923. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9924. this._rigCameras = new Array();
  9925. // Cache
  9926. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9927. this._projectionMatrix = new BABYLON.Matrix();
  9928. this._postProcesses = new Array();
  9929. this._postProcessesTakenIndices = [];
  9930. this._activeMeshes = new BABYLON.SmartArray(256);
  9931. this._globalPosition = BABYLON.Vector3.Zero();
  9932. scene.addCamera(this);
  9933. if (!scene.activeCamera) {
  9934. scene.activeCamera = this;
  9935. }
  9936. }
  9937. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9938. get: function () {
  9939. return Camera._PERSPECTIVE_CAMERA;
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9945. get: function () {
  9946. return Camera._ORTHOGRAPHIC_CAMERA;
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9952. get: function () {
  9953. return Camera._FOVMODE_VERTICAL_FIXED;
  9954. },
  9955. enumerable: true,
  9956. configurable: true
  9957. });
  9958. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9959. get: function () {
  9960. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9966. get: function () {
  9967. return Camera._RIG_MODE_NONE;
  9968. },
  9969. enumerable: true,
  9970. configurable: true
  9971. });
  9972. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9973. get: function () {
  9974. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9975. },
  9976. enumerable: true,
  9977. configurable: true
  9978. });
  9979. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9980. get: function () {
  9981. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9982. },
  9983. enumerable: true,
  9984. configurable: true
  9985. });
  9986. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9987. get: function () {
  9988. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9989. },
  9990. enumerable: true,
  9991. configurable: true
  9992. });
  9993. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9994. get: function () {
  9995. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9996. },
  9997. enumerable: true,
  9998. configurable: true
  9999. });
  10000. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10001. get: function () {
  10002. return Camera._RIG_MODE_VR;
  10003. },
  10004. enumerable: true,
  10005. configurable: true
  10006. });
  10007. Object.defineProperty(Camera.prototype, "globalPosition", {
  10008. get: function () {
  10009. return this._globalPosition;
  10010. },
  10011. enumerable: true,
  10012. configurable: true
  10013. });
  10014. Camera.prototype.getActiveMeshes = function () {
  10015. return this._activeMeshes;
  10016. };
  10017. Camera.prototype.isActiveMesh = function (mesh) {
  10018. return (this._activeMeshes.indexOf(mesh) !== -1);
  10019. };
  10020. //Cache
  10021. Camera.prototype._initCache = function () {
  10022. _super.prototype._initCache.call(this);
  10023. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10024. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10025. this._cache.mode = undefined;
  10026. this._cache.minZ = undefined;
  10027. this._cache.maxZ = undefined;
  10028. this._cache.fov = undefined;
  10029. this._cache.aspectRatio = undefined;
  10030. this._cache.orthoLeft = undefined;
  10031. this._cache.orthoRight = undefined;
  10032. this._cache.orthoBottom = undefined;
  10033. this._cache.orthoTop = undefined;
  10034. this._cache.renderWidth = undefined;
  10035. this._cache.renderHeight = undefined;
  10036. };
  10037. Camera.prototype._updateCache = function (ignoreParentClass) {
  10038. if (!ignoreParentClass) {
  10039. _super.prototype._updateCache.call(this);
  10040. }
  10041. var engine = this.getEngine();
  10042. this._cache.position.copyFrom(this.position);
  10043. this._cache.upVector.copyFrom(this.upVector);
  10044. this._cache.mode = this.mode;
  10045. this._cache.minZ = this.minZ;
  10046. this._cache.maxZ = this.maxZ;
  10047. this._cache.fov = this.fov;
  10048. this._cache.aspectRatio = engine.getAspectRatio(this);
  10049. this._cache.orthoLeft = this.orthoLeft;
  10050. this._cache.orthoRight = this.orthoRight;
  10051. this._cache.orthoBottom = this.orthoBottom;
  10052. this._cache.orthoTop = this.orthoTop;
  10053. this._cache.renderWidth = engine.getRenderWidth();
  10054. this._cache.renderHeight = engine.getRenderHeight();
  10055. };
  10056. Camera.prototype._updateFromScene = function () {
  10057. this.updateCache();
  10058. this._update();
  10059. };
  10060. // Synchronized
  10061. Camera.prototype._isSynchronized = function () {
  10062. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10063. };
  10064. Camera.prototype._isSynchronizedViewMatrix = function () {
  10065. if (!_super.prototype._isSynchronized.call(this))
  10066. return false;
  10067. return this._cache.position.equals(this.position)
  10068. && this._cache.upVector.equals(this.upVector)
  10069. && this.isSynchronizedWithParent();
  10070. };
  10071. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10072. var check = this._cache.mode === this.mode
  10073. && this._cache.minZ === this.minZ
  10074. && this._cache.maxZ === this.maxZ;
  10075. if (!check) {
  10076. return false;
  10077. }
  10078. var engine = this.getEngine();
  10079. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10080. check = this._cache.fov === this.fov
  10081. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10082. }
  10083. else {
  10084. check = this._cache.orthoLeft === this.orthoLeft
  10085. && this._cache.orthoRight === this.orthoRight
  10086. && this._cache.orthoBottom === this.orthoBottom
  10087. && this._cache.orthoTop === this.orthoTop
  10088. && this._cache.renderWidth === engine.getRenderWidth()
  10089. && this._cache.renderHeight === engine.getRenderHeight();
  10090. }
  10091. return check;
  10092. };
  10093. // Controls
  10094. Camera.prototype.attachControl = function (element) {
  10095. };
  10096. Camera.prototype.detachControl = function (element) {
  10097. };
  10098. Camera.prototype._update = function () {
  10099. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10100. this._updateRigCameras();
  10101. }
  10102. this._checkInputs();
  10103. };
  10104. Camera.prototype._checkInputs = function () {
  10105. };
  10106. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10107. if (insertAt === void 0) { insertAt = null; }
  10108. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10109. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10110. return 0;
  10111. }
  10112. if (insertAt == null || insertAt < 0) {
  10113. this._postProcesses.push(postProcess);
  10114. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10115. return this._postProcesses.length - 1;
  10116. }
  10117. var add = 0;
  10118. if (this._postProcesses[insertAt]) {
  10119. var start = this._postProcesses.length - 1;
  10120. for (var i = start; i >= insertAt + 1; --i) {
  10121. this._postProcesses[i + 1] = this._postProcesses[i];
  10122. }
  10123. add = 1;
  10124. }
  10125. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10126. if (this._postProcessesTakenIndices[i] < insertAt) {
  10127. continue;
  10128. }
  10129. start = this._postProcessesTakenIndices.length - 1;
  10130. for (var j = start; j >= i; --j) {
  10131. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10132. }
  10133. this._postProcessesTakenIndices[i] = insertAt;
  10134. break;
  10135. }
  10136. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  10137. this._postProcessesTakenIndices.push(insertAt);
  10138. }
  10139. var result = insertAt + add;
  10140. this._postProcesses[result] = postProcess;
  10141. return result;
  10142. };
  10143. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10144. if (atIndices === void 0) { atIndices = null; }
  10145. var result = [];
  10146. if (!atIndices) {
  10147. var length = this._postProcesses.length;
  10148. for (var i = 0; i < length; i++) {
  10149. if (this._postProcesses[i] !== postProcess) {
  10150. continue;
  10151. }
  10152. delete this._postProcesses[i];
  10153. var index = this._postProcessesTakenIndices.indexOf(i);
  10154. this._postProcessesTakenIndices.splice(index, 1);
  10155. }
  10156. }
  10157. else {
  10158. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10159. for (i = 0; i < atIndices.length; i++) {
  10160. var foundPostProcess = this._postProcesses[atIndices[i]];
  10161. if (foundPostProcess !== postProcess) {
  10162. result.push(i);
  10163. continue;
  10164. }
  10165. delete this._postProcesses[atIndices[i]];
  10166. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10167. this._postProcessesTakenIndices.splice(index, 1);
  10168. }
  10169. }
  10170. return result;
  10171. };
  10172. Camera.prototype.getWorldMatrix = function () {
  10173. if (!this._worldMatrix) {
  10174. this._worldMatrix = BABYLON.Matrix.Identity();
  10175. }
  10176. var viewMatrix = this.getViewMatrix();
  10177. viewMatrix.invertToRef(this._worldMatrix);
  10178. return this._worldMatrix;
  10179. };
  10180. Camera.prototype._getViewMatrix = function () {
  10181. return BABYLON.Matrix.Identity();
  10182. };
  10183. Camera.prototype.getViewMatrix = function (force) {
  10184. this._computedViewMatrix = this._computeViewMatrix(force);
  10185. if (!force && this._isSynchronizedViewMatrix()) {
  10186. return this._computedViewMatrix;
  10187. }
  10188. if (!this.parent || !this.parent.getWorldMatrix) {
  10189. this._globalPosition.copyFrom(this.position);
  10190. }
  10191. else {
  10192. if (!this._worldMatrix) {
  10193. this._worldMatrix = BABYLON.Matrix.Identity();
  10194. }
  10195. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10196. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10197. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10198. this._computedViewMatrix.invert();
  10199. this._markSyncedWithParent();
  10200. }
  10201. this._currentRenderId = this.getScene().getRenderId();
  10202. return this._computedViewMatrix;
  10203. };
  10204. Camera.prototype._computeViewMatrix = function (force) {
  10205. if (!force && this._isSynchronizedViewMatrix()) {
  10206. return this._computedViewMatrix;
  10207. }
  10208. this._computedViewMatrix = this._getViewMatrix();
  10209. this._currentRenderId = this.getScene().getRenderId();
  10210. return this._computedViewMatrix;
  10211. };
  10212. Camera.prototype.getProjectionMatrix = function (force) {
  10213. if (!force && this._isSynchronizedProjectionMatrix()) {
  10214. return this._projectionMatrix;
  10215. }
  10216. var engine = this.getEngine();
  10217. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10218. if (this.minZ <= 0) {
  10219. this.minZ = 0.1;
  10220. }
  10221. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10222. return this._projectionMatrix;
  10223. }
  10224. var halfWidth = engine.getRenderWidth() / 2.0;
  10225. var halfHeight = engine.getRenderHeight() / 2.0;
  10226. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10227. return this._projectionMatrix;
  10228. };
  10229. Camera.prototype.dispose = function () {
  10230. // Remove from scene
  10231. this.getScene().removeCamera(this);
  10232. while (this._rigCameras.length > 0) {
  10233. this._rigCameras.pop().dispose();
  10234. }
  10235. // Postprocesses
  10236. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10237. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10238. }
  10239. };
  10240. // ---- Camera rigs section ----
  10241. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10242. while (this._rigCameras.length > 0) {
  10243. this._rigCameras.pop().dispose();
  10244. }
  10245. this.cameraRigMode = mode;
  10246. this._cameraRigParams = {};
  10247. switch (this.cameraRigMode) {
  10248. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10249. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10250. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10251. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10252. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10253. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10254. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10255. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10256. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10257. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10258. break;
  10259. }
  10260. var postProcesses = new Array();
  10261. switch (this.cameraRigMode) {
  10262. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10263. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10264. this._rigCameras[0].isIntermediate = true;
  10265. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10266. postProcesses[1].onApply = function (effect) {
  10267. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10268. };
  10269. break;
  10270. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10271. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10272. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10273. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10274. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10275. var secondCamIndex = 1 - firstCamIndex;
  10276. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10277. this._rigCameras[firstCamIndex].isIntermediate = true;
  10278. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10279. break;
  10280. case Camera.RIG_MODE_VR:
  10281. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10282. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10283. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10284. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10285. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10286. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10287. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10288. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10289. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10290. if (metrics.compensateDistorsion) {
  10291. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10292. }
  10293. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10294. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10295. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10296. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10297. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10298. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10299. if (metrics.compensateDistorsion) {
  10300. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10301. }
  10302. break;
  10303. }
  10304. this._update();
  10305. };
  10306. Camera.prototype._getVRProjectionMatrix = function () {
  10307. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10308. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10309. return this._projectionMatrix;
  10310. };
  10311. Camera.prototype.setCameraRigParameter = function (name, value) {
  10312. this._cameraRigParams[name] = value;
  10313. //provisionnally:
  10314. if (name === "interaxialDistance") {
  10315. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10316. }
  10317. };
  10318. /**
  10319. * May needs to be overridden by children so sub has required properties to be copied
  10320. */
  10321. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10322. return null;
  10323. };
  10324. /**
  10325. * May needs to be overridden by children
  10326. */
  10327. Camera.prototype._updateRigCameras = function () {
  10328. for (var i = 0; i < this._rigCameras.length; i++) {
  10329. this._rigCameras[i].minZ = this.minZ;
  10330. this._rigCameras[i].maxZ = this.maxZ;
  10331. this._rigCameras[i].fov = this.fov;
  10332. }
  10333. // only update viewport when ANAGLYPH
  10334. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10335. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10336. }
  10337. };
  10338. // Statics
  10339. Camera._PERSPECTIVE_CAMERA = 0;
  10340. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10341. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10342. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10343. Camera._RIG_MODE_NONE = 0;
  10344. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10345. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10346. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10347. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10348. Camera._RIG_MODE_VR = 20;
  10349. return Camera;
  10350. })(BABYLON.Node);
  10351. BABYLON.Camera = Camera;
  10352. })(BABYLON || (BABYLON = {}));
  10353. var BABYLON;
  10354. (function (BABYLON) {
  10355. var TargetCamera = (function (_super) {
  10356. __extends(TargetCamera, _super);
  10357. function TargetCamera(name, position, scene) {
  10358. _super.call(this, name, position, scene);
  10359. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10360. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10361. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10362. this.speed = 2.0;
  10363. this.noRotationConstraint = false;
  10364. this.lockedTarget = null;
  10365. this._currentTarget = BABYLON.Vector3.Zero();
  10366. this._viewMatrix = BABYLON.Matrix.Zero();
  10367. this._camMatrix = BABYLON.Matrix.Zero();
  10368. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10369. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10370. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10371. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10372. this._lookAtTemp = BABYLON.Matrix.Zero();
  10373. this._tempMatrix = BABYLON.Matrix.Zero();
  10374. }
  10375. TargetCamera.prototype.getFrontPosition = function (distance) {
  10376. var direction = this.getTarget().subtract(this.position);
  10377. direction.normalize();
  10378. direction.scaleInPlace(distance);
  10379. return this.globalPosition.add(direction);
  10380. };
  10381. TargetCamera.prototype._getLockedTargetPosition = function () {
  10382. if (!this.lockedTarget) {
  10383. return null;
  10384. }
  10385. return this.lockedTarget.position || this.lockedTarget;
  10386. };
  10387. // Cache
  10388. TargetCamera.prototype._initCache = function () {
  10389. _super.prototype._initCache.call(this);
  10390. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10391. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10392. };
  10393. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10394. if (!ignoreParentClass) {
  10395. _super.prototype._updateCache.call(this);
  10396. }
  10397. var lockedTargetPosition = this._getLockedTargetPosition();
  10398. if (!lockedTargetPosition) {
  10399. this._cache.lockedTarget = null;
  10400. }
  10401. else {
  10402. if (!this._cache.lockedTarget) {
  10403. this._cache.lockedTarget = lockedTargetPosition.clone();
  10404. }
  10405. else {
  10406. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10407. }
  10408. }
  10409. this._cache.rotation.copyFrom(this.rotation);
  10410. };
  10411. // Synchronized
  10412. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10413. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10414. return false;
  10415. }
  10416. var lockedTargetPosition = this._getLockedTargetPosition();
  10417. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10418. && this._cache.rotation.equals(this.rotation);
  10419. };
  10420. // Methods
  10421. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10422. var engine = this.getEngine();
  10423. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10424. };
  10425. // Target
  10426. TargetCamera.prototype.setTarget = function (target) {
  10427. this.upVector.normalize();
  10428. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10429. this._camMatrix.invert();
  10430. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10431. var vDir = target.subtract(this.position);
  10432. if (vDir.x >= 0.0) {
  10433. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10434. }
  10435. else {
  10436. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10437. }
  10438. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10439. if (isNaN(this.rotation.x)) {
  10440. this.rotation.x = 0;
  10441. }
  10442. if (isNaN(this.rotation.y)) {
  10443. this.rotation.y = 0;
  10444. }
  10445. if (isNaN(this.rotation.z)) {
  10446. this.rotation.z = 0;
  10447. }
  10448. };
  10449. TargetCamera.prototype.getTarget = function () {
  10450. return this._currentTarget;
  10451. };
  10452. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10453. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10454. };
  10455. TargetCamera.prototype._updatePosition = function () {
  10456. this.position.addInPlace(this.cameraDirection);
  10457. };
  10458. TargetCamera.prototype._checkInputs = function () {
  10459. var needToMove = this._decideIfNeedsToMove();
  10460. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10461. // Move
  10462. if (needToMove) {
  10463. this._updatePosition();
  10464. }
  10465. // Rotate
  10466. if (needToRotate) {
  10467. this.rotation.x += this.cameraRotation.x;
  10468. this.rotation.y += this.cameraRotation.y;
  10469. if (!this.noRotationConstraint) {
  10470. var limit = (Math.PI / 2) * 0.95;
  10471. if (this.rotation.x > limit)
  10472. this.rotation.x = limit;
  10473. if (this.rotation.x < -limit)
  10474. this.rotation.x = -limit;
  10475. }
  10476. }
  10477. // Inertia
  10478. if (needToMove) {
  10479. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10480. this.cameraDirection.x = 0;
  10481. }
  10482. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10483. this.cameraDirection.y = 0;
  10484. }
  10485. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10486. this.cameraDirection.z = 0;
  10487. }
  10488. this.cameraDirection.scaleInPlace(this.inertia);
  10489. }
  10490. if (needToRotate) {
  10491. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10492. this.cameraRotation.x = 0;
  10493. }
  10494. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10495. this.cameraRotation.y = 0;
  10496. }
  10497. this.cameraRotation.scaleInPlace(this.inertia);
  10498. }
  10499. _super.prototype._checkInputs.call(this);
  10500. };
  10501. TargetCamera.prototype._getViewMatrix = function () {
  10502. if (!this.lockedTarget) {
  10503. // Compute
  10504. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10505. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10506. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10507. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10508. this._lookAtTemp.invert();
  10509. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10510. }
  10511. else {
  10512. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10513. }
  10514. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10515. // Computing target and final matrix
  10516. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10517. }
  10518. else {
  10519. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10520. }
  10521. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10522. return this._viewMatrix;
  10523. };
  10524. TargetCamera.prototype._getVRViewMatrix = function () {
  10525. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10526. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10527. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10528. // Computing target and final matrix
  10529. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10530. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10531. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10532. return this._viewMatrix;
  10533. };
  10534. /**
  10535. * @override
  10536. * Override Camera.createRigCamera
  10537. */
  10538. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10539. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10540. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10541. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10542. rigCamera._cameraRigParams = {};
  10543. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10544. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10545. }
  10546. return rigCamera;
  10547. }
  10548. return null;
  10549. };
  10550. /**
  10551. * @override
  10552. * Override Camera._updateRigCameras
  10553. */
  10554. TargetCamera.prototype._updateRigCameras = function () {
  10555. switch (this.cameraRigMode) {
  10556. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10557. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10558. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10559. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10560. case BABYLON.Camera.RIG_MODE_VR:
  10561. var camLeft = this._rigCameras[0];
  10562. var camRight = this._rigCameras[1];
  10563. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10564. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10565. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10566. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10567. camLeft.position.copyFrom(this.position);
  10568. camRight.position.copyFrom(this.position);
  10569. }
  10570. else {
  10571. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10572. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10573. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10574. camLeft.setTarget(this.getTarget());
  10575. camRight.setTarget(this.getTarget());
  10576. }
  10577. break;
  10578. }
  10579. _super.prototype._updateRigCameras.call(this);
  10580. };
  10581. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10582. if (!this._rigCamTransformMatrix) {
  10583. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10584. }
  10585. var target = this.getTarget();
  10586. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10587. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10588. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10589. };
  10590. return TargetCamera;
  10591. })(BABYLON.Camera);
  10592. BABYLON.TargetCamera = TargetCamera;
  10593. })(BABYLON || (BABYLON = {}));
  10594. var BABYLON;
  10595. (function (BABYLON) {
  10596. var FreeCamera = (function (_super) {
  10597. __extends(FreeCamera, _super);
  10598. function FreeCamera(name, position, scene) {
  10599. var _this = this;
  10600. _super.call(this, name, position, scene);
  10601. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10602. this.keysUp = [38];
  10603. this.keysDown = [40];
  10604. this.keysLeft = [37];
  10605. this.keysRight = [39];
  10606. this.checkCollisions = false;
  10607. this.applyGravity = false;
  10608. this.angularSensibility = 2000.0;
  10609. this._keys = [];
  10610. this._collider = new BABYLON.Collider();
  10611. this._needMoveForGravity = false;
  10612. this._oldPosition = BABYLON.Vector3.Zero();
  10613. this._diffPosition = BABYLON.Vector3.Zero();
  10614. this._newPosition = BABYLON.Vector3.Zero();
  10615. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10616. if (collidedMesh === void 0) { collidedMesh = null; }
  10617. //TODO move this to the collision coordinator!
  10618. if (_this.getScene().workerCollisions)
  10619. newPosition.multiplyInPlace(_this._collider.radius);
  10620. var updatePosition = function (newPos) {
  10621. _this._newPosition.copyFrom(newPos);
  10622. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10623. var oldPosition = _this.position.clone();
  10624. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10625. _this.position.addInPlace(_this._diffPosition);
  10626. if (_this.onCollide && collidedMesh) {
  10627. _this.onCollide(collidedMesh);
  10628. }
  10629. }
  10630. };
  10631. updatePosition(newPosition);
  10632. };
  10633. }
  10634. // Controls
  10635. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10636. var _this = this;
  10637. var previousPosition;
  10638. var engine = this.getEngine();
  10639. if (this._attachedElement) {
  10640. return;
  10641. }
  10642. this._attachedElement = element;
  10643. if (this._onMouseDown === undefined) {
  10644. this._onMouseDown = function (evt) {
  10645. previousPosition = {
  10646. x: evt.clientX,
  10647. y: evt.clientY
  10648. };
  10649. if (!noPreventDefault) {
  10650. evt.preventDefault();
  10651. }
  10652. };
  10653. this._onMouseUp = function (evt) {
  10654. previousPosition = null;
  10655. if (!noPreventDefault) {
  10656. evt.preventDefault();
  10657. }
  10658. };
  10659. this._onMouseOut = function (evt) {
  10660. previousPosition = null;
  10661. _this._keys = [];
  10662. if (!noPreventDefault) {
  10663. evt.preventDefault();
  10664. }
  10665. };
  10666. this._onMouseMove = function (evt) {
  10667. if (!previousPosition && !engine.isPointerLock) {
  10668. return;
  10669. }
  10670. var offsetX;
  10671. var offsetY;
  10672. if (!engine.isPointerLock) {
  10673. offsetX = evt.clientX - previousPosition.x;
  10674. offsetY = evt.clientY - previousPosition.y;
  10675. }
  10676. else {
  10677. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10678. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10679. }
  10680. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10681. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10682. previousPosition = {
  10683. x: evt.clientX,
  10684. y: evt.clientY
  10685. };
  10686. if (!noPreventDefault) {
  10687. evt.preventDefault();
  10688. }
  10689. };
  10690. this._onKeyDown = function (evt) {
  10691. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10692. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10693. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10694. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10695. var index = _this._keys.indexOf(evt.keyCode);
  10696. if (index === -1) {
  10697. _this._keys.push(evt.keyCode);
  10698. }
  10699. if (!noPreventDefault) {
  10700. evt.preventDefault();
  10701. }
  10702. }
  10703. };
  10704. this._onKeyUp = function (evt) {
  10705. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10706. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10707. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10708. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10709. var index = _this._keys.indexOf(evt.keyCode);
  10710. if (index >= 0) {
  10711. _this._keys.splice(index, 1);
  10712. }
  10713. if (!noPreventDefault) {
  10714. evt.preventDefault();
  10715. }
  10716. }
  10717. };
  10718. this._onLostFocus = function () {
  10719. _this._keys = [];
  10720. };
  10721. this._reset = function () {
  10722. _this._keys = [];
  10723. previousPosition = null;
  10724. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10725. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10726. };
  10727. }
  10728. element.addEventListener("mousedown", this._onMouseDown, false);
  10729. element.addEventListener("mouseup", this._onMouseUp, false);
  10730. element.addEventListener("mouseout", this._onMouseOut, false);
  10731. element.addEventListener("mousemove", this._onMouseMove, false);
  10732. BABYLON.Tools.RegisterTopRootEvents([
  10733. { name: "keydown", handler: this._onKeyDown },
  10734. { name: "keyup", handler: this._onKeyUp },
  10735. { name: "blur", handler: this._onLostFocus }
  10736. ]);
  10737. };
  10738. FreeCamera.prototype.detachControl = function (element) {
  10739. if (this._attachedElement != element) {
  10740. return;
  10741. }
  10742. element.removeEventListener("mousedown", this._onMouseDown);
  10743. element.removeEventListener("mouseup", this._onMouseUp);
  10744. element.removeEventListener("mouseout", this._onMouseOut);
  10745. element.removeEventListener("mousemove", this._onMouseMove);
  10746. BABYLON.Tools.UnregisterTopRootEvents([
  10747. { name: "keydown", handler: this._onKeyDown },
  10748. { name: "keyup", handler: this._onKeyUp },
  10749. { name: "blur", handler: this._onLostFocus }
  10750. ]);
  10751. this._attachedElement = null;
  10752. if (this._reset) {
  10753. this._reset();
  10754. }
  10755. };
  10756. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10757. var globalPosition;
  10758. if (this.parent) {
  10759. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10760. }
  10761. else {
  10762. globalPosition = this.position;
  10763. }
  10764. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10765. this._collider.radius = this.ellipsoid;
  10766. //add gravity to the velocity to prevent the dual-collision checking
  10767. if (this.applyGravity) {
  10768. velocity.addInPlace(this.getScene().gravity);
  10769. }
  10770. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10771. };
  10772. FreeCamera.prototype._checkInputs = function () {
  10773. if (!this._localDirection) {
  10774. this._localDirection = BABYLON.Vector3.Zero();
  10775. this._transformedDirection = BABYLON.Vector3.Zero();
  10776. }
  10777. // Keyboard
  10778. for (var index = 0; index < this._keys.length; index++) {
  10779. var keyCode = this._keys[index];
  10780. var speed = this._computeLocalCameraSpeed();
  10781. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10782. this._localDirection.copyFromFloats(-speed, 0, 0);
  10783. }
  10784. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10785. this._localDirection.copyFromFloats(0, 0, speed);
  10786. }
  10787. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10788. this._localDirection.copyFromFloats(speed, 0, 0);
  10789. }
  10790. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10791. this._localDirection.copyFromFloats(0, 0, -speed);
  10792. }
  10793. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10794. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10795. this.cameraDirection.addInPlace(this._transformedDirection);
  10796. }
  10797. _super.prototype._checkInputs.call(this);
  10798. };
  10799. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10800. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10801. };
  10802. FreeCamera.prototype._updatePosition = function () {
  10803. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10804. this._collideWithWorld(this.cameraDirection);
  10805. }
  10806. else {
  10807. this.position.addInPlace(this.cameraDirection);
  10808. }
  10809. };
  10810. return FreeCamera;
  10811. })(BABYLON.TargetCamera);
  10812. BABYLON.FreeCamera = FreeCamera;
  10813. })(BABYLON || (BABYLON = {}));
  10814. var BABYLON;
  10815. (function (BABYLON) {
  10816. var FollowCamera = (function (_super) {
  10817. __extends(FollowCamera, _super);
  10818. function FollowCamera(name, position, scene) {
  10819. _super.call(this, name, position, scene);
  10820. this.radius = 12;
  10821. this.rotationOffset = 0;
  10822. this.heightOffset = 4;
  10823. this.cameraAcceleration = 0.05;
  10824. this.maxCameraSpeed = 20;
  10825. }
  10826. FollowCamera.prototype.getRadians = function (degrees) {
  10827. return degrees * Math.PI / 180;
  10828. };
  10829. FollowCamera.prototype.follow = function (cameraTarget) {
  10830. if (!cameraTarget)
  10831. return;
  10832. var yRotation;
  10833. if (cameraTarget.rotationQuaternion) {
  10834. var rotMatrix = new BABYLON.Matrix();
  10835. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10836. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10837. }
  10838. else {
  10839. yRotation = cameraTarget.rotation.y;
  10840. }
  10841. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10842. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10843. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10844. var dx = targetX - this.position.x;
  10845. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10846. var dz = (targetZ) - this.position.z;
  10847. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10848. var vy = dy * this.cameraAcceleration;
  10849. var vz = dz * this.cameraAcceleration * 2;
  10850. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10851. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10852. }
  10853. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10854. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10855. }
  10856. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10857. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10858. }
  10859. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10860. this.setTarget(cameraTarget.position);
  10861. };
  10862. FollowCamera.prototype._checkInputs = function () {
  10863. _super.prototype._checkInputs.call(this);
  10864. this.follow(this.target);
  10865. };
  10866. return FollowCamera;
  10867. })(BABYLON.TargetCamera);
  10868. BABYLON.FollowCamera = FollowCamera;
  10869. var ArcFollowCamera = (function (_super) {
  10870. __extends(ArcFollowCamera, _super);
  10871. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10872. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10873. this.alpha = alpha;
  10874. this.beta = beta;
  10875. this.radius = radius;
  10876. this.target = target;
  10877. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10878. this.follow();
  10879. }
  10880. ArcFollowCamera.prototype.follow = function () {
  10881. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10882. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10883. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10884. this.position = this.target.position.add(this._cartesianCoordinates);
  10885. this.setTarget(this.target.position);
  10886. };
  10887. ArcFollowCamera.prototype._checkInputs = function () {
  10888. _super.prototype._checkInputs.call(this);
  10889. this.follow();
  10890. };
  10891. return ArcFollowCamera;
  10892. })(BABYLON.TargetCamera);
  10893. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10894. })(BABYLON || (BABYLON = {}));
  10895. var BABYLON;
  10896. (function (BABYLON) {
  10897. // We're mainly based on the logic defined into the FreeCamera code
  10898. var TouchCamera = (function (_super) {
  10899. __extends(TouchCamera, _super);
  10900. function TouchCamera(name, position, scene) {
  10901. _super.call(this, name, position, scene);
  10902. this._offsetX = null;
  10903. this._offsetY = null;
  10904. this._pointerCount = 0;
  10905. this._pointerPressed = [];
  10906. this.angularSensibility = 200000.0;
  10907. this.moveSensibility = 500.0;
  10908. }
  10909. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10910. var _this = this;
  10911. var previousPosition;
  10912. if (this._attachedCanvas) {
  10913. return;
  10914. }
  10915. this._attachedCanvas = canvas;
  10916. if (this._onPointerDown === undefined) {
  10917. this._onPointerDown = function (evt) {
  10918. if (!noPreventDefault) {
  10919. evt.preventDefault();
  10920. }
  10921. _this._pointerPressed.push(evt.pointerId);
  10922. if (_this._pointerPressed.length !== 1) {
  10923. return;
  10924. }
  10925. previousPosition = {
  10926. x: evt.clientX,
  10927. y: evt.clientY
  10928. };
  10929. };
  10930. this._onPointerUp = function (evt) {
  10931. if (!noPreventDefault) {
  10932. evt.preventDefault();
  10933. }
  10934. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10935. if (index === -1) {
  10936. return;
  10937. }
  10938. _this._pointerPressed.splice(index, 1);
  10939. if (index != 0) {
  10940. return;
  10941. }
  10942. previousPosition = null;
  10943. _this._offsetX = null;
  10944. _this._offsetY = null;
  10945. };
  10946. this._onPointerMove = function (evt) {
  10947. if (!noPreventDefault) {
  10948. evt.preventDefault();
  10949. }
  10950. if (!previousPosition) {
  10951. return;
  10952. }
  10953. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10954. if (index != 0) {
  10955. return;
  10956. }
  10957. _this._offsetX = evt.clientX - previousPosition.x;
  10958. _this._offsetY = -(evt.clientY - previousPosition.y);
  10959. };
  10960. this._onLostFocus = function () {
  10961. _this._offsetX = null;
  10962. _this._offsetY = null;
  10963. };
  10964. }
  10965. canvas.addEventListener("pointerdown", this._onPointerDown);
  10966. canvas.addEventListener("pointerup", this._onPointerUp);
  10967. canvas.addEventListener("pointerout", this._onPointerUp);
  10968. canvas.addEventListener("pointermove", this._onPointerMove);
  10969. BABYLON.Tools.RegisterTopRootEvents([
  10970. { name: "blur", handler: this._onLostFocus }
  10971. ]);
  10972. };
  10973. TouchCamera.prototype.detachControl = function (canvas) {
  10974. if (this._attachedCanvas != canvas) {
  10975. return;
  10976. }
  10977. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10978. canvas.removeEventListener("pointerup", this._onPointerUp);
  10979. canvas.removeEventListener("pointerout", this._onPointerUp);
  10980. canvas.removeEventListener("pointermove", this._onPointerMove);
  10981. BABYLON.Tools.UnregisterTopRootEvents([
  10982. { name: "blur", handler: this._onLostFocus }
  10983. ]);
  10984. this._attachedCanvas = null;
  10985. };
  10986. TouchCamera.prototype._checkInputs = function () {
  10987. if (this._offsetX) {
  10988. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10989. if (this._pointerPressed.length > 1) {
  10990. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10991. }
  10992. else {
  10993. var speed = this._computeLocalCameraSpeed();
  10994. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10995. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10996. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10997. }
  10998. }
  10999. _super.prototype._checkInputs.call(this);
  11000. };
  11001. return TouchCamera;
  11002. })(BABYLON.FreeCamera);
  11003. BABYLON.TouchCamera = TouchCamera;
  11004. })(BABYLON || (BABYLON = {}));
  11005. var BABYLON;
  11006. (function (BABYLON) {
  11007. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11008. var ArcRotateCamera = (function (_super) {
  11009. __extends(ArcRotateCamera, _super);
  11010. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11011. var _this = this;
  11012. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11013. this.alpha = alpha;
  11014. this.beta = beta;
  11015. this.radius = radius;
  11016. this.target = target;
  11017. this.inertialAlphaOffset = 0;
  11018. this.inertialBetaOffset = 0;
  11019. this.inertialRadiusOffset = 0;
  11020. this.lowerAlphaLimit = null;
  11021. this.upperAlphaLimit = null;
  11022. this.lowerBetaLimit = 0.01;
  11023. this.upperBetaLimit = Math.PI;
  11024. this.lowerRadiusLimit = null;
  11025. this.upperRadiusLimit = null;
  11026. this.angularSensibilityX = 1000.0;
  11027. this.angularSensibilityY = 1000.0;
  11028. this.wheelPrecision = 3.0;
  11029. this.pinchPrecision = 2.0;
  11030. this.panningSensibility = 50.0;
  11031. this.inertialPanningX = 0;
  11032. this.inertialPanningY = 0;
  11033. this.keysUp = [38];
  11034. this.keysDown = [40];
  11035. this.keysLeft = [37];
  11036. this.keysRight = [39];
  11037. this.zoomOnFactor = 1;
  11038. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11039. this.pinchInwards = true;
  11040. this.allowUpsideDown = true;
  11041. this._keys = [];
  11042. this._viewMatrix = new BABYLON.Matrix();
  11043. this._isRightClick = false;
  11044. this._isCtrlPushed = false;
  11045. this.checkCollisions = false;
  11046. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11047. this._collider = new BABYLON.Collider();
  11048. this._previousPosition = BABYLON.Vector3.Zero();
  11049. this._collisionVelocity = BABYLON.Vector3.Zero();
  11050. this._newPosition = BABYLON.Vector3.Zero();
  11051. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11052. if (collidedMesh === void 0) { collidedMesh = null; }
  11053. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11054. newPosition.multiplyInPlace(_this._collider.radius);
  11055. }
  11056. if (!collidedMesh) {
  11057. _this._previousPosition.copyFrom(_this.position);
  11058. }
  11059. else {
  11060. _this.setPosition(_this.position);
  11061. if (_this.onCollide) {
  11062. _this.onCollide(collidedMesh);
  11063. }
  11064. }
  11065. // Recompute because of constraints
  11066. var cosa = Math.cos(_this.alpha);
  11067. var sina = Math.sin(_this.alpha);
  11068. var cosb = Math.cos(_this.beta);
  11069. var sinb = Math.sin(_this.beta);
  11070. var target = _this._getTargetPosition();
  11071. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11072. _this.position.copyFrom(_this._newPosition);
  11073. var up = _this.upVector;
  11074. if (_this.allowUpsideDown && _this.beta < 0) {
  11075. var up = up.clone();
  11076. up = up.negate();
  11077. }
  11078. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11079. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11080. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11081. _this._collisionTriggered = false;
  11082. };
  11083. if (!this.target) {
  11084. this.target = BABYLON.Vector3.Zero();
  11085. }
  11086. this.getViewMatrix();
  11087. }
  11088. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11089. //deprecated angularSensibility support
  11090. get: function () {
  11091. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11092. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11093. },
  11094. //deprecated angularSensibility support
  11095. set: function (value) {
  11096. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11097. this.angularSensibilityX = value;
  11098. this.angularSensibilityY = value;
  11099. },
  11100. enumerable: true,
  11101. configurable: true
  11102. });
  11103. ArcRotateCamera.prototype._getTargetPosition = function () {
  11104. return this.target.position || this.target;
  11105. };
  11106. // Cache
  11107. ArcRotateCamera.prototype._initCache = function () {
  11108. _super.prototype._initCache.call(this);
  11109. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11110. this._cache.alpha = undefined;
  11111. this._cache.beta = undefined;
  11112. this._cache.radius = undefined;
  11113. this._cache.targetScreenOffset = undefined;
  11114. };
  11115. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11116. if (!ignoreParentClass) {
  11117. _super.prototype._updateCache.call(this);
  11118. }
  11119. this._cache.target.copyFrom(this._getTargetPosition());
  11120. this._cache.alpha = this.alpha;
  11121. this._cache.beta = this.beta;
  11122. this._cache.radius = this.radius;
  11123. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11124. };
  11125. // Synchronized
  11126. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11127. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11128. return false;
  11129. return this._cache.target.equals(this._getTargetPosition())
  11130. && this._cache.alpha === this.alpha
  11131. && this._cache.beta === this.beta
  11132. && this._cache.radius === this.radius
  11133. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11134. };
  11135. // Methods
  11136. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11137. var _this = this;
  11138. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11139. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11140. var previousPinchDistance = 0;
  11141. var pointers = new BABYLON.SmartCollection();
  11142. if (this._attachedElement) {
  11143. return;
  11144. }
  11145. this._attachedElement = element;
  11146. var engine = this.getEngine();
  11147. if (this._onPointerDown === undefined) {
  11148. this._onPointerDown = function (evt) {
  11149. // Manage panning with right click
  11150. _this._isRightClick = evt.button === 2 ? true : false;
  11151. // manage pointers
  11152. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11153. cacheSoloPointer = pointers.item(evt.pointerId);
  11154. if (!noPreventDefault) {
  11155. evt.preventDefault();
  11156. }
  11157. };
  11158. this._onPointerUp = function (evt) {
  11159. cacheSoloPointer = null;
  11160. previousPinchDistance = 0;
  11161. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11162. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11163. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11164. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11165. pointers.empty();
  11166. if (!noPreventDefault) {
  11167. evt.preventDefault();
  11168. }
  11169. };
  11170. this._onContextMenu = function (evt) {
  11171. evt.preventDefault();
  11172. };
  11173. this._onPointerMove = function (evt) {
  11174. if (!noPreventDefault) {
  11175. evt.preventDefault();
  11176. }
  11177. switch (pointers.count) {
  11178. case 1:
  11179. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11180. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11181. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11182. }
  11183. else {
  11184. var offsetX = evt.clientX - cacheSoloPointer.x;
  11185. var offsetY = evt.clientY - cacheSoloPointer.y;
  11186. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11187. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11188. }
  11189. cacheSoloPointer.x = evt.clientX;
  11190. cacheSoloPointer.y = evt.clientY;
  11191. break;
  11192. case 2:
  11193. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11194. pointers.item(evt.pointerId).x = evt.clientX;
  11195. pointers.item(evt.pointerId).y = evt.clientY;
  11196. var direction = _this.pinchInwards ? 1 : -1;
  11197. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11198. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11199. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11200. if (previousPinchDistance === 0) {
  11201. previousPinchDistance = pinchSquaredDistance;
  11202. return;
  11203. }
  11204. if (pinchSquaredDistance !== previousPinchDistance) {
  11205. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11206. previousPinchDistance = pinchSquaredDistance;
  11207. }
  11208. break;
  11209. default:
  11210. if (pointers.item(evt.pointerId)) {
  11211. pointers.item(evt.pointerId).x = evt.clientX;
  11212. pointers.item(evt.pointerId).y = evt.clientY;
  11213. }
  11214. }
  11215. };
  11216. this._onMouseMove = function (evt) {
  11217. if (!engine.isPointerLock) {
  11218. return;
  11219. }
  11220. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11221. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11222. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11223. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11224. if (!noPreventDefault) {
  11225. evt.preventDefault();
  11226. }
  11227. };
  11228. this._wheel = function (event) {
  11229. var delta = 0;
  11230. if (event.wheelDelta) {
  11231. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11232. }
  11233. else if (event.detail) {
  11234. delta = -event.detail / _this.wheelPrecision;
  11235. }
  11236. if (delta)
  11237. _this.inertialRadiusOffset += delta;
  11238. if (event.preventDefault) {
  11239. if (!noPreventDefault) {
  11240. event.preventDefault();
  11241. }
  11242. }
  11243. };
  11244. this._onKeyDown = function (evt) {
  11245. _this._isCtrlPushed = evt.ctrlKey;
  11246. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11247. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11248. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11249. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11250. var index = _this._keys.indexOf(evt.keyCode);
  11251. if (index === -1) {
  11252. _this._keys.push(evt.keyCode);
  11253. }
  11254. if (evt.preventDefault) {
  11255. if (!noPreventDefault) {
  11256. evt.preventDefault();
  11257. }
  11258. }
  11259. }
  11260. };
  11261. this._onKeyUp = function (evt) {
  11262. _this._isCtrlPushed = evt.ctrlKey;
  11263. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11264. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11265. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11266. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11267. var index = _this._keys.indexOf(evt.keyCode);
  11268. if (index >= 0) {
  11269. _this._keys.splice(index, 1);
  11270. }
  11271. if (evt.preventDefault) {
  11272. if (!noPreventDefault) {
  11273. evt.preventDefault();
  11274. }
  11275. }
  11276. }
  11277. };
  11278. this._onLostFocus = function () {
  11279. _this._keys = [];
  11280. pointers.empty();
  11281. previousPinchDistance = 0;
  11282. cacheSoloPointer = null;
  11283. };
  11284. this._onGestureStart = function (e) {
  11285. if (window.MSGesture === undefined) {
  11286. return;
  11287. }
  11288. if (!_this._MSGestureHandler) {
  11289. _this._MSGestureHandler = new MSGesture();
  11290. _this._MSGestureHandler.target = element;
  11291. }
  11292. _this._MSGestureHandler.addPointer(e.pointerId);
  11293. };
  11294. this._onGesture = function (e) {
  11295. _this.radius *= e.scale;
  11296. if (e.preventDefault) {
  11297. if (!noPreventDefault) {
  11298. e.stopPropagation();
  11299. e.preventDefault();
  11300. }
  11301. }
  11302. };
  11303. this._reset = function () {
  11304. _this._keys = [];
  11305. _this.inertialAlphaOffset = 0;
  11306. _this.inertialBetaOffset = 0;
  11307. _this.inertialRadiusOffset = 0;
  11308. pointers.empty();
  11309. previousPinchDistance = 0;
  11310. cacheSoloPointer = null;
  11311. };
  11312. }
  11313. if (!useCtrlForPanning) {
  11314. element.addEventListener("contextmenu", this._onContextMenu, false);
  11315. }
  11316. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11317. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11318. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11319. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11320. element.addEventListener("mousemove", this._onMouseMove, false);
  11321. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11322. element.addEventListener("MSGestureChange", this._onGesture, false);
  11323. element.addEventListener('mousewheel', this._wheel, false);
  11324. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11325. BABYLON.Tools.RegisterTopRootEvents([
  11326. { name: "keydown", handler: this._onKeyDown },
  11327. { name: "keyup", handler: this._onKeyUp },
  11328. { name: "blur", handler: this._onLostFocus }
  11329. ]);
  11330. };
  11331. ArcRotateCamera.prototype.detachControl = function (element) {
  11332. if (this._attachedElement !== element) {
  11333. return;
  11334. }
  11335. element.removeEventListener("contextmenu", this._onContextMenu);
  11336. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11337. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11338. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11339. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11340. element.removeEventListener("mousemove", this._onMouseMove);
  11341. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11342. element.removeEventListener("MSGestureChange", this._onGesture);
  11343. element.removeEventListener('mousewheel', this._wheel);
  11344. element.removeEventListener('DOMMouseScroll', this._wheel);
  11345. BABYLON.Tools.UnregisterTopRootEvents([
  11346. { name: "keydown", handler: this._onKeyDown },
  11347. { name: "keyup", handler: this._onKeyUp },
  11348. { name: "blur", handler: this._onLostFocus }
  11349. ]);
  11350. this._MSGestureHandler = null;
  11351. this._attachedElement = null;
  11352. if (this._reset) {
  11353. this._reset();
  11354. }
  11355. };
  11356. ArcRotateCamera.prototype._checkInputs = function () {
  11357. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11358. if (this._collisionTriggered) {
  11359. return;
  11360. }
  11361. // Keyboard
  11362. for (var index = 0; index < this._keys.length; index++) {
  11363. var keyCode = this._keys[index];
  11364. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11365. this.inertialAlphaOffset -= 0.01;
  11366. }
  11367. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11368. this.inertialBetaOffset -= 0.01;
  11369. }
  11370. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11371. this.inertialAlphaOffset += 0.01;
  11372. }
  11373. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11374. this.inertialBetaOffset += 0.01;
  11375. }
  11376. }
  11377. // Inertia
  11378. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11379. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11380. this.beta += this.inertialBetaOffset;
  11381. this.radius -= this.inertialRadiusOffset;
  11382. this.inertialAlphaOffset *= this.inertia;
  11383. this.inertialBetaOffset *= this.inertia;
  11384. this.inertialRadiusOffset *= this.inertia;
  11385. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11386. this.inertialAlphaOffset = 0;
  11387. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11388. this.inertialBetaOffset = 0;
  11389. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11390. this.inertialRadiusOffset = 0;
  11391. }
  11392. // Panning inertia
  11393. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11394. if (!this._localDirection) {
  11395. this._localDirection = BABYLON.Vector3.Zero();
  11396. this._transformedDirection = BABYLON.Vector3.Zero();
  11397. }
  11398. this.inertialPanningX *= this.inertia;
  11399. this.inertialPanningY *= this.inertia;
  11400. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11401. this.inertialPanningX = 0;
  11402. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11403. this.inertialPanningY = 0;
  11404. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11405. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11406. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11407. this.target.addInPlace(this._transformedDirection);
  11408. }
  11409. // Limits
  11410. this._checkLimits();
  11411. _super.prototype._checkInputs.call(this);
  11412. };
  11413. ArcRotateCamera.prototype._checkLimits = function () {
  11414. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11415. if (this.allowUpsideDown && this.beta > Math.PI) {
  11416. this.beta = this.beta - (2 * Math.PI);
  11417. }
  11418. }
  11419. else {
  11420. if (this.beta < this.lowerBetaLimit) {
  11421. this.beta = this.lowerBetaLimit;
  11422. }
  11423. }
  11424. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11425. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11426. this.beta = this.beta + (2 * Math.PI);
  11427. }
  11428. }
  11429. else {
  11430. if (this.beta > this.upperBetaLimit) {
  11431. this.beta = this.upperBetaLimit;
  11432. }
  11433. }
  11434. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11435. this.alpha = this.lowerAlphaLimit;
  11436. }
  11437. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11438. this.alpha = this.upperAlphaLimit;
  11439. }
  11440. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11441. this.radius = this.lowerRadiusLimit;
  11442. }
  11443. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11444. this.radius = this.upperRadiusLimit;
  11445. }
  11446. };
  11447. ArcRotateCamera.prototype.setPosition = function (position) {
  11448. var radiusv3 = position.subtract(this._getTargetPosition());
  11449. this.radius = radiusv3.length();
  11450. // Alpha
  11451. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11452. if (radiusv3.z < 0) {
  11453. this.alpha = 2 * Math.PI - this.alpha;
  11454. }
  11455. // Beta
  11456. this.beta = Math.acos(radiusv3.y / this.radius);
  11457. this._checkLimits();
  11458. };
  11459. ArcRotateCamera.prototype.setTarget = function (target) {
  11460. this.target = target;
  11461. };
  11462. ArcRotateCamera.prototype._getViewMatrix = function () {
  11463. // Compute
  11464. var cosa = Math.cos(this.alpha);
  11465. var sina = Math.sin(this.alpha);
  11466. var cosb = Math.cos(this.beta);
  11467. var sinb = Math.sin(this.beta);
  11468. var target = this._getTargetPosition();
  11469. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11470. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11471. this._collider.radius = this.collisionRadius;
  11472. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11473. this._collisionTriggered = true;
  11474. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11475. }
  11476. else {
  11477. this.position.copyFrom(this._newPosition);
  11478. var up = this.upVector;
  11479. if (this.allowUpsideDown && this.beta < 0) {
  11480. var up = up.clone();
  11481. up = up.negate();
  11482. }
  11483. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11484. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11485. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11486. }
  11487. return this._viewMatrix;
  11488. };
  11489. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11490. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11491. meshes = meshes || this.getScene().meshes;
  11492. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11493. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11494. this.radius = distance * this.zoomOnFactor;
  11495. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11496. };
  11497. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11498. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11499. var meshesOrMinMaxVector;
  11500. var distance;
  11501. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11502. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11503. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11504. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11505. }
  11506. else {
  11507. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11508. distance = meshesOrMinMaxVectorAndDistance.distance;
  11509. }
  11510. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11511. if (!doNotUpdateMaxZ) {
  11512. this.maxZ = distance * 2;
  11513. }
  11514. };
  11515. /**
  11516. * @override
  11517. * Override Camera.createRigCamera
  11518. */
  11519. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11520. switch (this.cameraRigMode) {
  11521. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11522. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11523. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11524. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11525. case BABYLON.Camera.RIG_MODE_VR:
  11526. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11527. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11528. }
  11529. };
  11530. /**
  11531. * @override
  11532. * Override Camera._updateRigCameras
  11533. */
  11534. ArcRotateCamera.prototype._updateRigCameras = function () {
  11535. switch (this.cameraRigMode) {
  11536. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11537. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11538. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11539. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11540. case BABYLON.Camera.RIG_MODE_VR:
  11541. var camLeft = this._rigCameras[0];
  11542. var camRight = this._rigCameras[1];
  11543. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11544. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11545. camLeft.beta = camRight.beta = this.beta;
  11546. camLeft.radius = camRight.radius = this.radius;
  11547. break;
  11548. }
  11549. _super.prototype._updateRigCameras.call(this);
  11550. };
  11551. return ArcRotateCamera;
  11552. })(BABYLON.TargetCamera);
  11553. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11554. })(BABYLON || (BABYLON = {}));
  11555. var BABYLON;
  11556. (function (BABYLON) {
  11557. // We're mainly based on the logic defined into the FreeCamera code
  11558. var DeviceOrientationCamera = (function (_super) {
  11559. __extends(DeviceOrientationCamera, _super);
  11560. function DeviceOrientationCamera(name, position, scene) {
  11561. var _this = this;
  11562. _super.call(this, name, position, scene);
  11563. this._offsetX = null;
  11564. this._offsetY = null;
  11565. this._orientationGamma = 0;
  11566. this._orientationBeta = 0;
  11567. this._initialOrientationGamma = 0;
  11568. this._initialOrientationBeta = 0;
  11569. this.angularSensibility = 10000.0;
  11570. this.moveSensibility = 50.0;
  11571. window.addEventListener("resize", function () {
  11572. _this._initialOrientationGamma = null;
  11573. }, false);
  11574. }
  11575. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11576. var _this = this;
  11577. if (this._attachedCanvas) {
  11578. return;
  11579. }
  11580. this._attachedCanvas = canvas;
  11581. if (!this._orientationChanged) {
  11582. this._orientationChanged = function (evt) {
  11583. if (!_this._initialOrientationGamma) {
  11584. _this._initialOrientationGamma = evt.gamma;
  11585. _this._initialOrientationBeta = evt.beta;
  11586. }
  11587. _this._orientationGamma = evt.gamma;
  11588. _this._orientationBeta = evt.beta;
  11589. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11590. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11591. };
  11592. }
  11593. window.addEventListener("deviceorientation", this._orientationChanged);
  11594. };
  11595. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11596. if (this._attachedCanvas != canvas) {
  11597. return;
  11598. }
  11599. window.removeEventListener("deviceorientation", this._orientationChanged);
  11600. this._attachedCanvas = null;
  11601. this._orientationGamma = 0;
  11602. this._orientationBeta = 0;
  11603. this._initialOrientationGamma = 0;
  11604. this._initialOrientationBeta = 0;
  11605. };
  11606. DeviceOrientationCamera.prototype._checkInputs = function () {
  11607. if (!this._offsetX) {
  11608. return;
  11609. }
  11610. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11611. var speed = this._computeLocalCameraSpeed();
  11612. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11613. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11614. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11615. _super.prototype._checkInputs.call(this);
  11616. };
  11617. return DeviceOrientationCamera;
  11618. })(BABYLON.FreeCamera);
  11619. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11620. })(BABYLON || (BABYLON = {}));
  11621. var BABYLON;
  11622. (function (BABYLON) {
  11623. var Gamepads = (function () {
  11624. function Gamepads(ongamedpadconnected) {
  11625. var _this = this;
  11626. this.babylonGamepads = [];
  11627. this.oneGamepadConnected = false;
  11628. this.isMonitoring = false;
  11629. this.gamepadEventSupported = 'GamepadEvent' in window;
  11630. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11631. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11632. 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=";
  11633. this._callbackGamepadConnected = ongamedpadconnected;
  11634. if (this.gamepadSupportAvailable) {
  11635. // Checking if the gamepad connected event is supported (like in Firefox)
  11636. if (this.gamepadEventSupported) {
  11637. window.addEventListener('gamepadconnected', function (evt) {
  11638. _this._onGamepadConnected(evt);
  11639. }, false);
  11640. window.addEventListener('gamepaddisconnected', function (evt) {
  11641. _this._onGamepadDisconnected(evt);
  11642. }, false);
  11643. }
  11644. else {
  11645. this._startMonitoringGamepads();
  11646. }
  11647. if (!this.oneGamepadConnected) {
  11648. this._insertGamepadDOMInstructions();
  11649. }
  11650. }
  11651. else {
  11652. this._insertGamepadDOMNotSupported();
  11653. }
  11654. }
  11655. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11656. Gamepads.gamepadDOMInfo = document.createElement("div");
  11657. var buttonAImage = document.createElement("img");
  11658. buttonAImage.src = this.buttonADataURL;
  11659. var spanMessage = document.createElement("span");
  11660. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11661. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11662. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11663. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11664. Gamepads.gamepadDOMInfo.style.width = "100%";
  11665. Gamepads.gamepadDOMInfo.style.height = "48px";
  11666. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11667. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11668. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11669. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11670. buttonAImage.style.position = "relative";
  11671. buttonAImage.style.bottom = "8px";
  11672. spanMessage.style.position = "relative";
  11673. spanMessage.style.fontSize = "32px";
  11674. spanMessage.style.bottom = "32px";
  11675. spanMessage.style.color = "green";
  11676. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11677. };
  11678. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11679. Gamepads.gamepadDOMInfo = document.createElement("div");
  11680. var spanMessage = document.createElement("span");
  11681. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11682. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11683. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11684. Gamepads.gamepadDOMInfo.style.width = "100%";
  11685. Gamepads.gamepadDOMInfo.style.height = "40px";
  11686. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11687. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11688. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11689. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11690. spanMessage.style.position = "relative";
  11691. spanMessage.style.fontSize = "32px";
  11692. spanMessage.style.color = "red";
  11693. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11694. };
  11695. Gamepads.prototype.dispose = function () {
  11696. if (Gamepads.gamepadDOMInfo) {
  11697. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11698. }
  11699. };
  11700. Gamepads.prototype._onGamepadConnected = function (evt) {
  11701. var newGamepad = this._addNewGamepad(evt.gamepad);
  11702. if (this._callbackGamepadConnected)
  11703. this._callbackGamepadConnected(newGamepad);
  11704. this._startMonitoringGamepads();
  11705. };
  11706. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11707. if (!this.oneGamepadConnected) {
  11708. this.oneGamepadConnected = true;
  11709. if (Gamepads.gamepadDOMInfo) {
  11710. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11711. Gamepads.gamepadDOMInfo = null;
  11712. }
  11713. }
  11714. var newGamepad;
  11715. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11716. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11717. }
  11718. else {
  11719. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11720. }
  11721. this.babylonGamepads.push(newGamepad);
  11722. return newGamepad;
  11723. };
  11724. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11725. // Remove the gamepad from the list of gamepads to monitor.
  11726. for (var i in this.babylonGamepads) {
  11727. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11728. this.babylonGamepads.splice(i, 1);
  11729. break;
  11730. }
  11731. }
  11732. // If no gamepads are left, stop the polling loop.
  11733. if (this.babylonGamepads.length == 0) {
  11734. this._stopMonitoringGamepads();
  11735. }
  11736. };
  11737. Gamepads.prototype._startMonitoringGamepads = function () {
  11738. if (!this.isMonitoring) {
  11739. this.isMonitoring = true;
  11740. this._checkGamepadsStatus();
  11741. }
  11742. };
  11743. Gamepads.prototype._stopMonitoringGamepads = function () {
  11744. this.isMonitoring = false;
  11745. };
  11746. Gamepads.prototype._checkGamepadsStatus = function () {
  11747. var _this = this;
  11748. // updating gamepad objects
  11749. this._updateGamepadObjects();
  11750. for (var i in this.babylonGamepads) {
  11751. this.babylonGamepads[i].update();
  11752. }
  11753. if (this.isMonitoring) {
  11754. if (window.requestAnimationFrame) {
  11755. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11756. }
  11757. else if (window.mozRequestAnimationFrame) {
  11758. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11759. }
  11760. else if (window.webkitRequestAnimationFrame) {
  11761. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11762. }
  11763. }
  11764. };
  11765. // This function is called only on Chrome, which does not yet support
  11766. // connection/disconnection events, but requires you to monitor
  11767. // an array for changes.
  11768. Gamepads.prototype._updateGamepadObjects = function () {
  11769. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11770. for (var i = 0; i < gamepads.length; i++) {
  11771. if (gamepads[i]) {
  11772. if (!(gamepads[i].index in this.babylonGamepads)) {
  11773. var newGamepad = this._addNewGamepad(gamepads[i]);
  11774. if (this._callbackGamepadConnected) {
  11775. this._callbackGamepadConnected(newGamepad);
  11776. }
  11777. }
  11778. else {
  11779. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11780. }
  11781. }
  11782. }
  11783. };
  11784. return Gamepads;
  11785. })();
  11786. BABYLON.Gamepads = Gamepads;
  11787. var StickValues = (function () {
  11788. function StickValues(x, y) {
  11789. this.x = x;
  11790. this.y = y;
  11791. }
  11792. return StickValues;
  11793. })();
  11794. BABYLON.StickValues = StickValues;
  11795. var Gamepad = (function () {
  11796. function Gamepad(id, index, browserGamepad) {
  11797. this.id = id;
  11798. this.index = index;
  11799. this.browserGamepad = browserGamepad;
  11800. if (this.browserGamepad.axes.length >= 2) {
  11801. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11802. }
  11803. if (this.browserGamepad.axes.length >= 4) {
  11804. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11805. }
  11806. }
  11807. Gamepad.prototype.onleftstickchanged = function (callback) {
  11808. this._onleftstickchanged = callback;
  11809. };
  11810. Gamepad.prototype.onrightstickchanged = function (callback) {
  11811. this._onrightstickchanged = callback;
  11812. };
  11813. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11814. get: function () {
  11815. return this._leftStick;
  11816. },
  11817. set: function (newValues) {
  11818. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11819. this._onleftstickchanged(newValues);
  11820. }
  11821. this._leftStick = newValues;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11827. get: function () {
  11828. return this._rightStick;
  11829. },
  11830. set: function (newValues) {
  11831. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11832. this._onrightstickchanged(newValues);
  11833. }
  11834. this._rightStick = newValues;
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Gamepad.prototype.update = function () {
  11840. if (this._leftStick) {
  11841. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11842. }
  11843. if (this._rightStick) {
  11844. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11845. }
  11846. };
  11847. return Gamepad;
  11848. })();
  11849. BABYLON.Gamepad = Gamepad;
  11850. var GenericPad = (function (_super) {
  11851. __extends(GenericPad, _super);
  11852. function GenericPad(id, index, gamepad) {
  11853. _super.call(this, id, index, gamepad);
  11854. this.id = id;
  11855. this.index = index;
  11856. this.gamepad = gamepad;
  11857. this._buttons = new Array(gamepad.buttons.length);
  11858. }
  11859. GenericPad.prototype.onbuttondown = function (callback) {
  11860. this._onbuttondown = callback;
  11861. };
  11862. GenericPad.prototype.onbuttonup = function (callback) {
  11863. this._onbuttonup = callback;
  11864. };
  11865. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11866. if (newValue !== currentValue) {
  11867. if (this._onbuttondown && newValue === 1) {
  11868. this._onbuttondown(buttonIndex);
  11869. }
  11870. if (this._onbuttonup && newValue === 0) {
  11871. this._onbuttonup(buttonIndex);
  11872. }
  11873. }
  11874. return newValue;
  11875. };
  11876. GenericPad.prototype.update = function () {
  11877. _super.prototype.update.call(this);
  11878. for (var index = 0; index < this._buttons.length; index++) {
  11879. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11880. }
  11881. };
  11882. return GenericPad;
  11883. })(Gamepad);
  11884. BABYLON.GenericPad = GenericPad;
  11885. (function (Xbox360Button) {
  11886. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11887. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11888. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11889. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11890. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11891. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11892. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11893. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11894. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11895. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11896. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11897. var Xbox360Button = BABYLON.Xbox360Button;
  11898. (function (Xbox360Dpad) {
  11899. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11900. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11901. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11902. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11903. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11904. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11905. var Xbox360Pad = (function (_super) {
  11906. __extends(Xbox360Pad, _super);
  11907. function Xbox360Pad() {
  11908. _super.apply(this, arguments);
  11909. this._leftTrigger = 0;
  11910. this._rightTrigger = 0;
  11911. this._buttonA = 0;
  11912. this._buttonB = 0;
  11913. this._buttonX = 0;
  11914. this._buttonY = 0;
  11915. this._buttonBack = 0;
  11916. this._buttonStart = 0;
  11917. this._buttonLB = 0;
  11918. this._buttonRB = 0;
  11919. this._buttonLeftStick = 0;
  11920. this._buttonRightStick = 0;
  11921. this._dPadUp = 0;
  11922. this._dPadDown = 0;
  11923. this._dPadLeft = 0;
  11924. this._dPadRight = 0;
  11925. }
  11926. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11927. this._onlefttriggerchanged = callback;
  11928. };
  11929. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11930. this._onrighttriggerchanged = callback;
  11931. };
  11932. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11933. get: function () {
  11934. return this._leftTrigger;
  11935. },
  11936. set: function (newValue) {
  11937. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11938. this._onlefttriggerchanged(newValue);
  11939. }
  11940. this._leftTrigger = newValue;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11946. get: function () {
  11947. return this._rightTrigger;
  11948. },
  11949. set: function (newValue) {
  11950. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11951. this._onrighttriggerchanged(newValue);
  11952. }
  11953. this._rightTrigger = newValue;
  11954. },
  11955. enumerable: true,
  11956. configurable: true
  11957. });
  11958. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11959. this._onbuttondown = callback;
  11960. };
  11961. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11962. this._onbuttonup = callback;
  11963. };
  11964. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11965. this._ondpaddown = callback;
  11966. };
  11967. Xbox360Pad.prototype.ondpadup = function (callback) {
  11968. this._ondpadup = callback;
  11969. };
  11970. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11971. if (newValue !== currentValue) {
  11972. if (this._onbuttondown && newValue === 1) {
  11973. this._onbuttondown(buttonType);
  11974. }
  11975. if (this._onbuttonup && newValue === 0) {
  11976. this._onbuttonup(buttonType);
  11977. }
  11978. }
  11979. return newValue;
  11980. };
  11981. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11982. if (newValue !== currentValue) {
  11983. if (this._ondpaddown && newValue === 1) {
  11984. this._ondpaddown(buttonType);
  11985. }
  11986. if (this._ondpadup && newValue === 0) {
  11987. this._ondpadup(buttonType);
  11988. }
  11989. }
  11990. return newValue;
  11991. };
  11992. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11993. get: function () {
  11994. return this._buttonA;
  11995. },
  11996. set: function (value) {
  11997. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  12003. get: function () {
  12004. return this._buttonB;
  12005. },
  12006. set: function (value) {
  12007. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  12008. },
  12009. enumerable: true,
  12010. configurable: true
  12011. });
  12012. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  12013. get: function () {
  12014. return this._buttonX;
  12015. },
  12016. set: function (value) {
  12017. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  12018. },
  12019. enumerable: true,
  12020. configurable: true
  12021. });
  12022. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  12023. get: function () {
  12024. return this._buttonY;
  12025. },
  12026. set: function (value) {
  12027. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  12028. },
  12029. enumerable: true,
  12030. configurable: true
  12031. });
  12032. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  12033. get: function () {
  12034. return this._buttonStart;
  12035. },
  12036. set: function (value) {
  12037. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  12038. },
  12039. enumerable: true,
  12040. configurable: true
  12041. });
  12042. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  12043. get: function () {
  12044. return this._buttonBack;
  12045. },
  12046. set: function (value) {
  12047. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  12048. },
  12049. enumerable: true,
  12050. configurable: true
  12051. });
  12052. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  12053. get: function () {
  12054. return this._buttonLB;
  12055. },
  12056. set: function (value) {
  12057. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  12058. },
  12059. enumerable: true,
  12060. configurable: true
  12061. });
  12062. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  12063. get: function () {
  12064. return this._buttonRB;
  12065. },
  12066. set: function (value) {
  12067. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  12068. },
  12069. enumerable: true,
  12070. configurable: true
  12071. });
  12072. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  12073. get: function () {
  12074. return this._buttonLeftStick;
  12075. },
  12076. set: function (value) {
  12077. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  12078. },
  12079. enumerable: true,
  12080. configurable: true
  12081. });
  12082. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  12083. get: function () {
  12084. return this._buttonRightStick;
  12085. },
  12086. set: function (value) {
  12087. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12093. get: function () {
  12094. return this._dPadUp;
  12095. },
  12096. set: function (value) {
  12097. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12098. },
  12099. enumerable: true,
  12100. configurable: true
  12101. });
  12102. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12103. get: function () {
  12104. return this._dPadDown;
  12105. },
  12106. set: function (value) {
  12107. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12108. },
  12109. enumerable: true,
  12110. configurable: true
  12111. });
  12112. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12113. get: function () {
  12114. return this._dPadLeft;
  12115. },
  12116. set: function (value) {
  12117. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12118. },
  12119. enumerable: true,
  12120. configurable: true
  12121. });
  12122. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12123. get: function () {
  12124. return this._dPadRight;
  12125. },
  12126. set: function (value) {
  12127. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12128. },
  12129. enumerable: true,
  12130. configurable: true
  12131. });
  12132. Xbox360Pad.prototype.update = function () {
  12133. _super.prototype.update.call(this);
  12134. this.buttonA = this.browserGamepad.buttons[0].value;
  12135. this.buttonB = this.browserGamepad.buttons[1].value;
  12136. this.buttonX = this.browserGamepad.buttons[2].value;
  12137. this.buttonY = this.browserGamepad.buttons[3].value;
  12138. this.buttonLB = this.browserGamepad.buttons[4].value;
  12139. this.buttonRB = this.browserGamepad.buttons[5].value;
  12140. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12141. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12142. this.buttonBack = this.browserGamepad.buttons[8].value;
  12143. this.buttonStart = this.browserGamepad.buttons[9].value;
  12144. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12145. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12146. this.dPadUp = this.browserGamepad.buttons[12].value;
  12147. this.dPadDown = this.browserGamepad.buttons[13].value;
  12148. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12149. this.dPadRight = this.browserGamepad.buttons[15].value;
  12150. };
  12151. return Xbox360Pad;
  12152. })(Gamepad);
  12153. BABYLON.Xbox360Pad = Xbox360Pad;
  12154. })(BABYLON || (BABYLON = {}));
  12155. var BABYLON;
  12156. (function (BABYLON) {
  12157. // We're mainly based on the logic defined into the FreeCamera code
  12158. var GamepadCamera = (function (_super) {
  12159. __extends(GamepadCamera, _super);
  12160. function GamepadCamera(name, position, scene) {
  12161. var _this = this;
  12162. _super.call(this, name, position, scene);
  12163. this.angularSensibility = 200;
  12164. this.moveSensibility = 75;
  12165. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12166. }
  12167. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12168. // Only the first gamepad can control the camera
  12169. if (gamepad.index === 0) {
  12170. this._gamepad = gamepad;
  12171. }
  12172. };
  12173. GamepadCamera.prototype._checkInputs = function () {
  12174. if (this._gamepad) {
  12175. var LSValues = this._gamepad.leftStick;
  12176. var normalizedLX = LSValues.x / this.moveSensibility;
  12177. var normalizedLY = LSValues.y / this.moveSensibility;
  12178. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12179. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12180. var RSValues = this._gamepad.rightStick;
  12181. var normalizedRX = RSValues.x / this.angularSensibility;
  12182. var normalizedRY = RSValues.y / this.angularSensibility;
  12183. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12184. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12185. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12186. var speed = this._computeLocalCameraSpeed() * 50.0;
  12187. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12188. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12189. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12190. }
  12191. _super.prototype._checkInputs.call(this);
  12192. };
  12193. GamepadCamera.prototype.dispose = function () {
  12194. this._gamepads.dispose();
  12195. _super.prototype.dispose.call(this);
  12196. };
  12197. return GamepadCamera;
  12198. })(BABYLON.FreeCamera);
  12199. BABYLON.GamepadCamera = GamepadCamera;
  12200. })(BABYLON || (BABYLON = {}));
  12201. var BABYLON;
  12202. (function (BABYLON) {
  12203. var RenderingManager = (function () {
  12204. function RenderingManager(scene) {
  12205. this._renderingGroups = new Array();
  12206. this._scene = scene;
  12207. }
  12208. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12209. if (this._scene._activeParticleSystems.length === 0) {
  12210. return;
  12211. }
  12212. // Particles
  12213. var activeCamera = this._scene.activeCamera;
  12214. var beforeParticlesDate = BABYLON.Tools.Now;
  12215. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12216. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12217. if (particleSystem.renderingGroupId !== index) {
  12218. continue;
  12219. }
  12220. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12221. continue;
  12222. }
  12223. this._clearDepthBuffer();
  12224. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12225. this._scene._activeParticles += particleSystem.render();
  12226. }
  12227. }
  12228. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12229. };
  12230. RenderingManager.prototype._renderSprites = function (index) {
  12231. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12232. return;
  12233. }
  12234. // Sprites
  12235. var activeCamera = this._scene.activeCamera;
  12236. var beforeSpritessDate = BABYLON.Tools.Now;
  12237. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12238. var spriteManager = this._scene.spriteManagers[id];
  12239. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12240. this._clearDepthBuffer();
  12241. spriteManager.render();
  12242. }
  12243. }
  12244. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12245. };
  12246. RenderingManager.prototype._clearDepthBuffer = function () {
  12247. if (this._depthBufferAlreadyCleaned) {
  12248. return;
  12249. }
  12250. this._scene.getEngine().clear(0, false, true);
  12251. this._depthBufferAlreadyCleaned = true;
  12252. };
  12253. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12254. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12255. this._depthBufferAlreadyCleaned = false;
  12256. var renderingGroup = this._renderingGroups[index];
  12257. var needToStepBack = false;
  12258. if (renderingGroup) {
  12259. this._clearDepthBuffer();
  12260. if (!renderingGroup.render(customRenderFunction)) {
  12261. this._renderingGroups.splice(index, 1);
  12262. needToStepBack = true;
  12263. }
  12264. }
  12265. if (renderSprites) {
  12266. this._renderSprites(index);
  12267. }
  12268. if (renderParticles) {
  12269. this._renderParticles(index, activeMeshes);
  12270. }
  12271. if (needToStepBack) {
  12272. index--;
  12273. }
  12274. }
  12275. };
  12276. RenderingManager.prototype.reset = function () {
  12277. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12278. if (renderingGroup) {
  12279. renderingGroup.prepare();
  12280. }
  12281. });
  12282. };
  12283. RenderingManager.prototype.dispatch = function (subMesh) {
  12284. var mesh = subMesh.getMesh();
  12285. var renderingGroupId = mesh.renderingGroupId || 0;
  12286. if (!this._renderingGroups[renderingGroupId]) {
  12287. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12288. }
  12289. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12290. };
  12291. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12292. return RenderingManager;
  12293. })();
  12294. BABYLON.RenderingManager = RenderingManager;
  12295. })(BABYLON || (BABYLON = {}));
  12296. var BABYLON;
  12297. (function (BABYLON) {
  12298. var RenderingGroup = (function () {
  12299. function RenderingGroup(index, scene) {
  12300. this.index = index;
  12301. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12302. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12303. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12304. this._scene = scene;
  12305. }
  12306. RenderingGroup.prototype.render = function (customRenderFunction) {
  12307. if (customRenderFunction) {
  12308. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12309. return true;
  12310. }
  12311. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12312. return false;
  12313. }
  12314. var engine = this._scene.getEngine();
  12315. // Opaque
  12316. var subIndex;
  12317. var submesh;
  12318. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12319. submesh = this._opaqueSubMeshes.data[subIndex];
  12320. submesh.render(false);
  12321. }
  12322. // Alpha test
  12323. engine.setAlphaTesting(true);
  12324. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12325. submesh = this._alphaTestSubMeshes.data[subIndex];
  12326. submesh.render(false);
  12327. }
  12328. engine.setAlphaTesting(false);
  12329. // Transparent
  12330. if (this._transparentSubMeshes.length) {
  12331. // Sorting
  12332. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12333. submesh = this._transparentSubMeshes.data[subIndex];
  12334. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12335. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12336. }
  12337. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12338. sortedArray.sort(function (a, b) {
  12339. // Alpha index first
  12340. if (a._alphaIndex > b._alphaIndex) {
  12341. return 1;
  12342. }
  12343. if (a._alphaIndex < b._alphaIndex) {
  12344. return -1;
  12345. }
  12346. // Then distance to camera
  12347. if (a._distanceToCamera < b._distanceToCamera) {
  12348. return 1;
  12349. }
  12350. if (a._distanceToCamera > b._distanceToCamera) {
  12351. return -1;
  12352. }
  12353. return 0;
  12354. });
  12355. // Rendering
  12356. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12357. submesh = sortedArray[subIndex];
  12358. submesh.render(true);
  12359. }
  12360. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12361. }
  12362. return true;
  12363. };
  12364. RenderingGroup.prototype.prepare = function () {
  12365. this._opaqueSubMeshes.reset();
  12366. this._transparentSubMeshes.reset();
  12367. this._alphaTestSubMeshes.reset();
  12368. };
  12369. RenderingGroup.prototype.dispatch = function (subMesh) {
  12370. var material = subMesh.getMaterial();
  12371. var mesh = subMesh.getMesh();
  12372. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12373. this._transparentSubMeshes.push(subMesh);
  12374. }
  12375. else if (material.needAlphaTesting()) {
  12376. this._alphaTestSubMeshes.push(subMesh);
  12377. }
  12378. else {
  12379. this._opaqueSubMeshes.push(subMesh); // Opaque
  12380. }
  12381. };
  12382. return RenderingGroup;
  12383. })();
  12384. BABYLON.RenderingGroup = RenderingGroup;
  12385. })(BABYLON || (BABYLON = {}));
  12386. var BABYLON;
  12387. (function (BABYLON) {
  12388. /**
  12389. * Represents a scene to be rendered by the engine.
  12390. * @see http://doc.babylonjs.com/page.php?p=21911
  12391. */
  12392. var Scene = (function () {
  12393. /**
  12394. * @constructor
  12395. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12396. */
  12397. function Scene(engine) {
  12398. // Members
  12399. this.autoClear = true;
  12400. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12401. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12402. this.forceWireframe = false;
  12403. this.forcePointsCloud = false;
  12404. this.forceShowBoundingBoxes = false;
  12405. this.animationsEnabled = true;
  12406. 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
  12407. // Fog
  12408. /**
  12409. * is fog enabled on this scene.
  12410. * @type {boolean}
  12411. */
  12412. this.fogEnabled = true;
  12413. this.fogMode = Scene.FOGMODE_NONE;
  12414. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12415. this.fogDensity = 0.1;
  12416. this.fogStart = 0;
  12417. this.fogEnd = 1000.0;
  12418. // Lights
  12419. /**
  12420. * is shadow enabled on this scene.
  12421. * @type {boolean}
  12422. */
  12423. this.shadowsEnabled = true;
  12424. /**
  12425. * is light enabled on this scene.
  12426. * @type {boolean}
  12427. */
  12428. this.lightsEnabled = true;
  12429. /**
  12430. * All of the lights added to this scene.
  12431. * @see BABYLON.Light
  12432. * @type {BABYLON.Light[]}
  12433. */
  12434. this.lights = new Array();
  12435. // Cameras
  12436. /**
  12437. * All of the cameras added to this scene.
  12438. * @see BABYLON.Camera
  12439. * @type {BABYLON.Camera[]}
  12440. */
  12441. this.cameras = new Array();
  12442. this.activeCameras = new Array();
  12443. // Meshes
  12444. /**
  12445. * All of the (abstract) meshes added to this scene.
  12446. * @see BABYLON.AbstractMesh
  12447. * @type {BABYLON.AbstractMesh[]}
  12448. */
  12449. this.meshes = new Array();
  12450. // Geometries
  12451. this._geometries = new Array();
  12452. this.materials = new Array();
  12453. this.multiMaterials = new Array();
  12454. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12455. // Textures
  12456. this.texturesEnabled = true;
  12457. this.textures = new Array();
  12458. // Particles
  12459. this.particlesEnabled = true;
  12460. this.particleSystems = new Array();
  12461. // Sprites
  12462. this.spritesEnabled = true;
  12463. this.spriteManagers = new Array();
  12464. // Layers
  12465. this.layers = new Array();
  12466. // Skeletons
  12467. this.skeletonsEnabled = true;
  12468. this.skeletons = new Array();
  12469. // Lens flares
  12470. this.lensFlaresEnabled = true;
  12471. this.lensFlareSystems = new Array();
  12472. // Collisions
  12473. this.collisionsEnabled = true;
  12474. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12475. // Postprocesses
  12476. this.postProcessesEnabled = true;
  12477. // Customs render targets
  12478. this.renderTargetsEnabled = true;
  12479. this.dumpNextRenderTargets = false;
  12480. this.customRenderTargets = new Array();
  12481. // Imported meshes
  12482. this.importedMeshesFiles = new Array();
  12483. this._actionManagers = new Array();
  12484. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12485. // Procedural textures
  12486. this.proceduralTexturesEnabled = true;
  12487. this._proceduralTextures = new Array();
  12488. this.soundTracks = new Array();
  12489. this._audioEnabled = true;
  12490. this._headphone = false;
  12491. this._totalVertices = 0;
  12492. this._activeIndices = 0;
  12493. this._activeParticles = 0;
  12494. this._lastFrameDuration = 0;
  12495. this._evaluateActiveMeshesDuration = 0;
  12496. this._renderTargetsDuration = 0;
  12497. this._particlesDuration = 0;
  12498. this._renderDuration = 0;
  12499. this._spritesDuration = 0;
  12500. this._animationRatio = 0;
  12501. this._renderId = 0;
  12502. this._executeWhenReadyTimeoutId = -1;
  12503. this._toBeDisposed = new BABYLON.SmartArray(256);
  12504. this._onReadyCallbacks = new Array();
  12505. this._pendingData = []; //ANY
  12506. this._onBeforeRenderCallbacks = new Array();
  12507. this._onAfterRenderCallbacks = new Array();
  12508. this._activeMeshes = new BABYLON.SmartArray(256);
  12509. this._processedMaterials = new BABYLON.SmartArray(256);
  12510. this._renderTargets = new BABYLON.SmartArray(256);
  12511. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12512. this._activeSkeletons = new BABYLON.SmartArray(32);
  12513. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12514. this._activeBones = 0;
  12515. this._activeAnimatables = new Array();
  12516. this._transformMatrix = BABYLON.Matrix.Zero();
  12517. this._edgesRenderers = new BABYLON.SmartArray(16);
  12518. this._uniqueIdCounter = 0;
  12519. this._engine = engine;
  12520. engine.scenes.push(this);
  12521. this._renderingManager = new BABYLON.RenderingManager(this);
  12522. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12523. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12524. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12525. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12526. this.attachControl();
  12527. this._debugLayer = new BABYLON.DebugLayer(this);
  12528. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12529. //simplification queue
  12530. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12531. //collision coordinator initialization. For now legacy per default.
  12532. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12533. }
  12534. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12535. get: function () {
  12536. return Scene._FOGMODE_NONE;
  12537. },
  12538. enumerable: true,
  12539. configurable: true
  12540. });
  12541. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12542. get: function () {
  12543. return Scene._FOGMODE_EXP;
  12544. },
  12545. enumerable: true,
  12546. configurable: true
  12547. });
  12548. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12549. get: function () {
  12550. return Scene._FOGMODE_EXP2;
  12551. },
  12552. enumerable: true,
  12553. configurable: true
  12554. });
  12555. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12556. get: function () {
  12557. return Scene._FOGMODE_LINEAR;
  12558. },
  12559. enumerable: true,
  12560. configurable: true
  12561. });
  12562. Object.defineProperty(Scene.prototype, "debugLayer", {
  12563. // Properties
  12564. get: function () {
  12565. return this._debugLayer;
  12566. },
  12567. enumerable: true,
  12568. configurable: true
  12569. });
  12570. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12571. get: function () {
  12572. return this._workerCollisions;
  12573. },
  12574. set: function (enabled) {
  12575. enabled = (enabled && !!Worker);
  12576. this._workerCollisions = enabled;
  12577. if (this.collisionCoordinator) {
  12578. this.collisionCoordinator.destroy();
  12579. }
  12580. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12581. this.collisionCoordinator.init(this);
  12582. },
  12583. enumerable: true,
  12584. configurable: true
  12585. });
  12586. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12587. get: function () {
  12588. return this._selectionOctree;
  12589. },
  12590. enumerable: true,
  12591. configurable: true
  12592. });
  12593. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12594. /**
  12595. * The mesh that is currently under the pointer.
  12596. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12597. */
  12598. get: function () {
  12599. return this._meshUnderPointer;
  12600. },
  12601. enumerable: true,
  12602. configurable: true
  12603. });
  12604. Object.defineProperty(Scene.prototype, "pointerX", {
  12605. /**
  12606. * Current on-screen X position of the pointer
  12607. * @return {number} X position of the pointer
  12608. */
  12609. get: function () {
  12610. return this._pointerX;
  12611. },
  12612. enumerable: true,
  12613. configurable: true
  12614. });
  12615. Object.defineProperty(Scene.prototype, "pointerY", {
  12616. /**
  12617. * Current on-screen Y position of the pointer
  12618. * @return {number} Y position of the pointer
  12619. */
  12620. get: function () {
  12621. return this._pointerY;
  12622. },
  12623. enumerable: true,
  12624. configurable: true
  12625. });
  12626. Scene.prototype.getCachedMaterial = function () {
  12627. return this._cachedMaterial;
  12628. };
  12629. Scene.prototype.getBoundingBoxRenderer = function () {
  12630. return this._boundingBoxRenderer;
  12631. };
  12632. Scene.prototype.getOutlineRenderer = function () {
  12633. return this._outlineRenderer;
  12634. };
  12635. Scene.prototype.getEngine = function () {
  12636. return this._engine;
  12637. };
  12638. Scene.prototype.getTotalVertices = function () {
  12639. return this._totalVertices;
  12640. };
  12641. Scene.prototype.getActiveIndices = function () {
  12642. return this._activeIndices;
  12643. };
  12644. Scene.prototype.getActiveParticles = function () {
  12645. return this._activeParticles;
  12646. };
  12647. Scene.prototype.getActiveBones = function () {
  12648. return this._activeBones;
  12649. };
  12650. // Stats
  12651. Scene.prototype.getLastFrameDuration = function () {
  12652. return this._lastFrameDuration;
  12653. };
  12654. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12655. return this._evaluateActiveMeshesDuration;
  12656. };
  12657. Scene.prototype.getActiveMeshes = function () {
  12658. return this._activeMeshes;
  12659. };
  12660. Scene.prototype.getRenderTargetsDuration = function () {
  12661. return this._renderTargetsDuration;
  12662. };
  12663. Scene.prototype.getRenderDuration = function () {
  12664. return this._renderDuration;
  12665. };
  12666. Scene.prototype.getParticlesDuration = function () {
  12667. return this._particlesDuration;
  12668. };
  12669. Scene.prototype.getSpritesDuration = function () {
  12670. return this._spritesDuration;
  12671. };
  12672. Scene.prototype.getAnimationRatio = function () {
  12673. return this._animationRatio;
  12674. };
  12675. Scene.prototype.getRenderId = function () {
  12676. return this._renderId;
  12677. };
  12678. Scene.prototype.incrementRenderId = function () {
  12679. this._renderId++;
  12680. };
  12681. Scene.prototype._updatePointerPosition = function (evt) {
  12682. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12683. this._pointerX = evt.clientX - canvasRect.left;
  12684. this._pointerY = evt.clientY - canvasRect.top;
  12685. if (this.cameraToUseForPointers) {
  12686. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12687. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12688. }
  12689. };
  12690. // Pointers handling
  12691. Scene.prototype.attachControl = function () {
  12692. var _this = this;
  12693. this._onPointerMove = function (evt) {
  12694. var canvas = _this._engine.getRenderingCanvas();
  12695. _this._updatePointerPosition(evt);
  12696. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12697. if (pickResult.hit) {
  12698. _this._meshUnderPointer = pickResult.pickedMesh;
  12699. _this.setPointerOverMesh(pickResult.pickedMesh);
  12700. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12701. canvas.style.cursor = "pointer";
  12702. }
  12703. else {
  12704. canvas.style.cursor = "";
  12705. }
  12706. }
  12707. else {
  12708. _this.setPointerOverMesh(null);
  12709. canvas.style.cursor = "";
  12710. _this._meshUnderPointer = null;
  12711. }
  12712. };
  12713. this._onPointerDown = function (evt) {
  12714. var predicate = null;
  12715. if (!_this.onPointerDown) {
  12716. predicate = function (mesh) {
  12717. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12718. };
  12719. }
  12720. _this._updatePointerPosition(evt);
  12721. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12722. if (pickResult.hit) {
  12723. if (pickResult.pickedMesh.actionManager) {
  12724. switch (evt.button) {
  12725. case 0:
  12726. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12727. break;
  12728. case 1:
  12729. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12730. break;
  12731. case 2:
  12732. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12733. break;
  12734. }
  12735. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12736. }
  12737. }
  12738. if (_this.onPointerDown) {
  12739. _this.onPointerDown(evt, pickResult);
  12740. }
  12741. };
  12742. this._onPointerUp = function (evt) {
  12743. var predicate = null;
  12744. if (!_this.onPointerUp) {
  12745. predicate = function (mesh) {
  12746. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12747. };
  12748. }
  12749. _this._updatePointerPosition(evt);
  12750. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12751. if (pickResult.hit) {
  12752. if (pickResult.pickedMesh.actionManager) {
  12753. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12754. }
  12755. }
  12756. if (_this.onPointerUp) {
  12757. _this.onPointerUp(evt, pickResult);
  12758. }
  12759. };
  12760. this._onKeyDown = function (evt) {
  12761. if (_this.actionManager) {
  12762. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12763. }
  12764. };
  12765. this._onKeyUp = function (evt) {
  12766. if (_this.actionManager) {
  12767. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12768. }
  12769. };
  12770. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12771. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12772. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12773. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12774. // Wheel
  12775. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12776. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12777. BABYLON.Tools.RegisterTopRootEvents([
  12778. { name: "keydown", handler: this._onKeyDown },
  12779. { name: "keyup", handler: this._onKeyUp }
  12780. ]);
  12781. };
  12782. Scene.prototype.detachControl = function () {
  12783. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12784. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12785. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12786. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12787. // Wheel
  12788. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12789. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12790. BABYLON.Tools.UnregisterTopRootEvents([
  12791. { name: "keydown", handler: this._onKeyDown },
  12792. { name: "keyup", handler: this._onKeyUp }
  12793. ]);
  12794. };
  12795. // Ready
  12796. Scene.prototype.isReady = function () {
  12797. if (this._pendingData.length > 0) {
  12798. return false;
  12799. }
  12800. var index;
  12801. for (index = 0; index < this._geometries.length; index++) {
  12802. var geometry = this._geometries[index];
  12803. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12804. return false;
  12805. }
  12806. }
  12807. for (index = 0; index < this.meshes.length; index++) {
  12808. var mesh = this.meshes[index];
  12809. if (!mesh.isReady()) {
  12810. return false;
  12811. }
  12812. var mat = mesh.material;
  12813. if (mat) {
  12814. if (!mat.isReady(mesh)) {
  12815. return false;
  12816. }
  12817. }
  12818. }
  12819. return true;
  12820. };
  12821. Scene.prototype.resetCachedMaterial = function () {
  12822. this._cachedMaterial = null;
  12823. };
  12824. Scene.prototype.registerBeforeRender = function (func) {
  12825. this._onBeforeRenderCallbacks.push(func);
  12826. };
  12827. Scene.prototype.unregisterBeforeRender = function (func) {
  12828. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12829. if (index > -1) {
  12830. this._onBeforeRenderCallbacks.splice(index, 1);
  12831. }
  12832. };
  12833. Scene.prototype.registerAfterRender = function (func) {
  12834. this._onAfterRenderCallbacks.push(func);
  12835. };
  12836. Scene.prototype.unregisterAfterRender = function (func) {
  12837. var index = this._onAfterRenderCallbacks.indexOf(func);
  12838. if (index > -1) {
  12839. this._onAfterRenderCallbacks.splice(index, 1);
  12840. }
  12841. };
  12842. Scene.prototype._addPendingData = function (data) {
  12843. this._pendingData.push(data);
  12844. };
  12845. Scene.prototype._removePendingData = function (data) {
  12846. var index = this._pendingData.indexOf(data);
  12847. if (index !== -1) {
  12848. this._pendingData.splice(index, 1);
  12849. }
  12850. };
  12851. Scene.prototype.getWaitingItemsCount = function () {
  12852. return this._pendingData.length;
  12853. };
  12854. /**
  12855. * Registers a function to be executed when the scene is ready.
  12856. * @param {Function} func - the function to be executed.
  12857. */
  12858. Scene.prototype.executeWhenReady = function (func) {
  12859. var _this = this;
  12860. this._onReadyCallbacks.push(func);
  12861. if (this._executeWhenReadyTimeoutId !== -1) {
  12862. return;
  12863. }
  12864. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12865. _this._checkIsReady();
  12866. }, 150);
  12867. };
  12868. Scene.prototype._checkIsReady = function () {
  12869. var _this = this;
  12870. if (this.isReady()) {
  12871. this._onReadyCallbacks.forEach(function (func) {
  12872. func();
  12873. });
  12874. this._onReadyCallbacks = [];
  12875. this._executeWhenReadyTimeoutId = -1;
  12876. return;
  12877. }
  12878. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12879. _this._checkIsReady();
  12880. }, 150);
  12881. };
  12882. // Animations
  12883. /**
  12884. * Will start the animation sequence of a given target
  12885. * @param target - the target
  12886. * @param {number} from - from which frame should animation start
  12887. * @param {number} to - till which frame should animation run.
  12888. * @param {boolean} [loop] - should the animation loop
  12889. * @param {number} [speedRatio] - the speed in which to run the animation
  12890. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12891. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12892. * @return {BABYLON.Animatable} the animatable object created for this animation
  12893. * @see BABYLON.Animatable
  12894. * @see http://doc.babylonjs.com/page.php?p=22081
  12895. */
  12896. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12897. if (speedRatio === undefined) {
  12898. speedRatio = 1.0;
  12899. }
  12900. this.stopAnimation(target);
  12901. if (!animatable) {
  12902. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12903. }
  12904. // Local animations
  12905. if (target.animations) {
  12906. animatable.appendAnimations(target, target.animations);
  12907. }
  12908. // Children animations
  12909. if (target.getAnimatables) {
  12910. var animatables = target.getAnimatables();
  12911. for (var index = 0; index < animatables.length; index++) {
  12912. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12913. }
  12914. }
  12915. return animatable;
  12916. };
  12917. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12918. if (speedRatio === undefined) {
  12919. speedRatio = 1.0;
  12920. }
  12921. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12922. return animatable;
  12923. };
  12924. Scene.prototype.getAnimatableByTarget = function (target) {
  12925. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12926. if (this._activeAnimatables[index].target === target) {
  12927. return this._activeAnimatables[index];
  12928. }
  12929. }
  12930. return null;
  12931. };
  12932. /**
  12933. * Will stop the animation of the given target
  12934. * @param target - the target
  12935. * @see beginAnimation
  12936. */
  12937. Scene.prototype.stopAnimation = function (target) {
  12938. var animatable = this.getAnimatableByTarget(target);
  12939. if (animatable) {
  12940. animatable.stop();
  12941. }
  12942. };
  12943. Scene.prototype._animate = function () {
  12944. if (!this.animationsEnabled) {
  12945. return;
  12946. }
  12947. if (!this._animationStartDate) {
  12948. this._animationStartDate = BABYLON.Tools.Now;
  12949. }
  12950. // Getting time
  12951. var now = BABYLON.Tools.Now;
  12952. var delay = now - this._animationStartDate;
  12953. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12954. this._activeAnimatables[index]._animate(delay);
  12955. }
  12956. };
  12957. // Matrix
  12958. Scene.prototype.getViewMatrix = function () {
  12959. return this._viewMatrix;
  12960. };
  12961. Scene.prototype.getProjectionMatrix = function () {
  12962. return this._projectionMatrix;
  12963. };
  12964. Scene.prototype.getTransformMatrix = function () {
  12965. return this._transformMatrix;
  12966. };
  12967. Scene.prototype.setTransformMatrix = function (view, projection) {
  12968. this._viewMatrix = view;
  12969. this._projectionMatrix = projection;
  12970. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12971. };
  12972. // Methods
  12973. Scene.prototype.addMesh = function (newMesh) {
  12974. newMesh.uniqueId = this._uniqueIdCounter++;
  12975. var position = this.meshes.push(newMesh);
  12976. //notify the collision coordinator
  12977. this.collisionCoordinator.onMeshAdded(newMesh);
  12978. if (this.onNewMeshAdded) {
  12979. this.onNewMeshAdded(newMesh, position, this);
  12980. }
  12981. };
  12982. Scene.prototype.removeMesh = function (toRemove) {
  12983. var index = this.meshes.indexOf(toRemove);
  12984. if (index !== -1) {
  12985. // Remove from the scene if mesh found
  12986. this.meshes.splice(index, 1);
  12987. }
  12988. //notify the collision coordinator
  12989. this.collisionCoordinator.onMeshRemoved(toRemove);
  12990. if (this.onMeshRemoved) {
  12991. this.onMeshRemoved(toRemove);
  12992. }
  12993. return index;
  12994. };
  12995. Scene.prototype.removeLight = function (toRemove) {
  12996. var index = this.lights.indexOf(toRemove);
  12997. if (index !== -1) {
  12998. // Remove from the scene if mesh found
  12999. this.lights.splice(index, 1);
  13000. }
  13001. if (this.onLightRemoved) {
  13002. this.onLightRemoved(toRemove);
  13003. }
  13004. return index;
  13005. };
  13006. Scene.prototype.removeCamera = function (toRemove) {
  13007. var index = this.cameras.indexOf(toRemove);
  13008. if (index !== -1) {
  13009. // Remove from the scene if mesh found
  13010. this.cameras.splice(index, 1);
  13011. }
  13012. // Remove from activeCameras
  13013. var index2 = this.activeCameras.indexOf(toRemove);
  13014. if (index2 !== -1) {
  13015. // Remove from the scene if mesh found
  13016. this.activeCameras.splice(index2, 1);
  13017. }
  13018. // Reset the activeCamera
  13019. if (this.activeCamera === toRemove) {
  13020. if (this.cameras.length > 0) {
  13021. this.activeCamera = this.cameras[0];
  13022. }
  13023. else {
  13024. this.activeCamera = null;
  13025. }
  13026. }
  13027. if (this.onCameraRemoved) {
  13028. this.onCameraRemoved(toRemove);
  13029. }
  13030. return index;
  13031. };
  13032. Scene.prototype.addLight = function (newLight) {
  13033. newLight.uniqueId = this._uniqueIdCounter++;
  13034. var position = this.lights.push(newLight);
  13035. if (this.onNewLightAdded) {
  13036. this.onNewLightAdded(newLight, position, this);
  13037. }
  13038. };
  13039. Scene.prototype.addCamera = function (newCamera) {
  13040. newCamera.uniqueId = this._uniqueIdCounter++;
  13041. var position = this.cameras.push(newCamera);
  13042. if (this.onNewCameraAdded) {
  13043. this.onNewCameraAdded(newCamera, position, this);
  13044. }
  13045. };
  13046. /**
  13047. * sets the active camera of the scene using its ID
  13048. * @param {string} id - the camera's ID
  13049. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13050. * @see activeCamera
  13051. */
  13052. Scene.prototype.setActiveCameraByID = function (id) {
  13053. var camera = this.getCameraByID(id);
  13054. if (camera) {
  13055. this.activeCamera = camera;
  13056. return camera;
  13057. }
  13058. return null;
  13059. };
  13060. /**
  13061. * sets the active camera of the scene using its name
  13062. * @param {string} name - the camera's name
  13063. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13064. * @see activeCamera
  13065. */
  13066. Scene.prototype.setActiveCameraByName = function (name) {
  13067. var camera = this.getCameraByName(name);
  13068. if (camera) {
  13069. this.activeCamera = camera;
  13070. return camera;
  13071. }
  13072. return null;
  13073. };
  13074. /**
  13075. * get a material using its id
  13076. * @param {string} the material's ID
  13077. * @return {BABYLON.Material|null} the material or null if none found.
  13078. */
  13079. Scene.prototype.getMaterialByID = function (id) {
  13080. for (var index = 0; index < this.materials.length; index++) {
  13081. if (this.materials[index].id === id) {
  13082. return this.materials[index];
  13083. }
  13084. }
  13085. return null;
  13086. };
  13087. /**
  13088. * get a material using its name
  13089. * @param {string} the material's name
  13090. * @return {BABYLON.Material|null} the material or null if none found.
  13091. */
  13092. Scene.prototype.getMaterialByName = function (name) {
  13093. for (var index = 0; index < this.materials.length; index++) {
  13094. if (this.materials[index].name === name) {
  13095. return this.materials[index];
  13096. }
  13097. }
  13098. return null;
  13099. };
  13100. Scene.prototype.getLensFlareSystemByName = function (name) {
  13101. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13102. if (this.lensFlareSystems[index].name === name) {
  13103. return this.lensFlareSystems[index];
  13104. }
  13105. }
  13106. return null;
  13107. };
  13108. Scene.prototype.getCameraByID = function (id) {
  13109. for (var index = 0; index < this.cameras.length; index++) {
  13110. if (this.cameras[index].id === id) {
  13111. return this.cameras[index];
  13112. }
  13113. }
  13114. return null;
  13115. };
  13116. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13117. for (var index = 0; index < this.cameras.length; index++) {
  13118. if (this.cameras[index].uniqueId === uniqueId) {
  13119. return this.cameras[index];
  13120. }
  13121. }
  13122. return null;
  13123. };
  13124. /**
  13125. * get a camera using its name
  13126. * @param {string} the camera's name
  13127. * @return {BABYLON.Camera|null} the camera or null if none found.
  13128. */
  13129. Scene.prototype.getCameraByName = function (name) {
  13130. for (var index = 0; index < this.cameras.length; index++) {
  13131. if (this.cameras[index].name === name) {
  13132. return this.cameras[index];
  13133. }
  13134. }
  13135. return null;
  13136. };
  13137. /**
  13138. * get a light node using its name
  13139. * @param {string} the light's name
  13140. * @return {BABYLON.Light|null} the light or null if none found.
  13141. */
  13142. Scene.prototype.getLightByName = function (name) {
  13143. for (var index = 0; index < this.lights.length; index++) {
  13144. if (this.lights[index].name === name) {
  13145. return this.lights[index];
  13146. }
  13147. }
  13148. return null;
  13149. };
  13150. /**
  13151. * get a light node using its ID
  13152. * @param {string} the light's id
  13153. * @return {BABYLON.Light|null} the light or null if none found.
  13154. */
  13155. Scene.prototype.getLightByID = function (id) {
  13156. for (var index = 0; index < this.lights.length; index++) {
  13157. if (this.lights[index].id === id) {
  13158. return this.lights[index];
  13159. }
  13160. }
  13161. return null;
  13162. };
  13163. /**
  13164. * get a light node using its scene-generated unique ID
  13165. * @param {number} the light's unique id
  13166. * @return {BABYLON.Light|null} the light or null if none found.
  13167. */
  13168. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13169. for (var index = 0; index < this.lights.length; index++) {
  13170. if (this.lights[index].uniqueId === uniqueId) {
  13171. return this.lights[index];
  13172. }
  13173. }
  13174. return null;
  13175. };
  13176. /**
  13177. * get a geometry using its ID
  13178. * @param {string} the geometry's id
  13179. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13180. */
  13181. Scene.prototype.getGeometryByID = function (id) {
  13182. for (var index = 0; index < this._geometries.length; index++) {
  13183. if (this._geometries[index].id === id) {
  13184. return this._geometries[index];
  13185. }
  13186. }
  13187. return null;
  13188. };
  13189. /**
  13190. * add a new geometry to this scene.
  13191. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13192. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13193. * @return {boolean} was the geometry added or not
  13194. */
  13195. Scene.prototype.pushGeometry = function (geometry, force) {
  13196. if (!force && this.getGeometryByID(geometry.id)) {
  13197. return false;
  13198. }
  13199. this._geometries.push(geometry);
  13200. //notify the collision coordinator
  13201. this.collisionCoordinator.onGeometryAdded(geometry);
  13202. if (this.onGeometryAdded) {
  13203. this.onGeometryAdded(geometry);
  13204. }
  13205. return true;
  13206. };
  13207. /**
  13208. * Removes an existing geometry
  13209. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13210. * @return {boolean} was the geometry removed or not
  13211. */
  13212. Scene.prototype.removeGeometry = function (geometry) {
  13213. var index = this._geometries.indexOf(geometry);
  13214. if (index > -1) {
  13215. this._geometries.splice(index, 1);
  13216. //notify the collision coordinator
  13217. this.collisionCoordinator.onGeometryDeleted(geometry);
  13218. if (this.onGeometryRemoved) {
  13219. this.onGeometryRemoved(geometry);
  13220. }
  13221. return true;
  13222. }
  13223. return false;
  13224. };
  13225. Scene.prototype.getGeometries = function () {
  13226. return this._geometries;
  13227. };
  13228. /**
  13229. * Get the first added mesh found of a given ID
  13230. * @param {string} id - the id to search for
  13231. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13232. */
  13233. Scene.prototype.getMeshByID = function (id) {
  13234. for (var index = 0; index < this.meshes.length; index++) {
  13235. if (this.meshes[index].id === id) {
  13236. return this.meshes[index];
  13237. }
  13238. }
  13239. return null;
  13240. };
  13241. /**
  13242. * Get a mesh with its auto-generated unique id
  13243. * @param {number} uniqueId - the unique id to search for
  13244. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13245. */
  13246. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13247. for (var index = 0; index < this.meshes.length; index++) {
  13248. if (this.meshes[index].uniqueId === uniqueId) {
  13249. return this.meshes[index];
  13250. }
  13251. }
  13252. return null;
  13253. };
  13254. /**
  13255. * Get a the last added mesh found of a given ID
  13256. * @param {string} id - the id to search for
  13257. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13258. */
  13259. Scene.prototype.getLastMeshByID = function (id) {
  13260. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13261. if (this.meshes[index].id === id) {
  13262. return this.meshes[index];
  13263. }
  13264. }
  13265. return null;
  13266. };
  13267. /**
  13268. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13269. * @param {string} id - the id to search for
  13270. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13271. */
  13272. Scene.prototype.getLastEntryByID = function (id) {
  13273. var index;
  13274. for (index = this.meshes.length - 1; index >= 0; index--) {
  13275. if (this.meshes[index].id === id) {
  13276. return this.meshes[index];
  13277. }
  13278. }
  13279. for (index = this.cameras.length - 1; index >= 0; index--) {
  13280. if (this.cameras[index].id === id) {
  13281. return this.cameras[index];
  13282. }
  13283. }
  13284. for (index = this.lights.length - 1; index >= 0; index--) {
  13285. if (this.lights[index].id === id) {
  13286. return this.lights[index];
  13287. }
  13288. }
  13289. return null;
  13290. };
  13291. Scene.prototype.getNodeByID = function (id) {
  13292. var mesh = this.getMeshByID(id);
  13293. if (mesh) {
  13294. return mesh;
  13295. }
  13296. var light = this.getLightByID(id);
  13297. if (light) {
  13298. return light;
  13299. }
  13300. return this.getCameraByID(id);
  13301. };
  13302. Scene.prototype.getNodeByName = function (name) {
  13303. var mesh = this.getMeshByName(name);
  13304. if (mesh) {
  13305. return mesh;
  13306. }
  13307. var light = this.getLightByName(name);
  13308. if (light) {
  13309. return light;
  13310. }
  13311. return this.getCameraByName(name);
  13312. };
  13313. Scene.prototype.getMeshByName = function (name) {
  13314. for (var index = 0; index < this.meshes.length; index++) {
  13315. if (this.meshes[index].name === name) {
  13316. return this.meshes[index];
  13317. }
  13318. }
  13319. return null;
  13320. };
  13321. Scene.prototype.getSoundByName = function (name) {
  13322. var index;
  13323. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13324. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13325. return this.mainSoundTrack.soundCollection[index];
  13326. }
  13327. }
  13328. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13329. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13330. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13331. return this.soundTracks[sdIndex].soundCollection[index];
  13332. }
  13333. }
  13334. }
  13335. return null;
  13336. };
  13337. Scene.prototype.getLastSkeletonByID = function (id) {
  13338. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13339. if (this.skeletons[index].id === id) {
  13340. return this.skeletons[index];
  13341. }
  13342. }
  13343. return null;
  13344. };
  13345. Scene.prototype.getSkeletonById = function (id) {
  13346. for (var index = 0; index < this.skeletons.length; index++) {
  13347. if (this.skeletons[index].id === id) {
  13348. return this.skeletons[index];
  13349. }
  13350. }
  13351. return null;
  13352. };
  13353. Scene.prototype.getSkeletonByName = function (name) {
  13354. for (var index = 0; index < this.skeletons.length; index++) {
  13355. if (this.skeletons[index].name === name) {
  13356. return this.skeletons[index];
  13357. }
  13358. }
  13359. return null;
  13360. };
  13361. Scene.prototype.isActiveMesh = function (mesh) {
  13362. return (this._activeMeshes.indexOf(mesh) !== -1);
  13363. };
  13364. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13365. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13366. var material = subMesh.getMaterial();
  13367. if (mesh.showSubMeshesBoundingBox) {
  13368. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13369. }
  13370. if (material) {
  13371. // Render targets
  13372. if (material.getRenderTargetTextures) {
  13373. if (this._processedMaterials.indexOf(material) === -1) {
  13374. this._processedMaterials.push(material);
  13375. this._renderTargets.concat(material.getRenderTargetTextures());
  13376. }
  13377. }
  13378. // Dispatch
  13379. this._activeIndices += subMesh.indexCount;
  13380. this._renderingManager.dispatch(subMesh);
  13381. }
  13382. }
  13383. };
  13384. Scene.prototype._evaluateActiveMeshes = function () {
  13385. this.activeCamera._activeMeshes.reset();
  13386. this._activeMeshes.reset();
  13387. this._renderingManager.reset();
  13388. this._processedMaterials.reset();
  13389. this._activeParticleSystems.reset();
  13390. this._activeSkeletons.reset();
  13391. this._softwareSkinnedMeshes.reset();
  13392. this._boundingBoxRenderer.reset();
  13393. this._edgesRenderers.reset();
  13394. if (!this._frustumPlanes) {
  13395. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13396. }
  13397. else {
  13398. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13399. }
  13400. // Meshes
  13401. var meshes;
  13402. var len;
  13403. if (this._selectionOctree) {
  13404. var selection = this._selectionOctree.select(this._frustumPlanes);
  13405. meshes = selection.data;
  13406. len = selection.length;
  13407. }
  13408. else {
  13409. len = this.meshes.length;
  13410. meshes = this.meshes;
  13411. }
  13412. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13413. var mesh = meshes[meshIndex];
  13414. if (mesh.isBlocked) {
  13415. continue;
  13416. }
  13417. this._totalVertices += mesh.getTotalVertices();
  13418. if (!mesh.isReady() || !mesh.isEnabled()) {
  13419. continue;
  13420. }
  13421. mesh.computeWorldMatrix();
  13422. // Intersections
  13423. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13424. this._meshesForIntersections.pushNoDuplicate(mesh);
  13425. }
  13426. // Switch to current LOD
  13427. var meshLOD = mesh.getLOD(this.activeCamera);
  13428. if (!meshLOD) {
  13429. continue;
  13430. }
  13431. mesh._preActivate();
  13432. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13433. this._activeMeshes.push(mesh);
  13434. this.activeCamera._activeMeshes.push(mesh);
  13435. mesh._activate(this._renderId);
  13436. this._activeMesh(meshLOD);
  13437. }
  13438. }
  13439. // Particle systems
  13440. var beforeParticlesDate = BABYLON.Tools.Now;
  13441. if (this.particlesEnabled) {
  13442. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13443. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13444. var particleSystem = this.particleSystems[particleIndex];
  13445. if (!particleSystem.isStarted()) {
  13446. continue;
  13447. }
  13448. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13449. this._activeParticleSystems.push(particleSystem);
  13450. particleSystem.animate();
  13451. }
  13452. }
  13453. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13454. }
  13455. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13456. };
  13457. Scene.prototype._activeMesh = function (mesh) {
  13458. if (mesh.skeleton && this.skeletonsEnabled) {
  13459. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13460. if (!mesh.computeBonesUsingShaders) {
  13461. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13462. }
  13463. }
  13464. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13465. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13466. }
  13467. if (mesh._edgesRenderer) {
  13468. this._edgesRenderers.push(mesh._edgesRenderer);
  13469. }
  13470. if (mesh && mesh.subMeshes) {
  13471. // Submeshes Octrees
  13472. var len;
  13473. var subMeshes;
  13474. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13475. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13476. len = intersections.length;
  13477. subMeshes = intersections.data;
  13478. }
  13479. else {
  13480. subMeshes = mesh.subMeshes;
  13481. len = subMeshes.length;
  13482. }
  13483. for (var subIndex = 0; subIndex < len; subIndex++) {
  13484. var subMesh = subMeshes[subIndex];
  13485. this._evaluateSubMesh(subMesh, mesh);
  13486. }
  13487. }
  13488. };
  13489. Scene.prototype.updateTransformMatrix = function (force) {
  13490. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13491. };
  13492. Scene.prototype._renderForCamera = function (camera) {
  13493. var engine = this._engine;
  13494. this.activeCamera = camera;
  13495. if (!this.activeCamera)
  13496. throw new Error("Active camera not set");
  13497. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13498. // Viewport
  13499. engine.setViewport(this.activeCamera.viewport);
  13500. // Camera
  13501. this.resetCachedMaterial();
  13502. this._renderId++;
  13503. this.updateTransformMatrix();
  13504. if (this.beforeCameraRender) {
  13505. this.beforeCameraRender(this.activeCamera);
  13506. }
  13507. // Meshes
  13508. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13509. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13510. this._evaluateActiveMeshes();
  13511. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13512. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13513. // Skeletons
  13514. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13515. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13516. skeleton.prepare();
  13517. }
  13518. // Software skinning
  13519. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13520. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13521. mesh.applySkeleton(mesh.skeleton);
  13522. }
  13523. // Render targets
  13524. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13525. if (this.renderTargetsEnabled) {
  13526. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13527. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13528. var renderTarget = this._renderTargets.data[renderIndex];
  13529. if (renderTarget._shouldRender()) {
  13530. this._renderId++;
  13531. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13532. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13533. }
  13534. }
  13535. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13536. this._renderId++;
  13537. }
  13538. if (this._renderTargets.length > 0) {
  13539. engine.restoreDefaultFramebuffer();
  13540. }
  13541. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13542. // Prepare Frame
  13543. this.postProcessManager._prepareFrame();
  13544. var beforeRenderDate = BABYLON.Tools.Now;
  13545. // Backgrounds
  13546. var layerIndex;
  13547. var layer;
  13548. if (this.layers.length) {
  13549. engine.setDepthBuffer(false);
  13550. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13551. layer = this.layers[layerIndex];
  13552. if (layer.isBackground) {
  13553. layer.render();
  13554. }
  13555. }
  13556. engine.setDepthBuffer(true);
  13557. }
  13558. // Render
  13559. BABYLON.Tools.StartPerformanceCounter("Main render");
  13560. this._renderingManager.render(null, null, true, true);
  13561. BABYLON.Tools.EndPerformanceCounter("Main render");
  13562. // Bounding boxes
  13563. this._boundingBoxRenderer.render();
  13564. // Edges
  13565. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13566. this._edgesRenderers.data[edgesRendererIndex].render();
  13567. }
  13568. // Lens flares
  13569. if (this.lensFlaresEnabled) {
  13570. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13571. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13572. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13573. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13574. lensFlareSystem.render();
  13575. }
  13576. }
  13577. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13578. }
  13579. // Foregrounds
  13580. if (this.layers.length) {
  13581. engine.setDepthBuffer(false);
  13582. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13583. layer = this.layers[layerIndex];
  13584. if (!layer.isBackground) {
  13585. layer.render();
  13586. }
  13587. }
  13588. engine.setDepthBuffer(true);
  13589. }
  13590. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13591. // Finalize frame
  13592. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13593. // Update camera
  13594. this.activeCamera._updateFromScene();
  13595. // Reset some special arrays
  13596. this._renderTargets.reset();
  13597. if (this.afterCameraRender) {
  13598. this.afterCameraRender(this.activeCamera);
  13599. }
  13600. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13601. };
  13602. Scene.prototype._processSubCameras = function (camera) {
  13603. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13604. this._renderForCamera(camera);
  13605. return;
  13606. }
  13607. // rig cameras
  13608. for (var index = 0; index < camera._rigCameras.length; index++) {
  13609. this._renderForCamera(camera._rigCameras[index]);
  13610. }
  13611. this.activeCamera = camera;
  13612. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13613. // Update camera
  13614. this.activeCamera._updateFromScene();
  13615. };
  13616. Scene.prototype._checkIntersections = function () {
  13617. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13618. var sourceMesh = this._meshesForIntersections.data[index];
  13619. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13620. var action = sourceMesh.actionManager.actions[actionIndex];
  13621. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13622. var parameters = action.getTriggerParameter();
  13623. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13624. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13625. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13626. if (areIntersecting && currentIntersectionInProgress === -1) {
  13627. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13628. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13629. sourceMesh._intersectionsInProgress.push(otherMesh);
  13630. }
  13631. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13632. sourceMesh._intersectionsInProgress.push(otherMesh);
  13633. }
  13634. }
  13635. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13636. //They intersected, and now they don't.
  13637. //is this trigger an exit trigger? execute an event.
  13638. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13639. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13640. }
  13641. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13642. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13643. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13644. }
  13645. }
  13646. }
  13647. }
  13648. }
  13649. };
  13650. Scene.prototype.render = function () {
  13651. var startDate = BABYLON.Tools.Now;
  13652. this._particlesDuration = 0;
  13653. this._spritesDuration = 0;
  13654. this._activeParticles = 0;
  13655. this._renderDuration = 0;
  13656. this._renderTargetsDuration = 0;
  13657. this._evaluateActiveMeshesDuration = 0;
  13658. this._totalVertices = 0;
  13659. this._activeIndices = 0;
  13660. this._activeBones = 0;
  13661. this.getEngine().resetDrawCalls();
  13662. this._meshesForIntersections.reset();
  13663. this.resetCachedMaterial();
  13664. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13665. // Actions
  13666. if (this.actionManager) {
  13667. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13668. }
  13669. //Simplification Queue
  13670. if (!this.simplificationQueue.running) {
  13671. this.simplificationQueue.executeNext();
  13672. }
  13673. // Before render
  13674. if (this.beforeRender) {
  13675. this.beforeRender();
  13676. }
  13677. var callbackIndex;
  13678. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13679. this._onBeforeRenderCallbacks[callbackIndex]();
  13680. }
  13681. // Animations
  13682. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13683. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13684. this._animate();
  13685. // Physics
  13686. if (this._physicsEngine) {
  13687. BABYLON.Tools.StartPerformanceCounter("Physics");
  13688. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13689. BABYLON.Tools.EndPerformanceCounter("Physics");
  13690. }
  13691. // Customs render targets
  13692. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13693. var engine = this.getEngine();
  13694. var currentActiveCamera = this.activeCamera;
  13695. if (this.renderTargetsEnabled) {
  13696. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13697. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13698. var renderTarget = this.customRenderTargets[customIndex];
  13699. if (renderTarget._shouldRender()) {
  13700. this._renderId++;
  13701. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13702. if (!this.activeCamera)
  13703. throw new Error("Active camera not set");
  13704. // Viewport
  13705. engine.setViewport(this.activeCamera.viewport);
  13706. // Camera
  13707. this.updateTransformMatrix();
  13708. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13709. }
  13710. }
  13711. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13712. this._renderId++;
  13713. }
  13714. if (this.customRenderTargets.length > 0) {
  13715. engine.restoreDefaultFramebuffer();
  13716. }
  13717. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13718. this.activeCamera = currentActiveCamera;
  13719. // Procedural textures
  13720. if (this.proceduralTexturesEnabled) {
  13721. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13722. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13723. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13724. if (proceduralTexture._shouldRender()) {
  13725. proceduralTexture.render();
  13726. }
  13727. }
  13728. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13729. }
  13730. // Clear
  13731. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13732. // Shadows
  13733. if (this.shadowsEnabled) {
  13734. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13735. var light = this.lights[lightIndex];
  13736. var shadowGenerator = light.getShadowGenerator();
  13737. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13738. this._renderTargets.push(shadowGenerator.getShadowMap());
  13739. }
  13740. }
  13741. }
  13742. // Depth renderer
  13743. if (this._depthRenderer) {
  13744. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13745. }
  13746. // RenderPipeline
  13747. this.postProcessRenderPipelineManager.update();
  13748. // Multi-cameras?
  13749. if (this.activeCameras.length > 0) {
  13750. var currentRenderId = this._renderId;
  13751. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13752. this._renderId = currentRenderId;
  13753. this._processSubCameras(this.activeCameras[cameraIndex]);
  13754. }
  13755. }
  13756. else {
  13757. if (!this.activeCamera) {
  13758. throw new Error("No camera defined");
  13759. }
  13760. this._processSubCameras(this.activeCamera);
  13761. }
  13762. // Intersection checks
  13763. this._checkIntersections();
  13764. // Update the audio listener attached to the camera
  13765. this._updateAudioParameters();
  13766. // After render
  13767. if (this.afterRender) {
  13768. this.afterRender();
  13769. }
  13770. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13771. this._onAfterRenderCallbacks[callbackIndex]();
  13772. }
  13773. // Cleaning
  13774. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13775. this._toBeDisposed.data[index].dispose();
  13776. this._toBeDisposed[index] = null;
  13777. }
  13778. this._toBeDisposed.reset();
  13779. if (this.dumpNextRenderTargets) {
  13780. this.dumpNextRenderTargets = false;
  13781. }
  13782. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13783. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13784. };
  13785. Scene.prototype._updateAudioParameters = function () {
  13786. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13787. return;
  13788. }
  13789. var listeningCamera;
  13790. var audioEngine = BABYLON.Engine.audioEngine;
  13791. if (this.activeCameras.length > 0) {
  13792. listeningCamera = this.activeCameras[0];
  13793. }
  13794. else {
  13795. listeningCamera = this.activeCamera;
  13796. }
  13797. if (listeningCamera && audioEngine.canUseWebAudio) {
  13798. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13799. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13800. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13801. cameraDirection.normalize();
  13802. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13803. var i;
  13804. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13805. var sound = this.mainSoundTrack.soundCollection[i];
  13806. if (sound.useCustomAttenuation) {
  13807. sound.updateDistanceFromListener();
  13808. }
  13809. }
  13810. for (i = 0; i < this.soundTracks.length; i++) {
  13811. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13812. sound = this.soundTracks[i].soundCollection[j];
  13813. if (sound.useCustomAttenuation) {
  13814. sound.updateDistanceFromListener();
  13815. }
  13816. }
  13817. }
  13818. }
  13819. };
  13820. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13821. // Audio
  13822. get: function () {
  13823. return this._audioEnabled;
  13824. },
  13825. set: function (value) {
  13826. this._audioEnabled = value;
  13827. if (this._audioEnabled) {
  13828. this._enableAudio();
  13829. }
  13830. else {
  13831. this._disableAudio();
  13832. }
  13833. },
  13834. enumerable: true,
  13835. configurable: true
  13836. });
  13837. Scene.prototype._disableAudio = function () {
  13838. var i;
  13839. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13840. this.mainSoundTrack.soundCollection[i].pause();
  13841. }
  13842. for (i = 0; i < this.soundTracks.length; i++) {
  13843. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13844. this.soundTracks[i].soundCollection[j].pause();
  13845. }
  13846. }
  13847. };
  13848. Scene.prototype._enableAudio = function () {
  13849. var i;
  13850. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13851. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13852. this.mainSoundTrack.soundCollection[i].play();
  13853. }
  13854. }
  13855. for (i = 0; i < this.soundTracks.length; i++) {
  13856. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13857. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13858. this.soundTracks[i].soundCollection[j].play();
  13859. }
  13860. }
  13861. }
  13862. };
  13863. Object.defineProperty(Scene.prototype, "headphone", {
  13864. get: function () {
  13865. return this._headphone;
  13866. },
  13867. set: function (value) {
  13868. this._headphone = value;
  13869. if (this._headphone) {
  13870. this._switchAudioModeForHeadphones();
  13871. }
  13872. else {
  13873. this._switchAudioModeForNormalSpeakers();
  13874. }
  13875. },
  13876. enumerable: true,
  13877. configurable: true
  13878. });
  13879. Scene.prototype._switchAudioModeForHeadphones = function () {
  13880. this.mainSoundTrack.switchPanningModelToHRTF();
  13881. for (var i = 0; i < this.soundTracks.length; i++) {
  13882. this.soundTracks[i].switchPanningModelToHRTF();
  13883. }
  13884. };
  13885. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13886. this.mainSoundTrack.switchPanningModelToEqualPower();
  13887. for (var i = 0; i < this.soundTracks.length; i++) {
  13888. this.soundTracks[i].switchPanningModelToEqualPower();
  13889. }
  13890. };
  13891. Scene.prototype.enableDepthRenderer = function () {
  13892. if (this._depthRenderer) {
  13893. return this._depthRenderer;
  13894. }
  13895. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13896. return this._depthRenderer;
  13897. };
  13898. Scene.prototype.disableDepthRenderer = function () {
  13899. if (!this._depthRenderer) {
  13900. return;
  13901. }
  13902. this._depthRenderer.dispose();
  13903. this._depthRenderer = null;
  13904. };
  13905. Scene.prototype.dispose = function () {
  13906. this.beforeRender = null;
  13907. this.afterRender = null;
  13908. this.skeletons = [];
  13909. this._boundingBoxRenderer.dispose();
  13910. if (this._depthRenderer) {
  13911. this._depthRenderer.dispose();
  13912. }
  13913. // Debug layer
  13914. this.debugLayer.hide();
  13915. // Events
  13916. if (this.onDispose) {
  13917. this.onDispose();
  13918. }
  13919. this._onBeforeRenderCallbacks = [];
  13920. this._onAfterRenderCallbacks = [];
  13921. this.detachControl();
  13922. // Release sounds & sounds tracks
  13923. this.disposeSounds();
  13924. // Detach cameras
  13925. var canvas = this._engine.getRenderingCanvas();
  13926. var index;
  13927. for (index = 0; index < this.cameras.length; index++) {
  13928. this.cameras[index].detachControl(canvas);
  13929. }
  13930. // Release lights
  13931. while (this.lights.length) {
  13932. this.lights[0].dispose();
  13933. }
  13934. // Release meshes
  13935. while (this.meshes.length) {
  13936. this.meshes[0].dispose(true);
  13937. }
  13938. // Release cameras
  13939. while (this.cameras.length) {
  13940. this.cameras[0].dispose();
  13941. }
  13942. // Release materials
  13943. while (this.materials.length) {
  13944. this.materials[0].dispose();
  13945. }
  13946. // Release particles
  13947. while (this.particleSystems.length) {
  13948. this.particleSystems[0].dispose();
  13949. }
  13950. // Release sprites
  13951. while (this.spriteManagers.length) {
  13952. this.spriteManagers[0].dispose();
  13953. }
  13954. // Release layers
  13955. while (this.layers.length) {
  13956. this.layers[0].dispose();
  13957. }
  13958. // Release textures
  13959. while (this.textures.length) {
  13960. this.textures[0].dispose();
  13961. }
  13962. // Post-processes
  13963. this.postProcessManager.dispose();
  13964. // Physics
  13965. if (this._physicsEngine) {
  13966. this.disablePhysicsEngine();
  13967. }
  13968. // Remove from engine
  13969. index = this._engine.scenes.indexOf(this);
  13970. if (index > -1) {
  13971. this._engine.scenes.splice(index, 1);
  13972. }
  13973. this._engine.wipeCaches();
  13974. };
  13975. // Release sounds & sounds tracks
  13976. Scene.prototype.disposeSounds = function () {
  13977. this.mainSoundTrack.dispose();
  13978. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13979. this.soundTracks[scIndex].dispose();
  13980. }
  13981. };
  13982. // Octrees
  13983. Scene.prototype.getWorldExtends = function () {
  13984. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13985. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13986. for (var index = 0; index < this.meshes.length; index++) {
  13987. var mesh = this.meshes[index];
  13988. mesh.computeWorldMatrix(true);
  13989. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13990. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13991. BABYLON.Tools.CheckExtends(minBox, min, max);
  13992. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13993. }
  13994. return {
  13995. min: min,
  13996. max: max
  13997. };
  13998. };
  13999. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14000. if (maxCapacity === void 0) { maxCapacity = 64; }
  14001. if (maxDepth === void 0) { maxDepth = 2; }
  14002. if (!this._selectionOctree) {
  14003. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14004. }
  14005. var worldExtends = this.getWorldExtends();
  14006. // Update octree
  14007. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14008. return this._selectionOctree;
  14009. };
  14010. // Picking
  14011. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  14012. var engine = this._engine;
  14013. if (!camera) {
  14014. if (!this.activeCamera)
  14015. throw new Error("Active camera not set");
  14016. camera = this.activeCamera;
  14017. }
  14018. var cameraViewport = camera.viewport;
  14019. var viewport = cameraViewport.toGlobal(engine);
  14020. // Moving coordinates to local viewport world
  14021. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14022. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14023. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14024. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14025. };
  14026. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14027. var pickingInfo = null;
  14028. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14029. var mesh = this.meshes[meshIndex];
  14030. if (predicate) {
  14031. if (!predicate(mesh)) {
  14032. continue;
  14033. }
  14034. }
  14035. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14036. continue;
  14037. }
  14038. var world = mesh.getWorldMatrix();
  14039. var ray = rayFunction(world);
  14040. var result = mesh.intersects(ray, fastCheck);
  14041. if (!result || !result.hit)
  14042. continue;
  14043. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14044. continue;
  14045. pickingInfo = result;
  14046. if (fastCheck) {
  14047. break;
  14048. }
  14049. }
  14050. return pickingInfo || new BABYLON.PickingInfo();
  14051. };
  14052. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14053. var _this = this;
  14054. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14055. /// <param name="x">X position on screen</param>
  14056. /// <param name="y">Y position on screen</param>
  14057. /// <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>
  14058. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14059. /// <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>
  14060. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14061. };
  14062. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14063. var _this = this;
  14064. return this._internalPick(function (world) {
  14065. if (!_this._pickWithRayInverseMatrix) {
  14066. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14067. }
  14068. world.invertToRef(_this._pickWithRayInverseMatrix);
  14069. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14070. }, predicate, fastCheck);
  14071. };
  14072. Scene.prototype.setPointerOverMesh = function (mesh) {
  14073. if (this._pointerOverMesh === mesh) {
  14074. return;
  14075. }
  14076. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14077. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14078. }
  14079. this._pointerOverMesh = mesh;
  14080. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14081. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14082. }
  14083. };
  14084. Scene.prototype.getPointerOverMesh = function () {
  14085. return this._pointerOverMesh;
  14086. };
  14087. // Physics
  14088. Scene.prototype.getPhysicsEngine = function () {
  14089. return this._physicsEngine;
  14090. };
  14091. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14092. if (this._physicsEngine) {
  14093. return true;
  14094. }
  14095. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14096. if (!this._physicsEngine.isSupported()) {
  14097. this._physicsEngine = null;
  14098. return false;
  14099. }
  14100. this._physicsEngine._initialize(gravity);
  14101. return true;
  14102. };
  14103. Scene.prototype.disablePhysicsEngine = function () {
  14104. if (!this._physicsEngine) {
  14105. return;
  14106. }
  14107. this._physicsEngine.dispose();
  14108. this._physicsEngine = undefined;
  14109. };
  14110. Scene.prototype.isPhysicsEnabled = function () {
  14111. return this._physicsEngine !== undefined;
  14112. };
  14113. Scene.prototype.setGravity = function (gravity) {
  14114. if (!this._physicsEngine) {
  14115. return;
  14116. }
  14117. this._physicsEngine._setGravity(gravity);
  14118. };
  14119. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14120. if (parts.parts) {
  14121. options = parts;
  14122. parts = parts.parts;
  14123. }
  14124. if (!this._physicsEngine) {
  14125. return null;
  14126. }
  14127. for (var index = 0; index < parts.length; index++) {
  14128. var mesh = parts[index].mesh;
  14129. mesh._physicImpostor = parts[index].impostor;
  14130. mesh._physicsMass = options.mass / parts.length;
  14131. mesh._physicsFriction = options.friction;
  14132. mesh._physicRestitution = options.restitution;
  14133. }
  14134. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14135. };
  14136. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14137. for (var index = 0; index < compound.parts.length; index++) {
  14138. var mesh = compound.parts[index].mesh;
  14139. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14140. this._physicsEngine._unregisterMesh(mesh);
  14141. }
  14142. };
  14143. // Misc.
  14144. Scene.prototype.createDefaultCameraOrLight = function () {
  14145. // Light
  14146. if (this.lights.length === 0) {
  14147. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14148. }
  14149. // Camera
  14150. if (!this.activeCamera) {
  14151. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14152. // Compute position
  14153. var worldExtends = this.getWorldExtends();
  14154. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14155. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14156. camera.setTarget(worldCenter);
  14157. this.activeCamera = camera;
  14158. }
  14159. };
  14160. // Tags
  14161. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14162. if (tagsQuery === undefined) {
  14163. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14164. return list;
  14165. }
  14166. var listByTags = [];
  14167. forEach = forEach || (function (item) { return; });
  14168. for (var i in list) {
  14169. var item = list[i];
  14170. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14171. listByTags.push(item);
  14172. forEach(item);
  14173. }
  14174. }
  14175. return listByTags;
  14176. };
  14177. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14178. return this._getByTags(this.meshes, tagsQuery, forEach);
  14179. };
  14180. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14181. return this._getByTags(this.cameras, tagsQuery, forEach);
  14182. };
  14183. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14184. return this._getByTags(this.lights, tagsQuery, forEach);
  14185. };
  14186. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14187. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14188. };
  14189. // Statics
  14190. Scene._FOGMODE_NONE = 0;
  14191. Scene._FOGMODE_EXP = 1;
  14192. Scene._FOGMODE_EXP2 = 2;
  14193. Scene._FOGMODE_LINEAR = 3;
  14194. Scene.MinDeltaTime = 1.0;
  14195. Scene.MaxDeltaTime = 1000.0;
  14196. return Scene;
  14197. })();
  14198. BABYLON.Scene = Scene;
  14199. })(BABYLON || (BABYLON = {}));
  14200. var BABYLON;
  14201. (function (BABYLON) {
  14202. var VertexBuffer = (function () {
  14203. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14204. if (engine instanceof BABYLON.Mesh) {
  14205. this._engine = engine.getScene().getEngine();
  14206. }
  14207. else {
  14208. this._engine = engine;
  14209. }
  14210. this._updatable = updatable;
  14211. this._data = data;
  14212. if (!postponeInternalCreation) {
  14213. this.create();
  14214. }
  14215. this._kind = kind;
  14216. if (stride) {
  14217. this._strideSize = stride;
  14218. return;
  14219. }
  14220. // Deduce stride from kind
  14221. switch (kind) {
  14222. case VertexBuffer.PositionKind:
  14223. this._strideSize = 3;
  14224. break;
  14225. case VertexBuffer.NormalKind:
  14226. this._strideSize = 3;
  14227. break;
  14228. case VertexBuffer.UVKind:
  14229. case VertexBuffer.UV2Kind:
  14230. case VertexBuffer.UV3Kind:
  14231. case VertexBuffer.UV4Kind:
  14232. case VertexBuffer.UV5Kind:
  14233. case VertexBuffer.UV6Kind:
  14234. this._strideSize = 2;
  14235. break;
  14236. case VertexBuffer.ColorKind:
  14237. this._strideSize = 4;
  14238. break;
  14239. case VertexBuffer.MatricesIndicesKind:
  14240. this._strideSize = 4;
  14241. break;
  14242. case VertexBuffer.MatricesWeightsKind:
  14243. this._strideSize = 4;
  14244. break;
  14245. }
  14246. }
  14247. // Properties
  14248. VertexBuffer.prototype.isUpdatable = function () {
  14249. return this._updatable;
  14250. };
  14251. VertexBuffer.prototype.getData = function () {
  14252. return this._data;
  14253. };
  14254. VertexBuffer.prototype.getBuffer = function () {
  14255. return this._buffer;
  14256. };
  14257. VertexBuffer.prototype.getStrideSize = function () {
  14258. return this._strideSize;
  14259. };
  14260. // Methods
  14261. VertexBuffer.prototype.create = function (data) {
  14262. if (!data && this._buffer) {
  14263. return; // nothing to do
  14264. }
  14265. data = data || this._data;
  14266. if (!this._buffer) {
  14267. if (this._updatable) {
  14268. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14269. }
  14270. else {
  14271. this._buffer = this._engine.createVertexBuffer(data);
  14272. }
  14273. }
  14274. if (this._updatable) {
  14275. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14276. this._data = data;
  14277. }
  14278. };
  14279. VertexBuffer.prototype.update = function (data) {
  14280. this.create(data);
  14281. };
  14282. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14283. if (!this._buffer) {
  14284. return;
  14285. }
  14286. if (this._updatable) {
  14287. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14288. this._data = null;
  14289. }
  14290. };
  14291. VertexBuffer.prototype.dispose = function () {
  14292. if (!this._buffer) {
  14293. return;
  14294. }
  14295. if (this._engine._releaseBuffer(this._buffer)) {
  14296. this._buffer = null;
  14297. }
  14298. };
  14299. Object.defineProperty(VertexBuffer, "PositionKind", {
  14300. get: function () {
  14301. return VertexBuffer._PositionKind;
  14302. },
  14303. enumerable: true,
  14304. configurable: true
  14305. });
  14306. Object.defineProperty(VertexBuffer, "NormalKind", {
  14307. get: function () {
  14308. return VertexBuffer._NormalKind;
  14309. },
  14310. enumerable: true,
  14311. configurable: true
  14312. });
  14313. Object.defineProperty(VertexBuffer, "UVKind", {
  14314. get: function () {
  14315. return VertexBuffer._UVKind;
  14316. },
  14317. enumerable: true,
  14318. configurable: true
  14319. });
  14320. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14321. get: function () {
  14322. return VertexBuffer._UV2Kind;
  14323. },
  14324. enumerable: true,
  14325. configurable: true
  14326. });
  14327. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14328. get: function () {
  14329. return VertexBuffer._UV3Kind;
  14330. },
  14331. enumerable: true,
  14332. configurable: true
  14333. });
  14334. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14335. get: function () {
  14336. return VertexBuffer._UV4Kind;
  14337. },
  14338. enumerable: true,
  14339. configurable: true
  14340. });
  14341. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14342. get: function () {
  14343. return VertexBuffer._UV5Kind;
  14344. },
  14345. enumerable: true,
  14346. configurable: true
  14347. });
  14348. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14349. get: function () {
  14350. return VertexBuffer._UV6Kind;
  14351. },
  14352. enumerable: true,
  14353. configurable: true
  14354. });
  14355. Object.defineProperty(VertexBuffer, "ColorKind", {
  14356. get: function () {
  14357. return VertexBuffer._ColorKind;
  14358. },
  14359. enumerable: true,
  14360. configurable: true
  14361. });
  14362. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14363. get: function () {
  14364. return VertexBuffer._MatricesIndicesKind;
  14365. },
  14366. enumerable: true,
  14367. configurable: true
  14368. });
  14369. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14370. get: function () {
  14371. return VertexBuffer._MatricesWeightsKind;
  14372. },
  14373. enumerable: true,
  14374. configurable: true
  14375. });
  14376. // Enums
  14377. VertexBuffer._PositionKind = "position";
  14378. VertexBuffer._NormalKind = "normal";
  14379. VertexBuffer._UVKind = "uv";
  14380. VertexBuffer._UV2Kind = "uv2";
  14381. VertexBuffer._UV3Kind = "uv3";
  14382. VertexBuffer._UV4Kind = "uv4";
  14383. VertexBuffer._UV5Kind = "uv5";
  14384. VertexBuffer._UV6Kind = "uv6";
  14385. VertexBuffer._ColorKind = "color";
  14386. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14387. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14388. return VertexBuffer;
  14389. })();
  14390. BABYLON.VertexBuffer = VertexBuffer;
  14391. })(BABYLON || (BABYLON = {}));
  14392. var BABYLON;
  14393. (function (BABYLON) {
  14394. /**
  14395. * Creates an instance based on a source mesh.
  14396. */
  14397. var InstancedMesh = (function (_super) {
  14398. __extends(InstancedMesh, _super);
  14399. function InstancedMesh(name, source) {
  14400. _super.call(this, name, source.getScene());
  14401. source.instances.push(this);
  14402. this._sourceMesh = source;
  14403. this.position.copyFrom(source.position);
  14404. this.rotation.copyFrom(source.rotation);
  14405. this.scaling.copyFrom(source.scaling);
  14406. if (source.rotationQuaternion) {
  14407. this.rotationQuaternion = source.rotationQuaternion.clone();
  14408. }
  14409. this.infiniteDistance = source.infiniteDistance;
  14410. this.setPivotMatrix(source.getPivotMatrix());
  14411. this.refreshBoundingInfo();
  14412. this._syncSubMeshes();
  14413. }
  14414. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14415. // Methods
  14416. get: function () {
  14417. return this._sourceMesh.receiveShadows;
  14418. },
  14419. enumerable: true,
  14420. configurable: true
  14421. });
  14422. Object.defineProperty(InstancedMesh.prototype, "material", {
  14423. get: function () {
  14424. return this._sourceMesh.material;
  14425. },
  14426. enumerable: true,
  14427. configurable: true
  14428. });
  14429. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14430. get: function () {
  14431. return this._sourceMesh.visibility;
  14432. },
  14433. enumerable: true,
  14434. configurable: true
  14435. });
  14436. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14437. get: function () {
  14438. return this._sourceMesh.skeleton;
  14439. },
  14440. enumerable: true,
  14441. configurable: true
  14442. });
  14443. InstancedMesh.prototype.getTotalVertices = function () {
  14444. return this._sourceMesh.getTotalVertices();
  14445. };
  14446. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14447. get: function () {
  14448. return this._sourceMesh;
  14449. },
  14450. enumerable: true,
  14451. configurable: true
  14452. });
  14453. InstancedMesh.prototype.getVerticesData = function (kind) {
  14454. return this._sourceMesh.getVerticesData(kind);
  14455. };
  14456. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14457. return this._sourceMesh.isVerticesDataPresent(kind);
  14458. };
  14459. InstancedMesh.prototype.getIndices = function () {
  14460. return this._sourceMesh.getIndices();
  14461. };
  14462. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14463. get: function () {
  14464. return this._sourceMesh._positions;
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14470. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14471. if (data) {
  14472. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14473. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14474. }
  14475. this._updateBoundingInfo();
  14476. };
  14477. InstancedMesh.prototype._preActivate = function () {
  14478. if (this._currentLOD) {
  14479. this._currentLOD._preActivate();
  14480. }
  14481. };
  14482. InstancedMesh.prototype._activate = function (renderId) {
  14483. if (this._currentLOD) {
  14484. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14485. }
  14486. };
  14487. InstancedMesh.prototype.getLOD = function (camera) {
  14488. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14489. if (this._currentLOD === this.sourceMesh) {
  14490. return this;
  14491. }
  14492. return this._currentLOD;
  14493. };
  14494. InstancedMesh.prototype._syncSubMeshes = function () {
  14495. this.releaseSubMeshes();
  14496. if (this._sourceMesh.subMeshes) {
  14497. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14498. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14499. }
  14500. }
  14501. };
  14502. InstancedMesh.prototype._generatePointsArray = function () {
  14503. return this._sourceMesh._generatePointsArray();
  14504. };
  14505. // Clone
  14506. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14507. var result = this._sourceMesh.createInstance(name);
  14508. // Deep copy
  14509. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14510. // Bounding info
  14511. this.refreshBoundingInfo();
  14512. // Parent
  14513. if (newParent) {
  14514. result.parent = newParent;
  14515. }
  14516. if (!doNotCloneChildren) {
  14517. // Children
  14518. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14519. var mesh = this.getScene().meshes[index];
  14520. if (mesh.parent === this) {
  14521. mesh.clone(mesh.name, result);
  14522. }
  14523. }
  14524. }
  14525. result.computeWorldMatrix(true);
  14526. return result;
  14527. };
  14528. // Dispoe
  14529. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14530. // Remove from mesh
  14531. var index = this._sourceMesh.instances.indexOf(this);
  14532. this._sourceMesh.instances.splice(index, 1);
  14533. _super.prototype.dispose.call(this, doNotRecurse);
  14534. };
  14535. return InstancedMesh;
  14536. })(BABYLON.AbstractMesh);
  14537. BABYLON.InstancedMesh = InstancedMesh;
  14538. })(BABYLON || (BABYLON = {}));
  14539. var BABYLON;
  14540. (function (BABYLON) {
  14541. var _InstancesBatch = (function () {
  14542. function _InstancesBatch() {
  14543. this.mustReturn = false;
  14544. this.visibleInstances = new Array();
  14545. this.renderSelf = new Array();
  14546. }
  14547. return _InstancesBatch;
  14548. })();
  14549. BABYLON._InstancesBatch = _InstancesBatch;
  14550. var Mesh = (function (_super) {
  14551. __extends(Mesh, _super);
  14552. /**
  14553. * @constructor
  14554. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14555. * @param {Scene} scene - The scene to add this mesh to.
  14556. * @param {Node} parent - The parent of this mesh, if it has one
  14557. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14558. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14559. * When false, achieved by calling a clone(), also passing False.
  14560. * This will make creation of children, recursive.
  14561. */
  14562. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14563. if (parent === void 0) { parent = null; }
  14564. _super.call(this, name, scene);
  14565. // Members
  14566. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14567. this.instances = new Array();
  14568. this._LODLevels = new Array();
  14569. this._onBeforeRenderCallbacks = new Array();
  14570. this._onAfterRenderCallbacks = new Array();
  14571. this._visibleInstances = {};
  14572. this._renderIdForInstances = new Array();
  14573. this._batchCache = new _InstancesBatch();
  14574. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14575. this._sideOrientation = Mesh._DEFAULTSIDE;
  14576. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14577. if (source) {
  14578. // Geometry
  14579. if (source._geometry) {
  14580. source._geometry.applyToMesh(this);
  14581. }
  14582. // Deep copy
  14583. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14584. this.id = name + "." + source.id;
  14585. // Material
  14586. this.material = source.material;
  14587. if (!doNotCloneChildren) {
  14588. // Children
  14589. for (var index = 0; index < scene.meshes.length; index++) {
  14590. var mesh = scene.meshes[index];
  14591. if (mesh.parent === source) {
  14592. // doNotCloneChildren is always going to be False
  14593. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14594. }
  14595. }
  14596. }
  14597. // Particles
  14598. for (index = 0; index < scene.particleSystems.length; index++) {
  14599. var system = scene.particleSystems[index];
  14600. if (system.emitter === source) {
  14601. system.clone(system.name, this);
  14602. }
  14603. }
  14604. this.computeWorldMatrix(true);
  14605. }
  14606. // Parent
  14607. if (parent !== null) {
  14608. this.parent = parent;
  14609. }
  14610. }
  14611. Object.defineProperty(Mesh, "FRONTSIDE", {
  14612. get: function () {
  14613. return Mesh._FRONTSIDE;
  14614. },
  14615. enumerable: true,
  14616. configurable: true
  14617. });
  14618. Object.defineProperty(Mesh, "BACKSIDE", {
  14619. get: function () {
  14620. return Mesh._BACKSIDE;
  14621. },
  14622. enumerable: true,
  14623. configurable: true
  14624. });
  14625. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14626. get: function () {
  14627. return Mesh._DOUBLESIDE;
  14628. },
  14629. enumerable: true,
  14630. configurable: true
  14631. });
  14632. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14633. get: function () {
  14634. return Mesh._DEFAULTSIDE;
  14635. },
  14636. enumerable: true,
  14637. configurable: true
  14638. });
  14639. Object.defineProperty(Mesh, "NO_CAP", {
  14640. get: function () {
  14641. return Mesh._NO_CAP;
  14642. },
  14643. enumerable: true,
  14644. configurable: true
  14645. });
  14646. Object.defineProperty(Mesh, "CAP_START", {
  14647. get: function () {
  14648. return Mesh._CAP_START;
  14649. },
  14650. enumerable: true,
  14651. configurable: true
  14652. });
  14653. Object.defineProperty(Mesh, "CAP_END", {
  14654. get: function () {
  14655. return Mesh._CAP_END;
  14656. },
  14657. enumerable: true,
  14658. configurable: true
  14659. });
  14660. Object.defineProperty(Mesh, "CAP_ALL", {
  14661. get: function () {
  14662. return Mesh._CAP_ALL;
  14663. },
  14664. enumerable: true,
  14665. configurable: true
  14666. });
  14667. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14668. // Methods
  14669. get: function () {
  14670. return this._LODLevels.length > 0;
  14671. },
  14672. enumerable: true,
  14673. configurable: true
  14674. });
  14675. Mesh.prototype._sortLODLevels = function () {
  14676. this._LODLevels.sort(function (a, b) {
  14677. if (a.distance < b.distance) {
  14678. return 1;
  14679. }
  14680. if (a.distance > b.distance) {
  14681. return -1;
  14682. }
  14683. return 0;
  14684. });
  14685. };
  14686. /**
  14687. * Add a mesh as LOD level triggered at the given distance.
  14688. * @param {number} distance - the distance from the center of the object to show this level
  14689. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14690. * @return {BABYLON.Mesh} this mesh (for chaining)
  14691. */
  14692. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14693. if (mesh && mesh._masterMesh) {
  14694. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14695. return this;
  14696. }
  14697. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14698. this._LODLevels.push(level);
  14699. if (mesh) {
  14700. mesh._masterMesh = this;
  14701. }
  14702. this._sortLODLevels();
  14703. return this;
  14704. };
  14705. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14706. for (var index = 0; index < this._LODLevels.length; index++) {
  14707. var level = this._LODLevels[index];
  14708. if (level.distance === distance) {
  14709. return level.mesh;
  14710. }
  14711. }
  14712. return null;
  14713. };
  14714. /**
  14715. * Remove a mesh from the LOD array
  14716. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14717. * @return {BABYLON.Mesh} this mesh (for chaining)
  14718. */
  14719. Mesh.prototype.removeLODLevel = function (mesh) {
  14720. for (var index = 0; index < this._LODLevels.length; index++) {
  14721. if (this._LODLevels[index].mesh === mesh) {
  14722. this._LODLevels.splice(index, 1);
  14723. if (mesh) {
  14724. mesh._masterMesh = null;
  14725. }
  14726. }
  14727. }
  14728. this._sortLODLevels();
  14729. return this;
  14730. };
  14731. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14732. if (!this._LODLevels || this._LODLevels.length === 0) {
  14733. return this;
  14734. }
  14735. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14736. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14737. if (this.onLODLevelSelection) {
  14738. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14739. }
  14740. return this;
  14741. }
  14742. for (var index = 0; index < this._LODLevels.length; index++) {
  14743. var level = this._LODLevels[index];
  14744. if (level.distance < distanceToCamera) {
  14745. if (level.mesh) {
  14746. level.mesh._preActivate();
  14747. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14748. }
  14749. if (this.onLODLevelSelection) {
  14750. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14751. }
  14752. return level.mesh;
  14753. }
  14754. }
  14755. if (this.onLODLevelSelection) {
  14756. this.onLODLevelSelection(distanceToCamera, this, this);
  14757. }
  14758. return this;
  14759. };
  14760. Object.defineProperty(Mesh.prototype, "geometry", {
  14761. get: function () {
  14762. return this._geometry;
  14763. },
  14764. enumerable: true,
  14765. configurable: true
  14766. });
  14767. Mesh.prototype.getTotalVertices = function () {
  14768. if (!this._geometry) {
  14769. return 0;
  14770. }
  14771. return this._geometry.getTotalVertices();
  14772. };
  14773. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14774. if (!this._geometry) {
  14775. return null;
  14776. }
  14777. return this._geometry.getVerticesData(kind, copyWhenShared);
  14778. };
  14779. Mesh.prototype.getVertexBuffer = function (kind) {
  14780. if (!this._geometry) {
  14781. return undefined;
  14782. }
  14783. return this._geometry.getVertexBuffer(kind);
  14784. };
  14785. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14786. if (!this._geometry) {
  14787. if (this._delayInfo) {
  14788. return this._delayInfo.indexOf(kind) !== -1;
  14789. }
  14790. return false;
  14791. }
  14792. return this._geometry.isVerticesDataPresent(kind);
  14793. };
  14794. Mesh.prototype.getVerticesDataKinds = function () {
  14795. if (!this._geometry) {
  14796. var result = [];
  14797. if (this._delayInfo) {
  14798. for (var kind in this._delayInfo) {
  14799. result.push(kind);
  14800. }
  14801. }
  14802. return result;
  14803. }
  14804. return this._geometry.getVerticesDataKinds();
  14805. };
  14806. Mesh.prototype.getTotalIndices = function () {
  14807. if (!this._geometry) {
  14808. return 0;
  14809. }
  14810. return this._geometry.getTotalIndices();
  14811. };
  14812. Mesh.prototype.getIndices = function (copyWhenShared) {
  14813. if (!this._geometry) {
  14814. return [];
  14815. }
  14816. return this._geometry.getIndices(copyWhenShared);
  14817. };
  14818. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14819. get: function () {
  14820. return this._masterMesh !== null && this._masterMesh !== undefined;
  14821. },
  14822. enumerable: true,
  14823. configurable: true
  14824. });
  14825. Mesh.prototype.isReady = function () {
  14826. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14827. return false;
  14828. }
  14829. return _super.prototype.isReady.call(this);
  14830. };
  14831. Mesh.prototype.isDisposed = function () {
  14832. return this._isDisposed;
  14833. };
  14834. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14835. get: function () {
  14836. return this._sideOrientation;
  14837. },
  14838. set: function (sideO) {
  14839. this._sideOrientation = sideO;
  14840. },
  14841. enumerable: true,
  14842. configurable: true
  14843. });
  14844. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14845. get: function () {
  14846. return this._areNormalsFrozen;
  14847. },
  14848. enumerable: true,
  14849. configurable: true
  14850. });
  14851. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14852. Mesh.prototype.freezeNormals = function () {
  14853. this._areNormalsFrozen = true;
  14854. };
  14855. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14856. Mesh.prototype.unfreezeNormals = function () {
  14857. this._areNormalsFrozen = false;
  14858. };
  14859. // Methods
  14860. Mesh.prototype._preActivate = function () {
  14861. var sceneRenderId = this.getScene().getRenderId();
  14862. if (this._preActivateId === sceneRenderId) {
  14863. return;
  14864. }
  14865. this._preActivateId = sceneRenderId;
  14866. this._visibleInstances = null;
  14867. };
  14868. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14869. if (!this._visibleInstances) {
  14870. this._visibleInstances = {};
  14871. this._visibleInstances.defaultRenderId = renderId;
  14872. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14873. }
  14874. if (!this._visibleInstances[renderId]) {
  14875. this._visibleInstances[renderId] = new Array();
  14876. }
  14877. this._visibleInstances[renderId].push(instance);
  14878. };
  14879. Mesh.prototype.refreshBoundingInfo = function () {
  14880. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14881. if (data) {
  14882. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14883. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14884. }
  14885. if (this.subMeshes) {
  14886. for (var index = 0; index < this.subMeshes.length; index++) {
  14887. this.subMeshes[index].refreshBoundingInfo();
  14888. }
  14889. }
  14890. this._updateBoundingInfo();
  14891. };
  14892. Mesh.prototype._createGlobalSubMesh = function () {
  14893. var totalVertices = this.getTotalVertices();
  14894. if (!totalVertices || !this.getIndices()) {
  14895. return null;
  14896. }
  14897. this.releaseSubMeshes();
  14898. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14899. };
  14900. Mesh.prototype.subdivide = function (count) {
  14901. if (count < 1) {
  14902. return;
  14903. }
  14904. var totalIndices = this.getTotalIndices();
  14905. var subdivisionSize = (totalIndices / count) | 0;
  14906. var offset = 0;
  14907. // Ensure that subdivisionSize is a multiple of 3
  14908. while (subdivisionSize % 3 !== 0) {
  14909. subdivisionSize++;
  14910. }
  14911. this.releaseSubMeshes();
  14912. for (var index = 0; index < count; index++) {
  14913. if (offset >= totalIndices) {
  14914. break;
  14915. }
  14916. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14917. offset += subdivisionSize;
  14918. }
  14919. this.synchronizeInstances();
  14920. };
  14921. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14922. if (kind instanceof Array) {
  14923. var temp = data;
  14924. data = kind;
  14925. kind = temp;
  14926. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14927. }
  14928. if (!this._geometry) {
  14929. var vertexData = new BABYLON.VertexData();
  14930. vertexData.set(data, kind);
  14931. var scene = this.getScene();
  14932. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14933. }
  14934. else {
  14935. this._geometry.setVerticesData(kind, data, updatable, stride);
  14936. }
  14937. };
  14938. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14939. if (!this._geometry) {
  14940. return;
  14941. }
  14942. if (!makeItUnique) {
  14943. this._geometry.updateVerticesData(kind, data, updateExtends);
  14944. }
  14945. else {
  14946. this.makeGeometryUnique();
  14947. this.updateVerticesData(kind, data, updateExtends, false);
  14948. }
  14949. };
  14950. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14951. if (!this._geometry) {
  14952. return;
  14953. }
  14954. if (!makeItUnique) {
  14955. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14956. }
  14957. else {
  14958. this.makeGeometryUnique();
  14959. this.updateVerticesDataDirectly(kind, data, offset, false);
  14960. }
  14961. };
  14962. // Mesh positions update function :
  14963. // updates the mesh positions according to the positionFunction returned values.
  14964. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14965. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14966. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14967. if (computeNormals === void 0) { computeNormals = true; }
  14968. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14969. positionFunction(positions);
  14970. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14971. if (computeNormals) {
  14972. var indices = this.getIndices();
  14973. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14974. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14975. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14976. }
  14977. };
  14978. Mesh.prototype.makeGeometryUnique = function () {
  14979. if (!this._geometry) {
  14980. return;
  14981. }
  14982. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14983. geometry.applyToMesh(this);
  14984. };
  14985. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14986. if (!this._geometry) {
  14987. var vertexData = new BABYLON.VertexData();
  14988. vertexData.indices = indices;
  14989. var scene = this.getScene();
  14990. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14991. }
  14992. else {
  14993. this._geometry.setIndices(indices, totalVertices);
  14994. }
  14995. };
  14996. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14997. var engine = this.getScene().getEngine();
  14998. // Wireframe
  14999. var indexToBind;
  15000. switch (fillMode) {
  15001. case BABYLON.Material.PointFillMode:
  15002. indexToBind = null;
  15003. break;
  15004. case BABYLON.Material.WireFrameFillMode:
  15005. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15006. break;
  15007. default:
  15008. case BABYLON.Material.TriangleFillMode:
  15009. indexToBind = this._geometry.getIndexBuffer();
  15010. break;
  15011. }
  15012. // VBOs
  15013. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15014. };
  15015. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15016. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15017. return;
  15018. }
  15019. var engine = this.getScene().getEngine();
  15020. // Draw order
  15021. switch (fillMode) {
  15022. case BABYLON.Material.PointFillMode:
  15023. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15024. break;
  15025. case BABYLON.Material.WireFrameFillMode:
  15026. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15027. break;
  15028. default:
  15029. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15030. }
  15031. };
  15032. Mesh.prototype.registerBeforeRender = function (func) {
  15033. this._onBeforeRenderCallbacks.push(func);
  15034. };
  15035. Mesh.prototype.unregisterBeforeRender = function (func) {
  15036. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15037. if (index > -1) {
  15038. this._onBeforeRenderCallbacks.splice(index, 1);
  15039. }
  15040. };
  15041. Mesh.prototype.registerAfterRender = function (func) {
  15042. this._onAfterRenderCallbacks.push(func);
  15043. };
  15044. Mesh.prototype.unregisterAfterRender = function (func) {
  15045. var index = this._onAfterRenderCallbacks.indexOf(func);
  15046. if (index > -1) {
  15047. this._onAfterRenderCallbacks.splice(index, 1);
  15048. }
  15049. };
  15050. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15051. var scene = this.getScene();
  15052. this._batchCache.mustReturn = false;
  15053. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15054. this._batchCache.visibleInstances[subMeshId] = null;
  15055. if (this._visibleInstances) {
  15056. var currentRenderId = scene.getRenderId();
  15057. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15058. var selfRenderId = this._renderId;
  15059. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15060. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15061. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15062. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15063. }
  15064. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15065. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15066. this._batchCache.mustReturn = true;
  15067. return this._batchCache;
  15068. }
  15069. if (currentRenderId !== selfRenderId) {
  15070. this._batchCache.renderSelf[subMeshId] = false;
  15071. }
  15072. }
  15073. this._renderIdForInstances[subMeshId] = currentRenderId;
  15074. }
  15075. return this._batchCache;
  15076. };
  15077. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15078. var visibleInstances = batch.visibleInstances[subMesh._id];
  15079. var matricesCount = visibleInstances.length + 1;
  15080. var bufferSize = matricesCount * 16 * 4;
  15081. while (this._instancesBufferSize < bufferSize) {
  15082. this._instancesBufferSize *= 2;
  15083. }
  15084. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15085. if (this._worldMatricesInstancesBuffer) {
  15086. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15087. }
  15088. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15089. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15090. }
  15091. var offset = 0;
  15092. var instancesCount = 0;
  15093. var world = this.getWorldMatrix();
  15094. if (batch.renderSelf[subMesh._id]) {
  15095. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15096. offset += 16;
  15097. instancesCount++;
  15098. }
  15099. if (visibleInstances) {
  15100. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15101. var instance = visibleInstances[instanceIndex];
  15102. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15103. offset += 16;
  15104. instancesCount++;
  15105. }
  15106. }
  15107. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15108. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15109. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15110. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15111. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15112. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15113. this._draw(subMesh, fillMode, instancesCount);
  15114. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15115. };
  15116. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15117. var scene = this.getScene();
  15118. var engine = scene.getEngine();
  15119. if (hardwareInstancedRendering) {
  15120. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15121. }
  15122. else {
  15123. if (batch.renderSelf[subMesh._id]) {
  15124. // Draw
  15125. if (onBeforeDraw) {
  15126. onBeforeDraw(false, this.getWorldMatrix());
  15127. }
  15128. this._draw(subMesh, fillMode);
  15129. }
  15130. if (batch.visibleInstances[subMesh._id]) {
  15131. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15132. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15133. // World
  15134. var world = instance.getWorldMatrix();
  15135. if (onBeforeDraw) {
  15136. onBeforeDraw(true, world);
  15137. }
  15138. // Draw
  15139. this._draw(subMesh, fillMode);
  15140. }
  15141. }
  15142. }
  15143. };
  15144. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15145. var scene = this.getScene();
  15146. // Managing instances
  15147. var batch = this._getInstancesRenderList(subMesh._id);
  15148. if (batch.mustReturn) {
  15149. return;
  15150. }
  15151. // Checking geometry state
  15152. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15153. return;
  15154. }
  15155. var callbackIndex;
  15156. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15157. this._onBeforeRenderCallbacks[callbackIndex](this);
  15158. }
  15159. var engine = scene.getEngine();
  15160. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15161. // Material
  15162. var effectiveMaterial = subMesh.getMaterial();
  15163. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15164. return;
  15165. }
  15166. // Outline - step 1
  15167. var savedDepthWrite = engine.getDepthWrite();
  15168. if (this.renderOutline) {
  15169. engine.setDepthWrite(false);
  15170. scene.getOutlineRenderer().render(subMesh, batch);
  15171. engine.setDepthWrite(savedDepthWrite);
  15172. }
  15173. effectiveMaterial._preBind();
  15174. var effect = effectiveMaterial.getEffect();
  15175. // Bind
  15176. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15177. this._bind(subMesh, effect, fillMode);
  15178. var world = this.getWorldMatrix();
  15179. effectiveMaterial.bind(world, this);
  15180. // Alpha mode
  15181. if (enableAlphaMode) {
  15182. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15183. }
  15184. // Draw
  15185. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15186. if (isInstance) {
  15187. effectiveMaterial.bindOnlyWorldMatrix(world);
  15188. }
  15189. });
  15190. // Unbind
  15191. effectiveMaterial.unbind();
  15192. // Outline - step 2
  15193. if (this.renderOutline && savedDepthWrite) {
  15194. engine.setDepthWrite(true);
  15195. engine.setColorWrite(false);
  15196. scene.getOutlineRenderer().render(subMesh, batch);
  15197. engine.setColorWrite(true);
  15198. }
  15199. // Overlay
  15200. if (this.renderOverlay) {
  15201. var currentMode = engine.getAlphaMode();
  15202. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15203. scene.getOutlineRenderer().render(subMesh, batch, true);
  15204. engine.setAlphaMode(currentMode);
  15205. }
  15206. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15207. this._onAfterRenderCallbacks[callbackIndex](this);
  15208. }
  15209. };
  15210. Mesh.prototype.getEmittedParticleSystems = function () {
  15211. var results = new Array();
  15212. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15213. var particleSystem = this.getScene().particleSystems[index];
  15214. if (particleSystem.emitter === this) {
  15215. results.push(particleSystem);
  15216. }
  15217. }
  15218. return results;
  15219. };
  15220. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15221. var results = new Array();
  15222. var descendants = this.getDescendants();
  15223. descendants.push(this);
  15224. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15225. var particleSystem = this.getScene().particleSystems[index];
  15226. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15227. results.push(particleSystem);
  15228. }
  15229. }
  15230. return results;
  15231. };
  15232. Mesh.prototype.getChildren = function () {
  15233. var results = [];
  15234. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15235. var mesh = this.getScene().meshes[index];
  15236. if (mesh.parent === this) {
  15237. results.push(mesh);
  15238. }
  15239. }
  15240. return results;
  15241. };
  15242. Mesh.prototype._checkDelayState = function () {
  15243. var _this = this;
  15244. var that = this;
  15245. var scene = this.getScene();
  15246. if (this._geometry) {
  15247. this._geometry.load(scene);
  15248. }
  15249. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15250. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15251. scene._addPendingData(that);
  15252. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15253. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15254. if (data instanceof ArrayBuffer) {
  15255. _this._delayLoadingFunction(data, _this);
  15256. }
  15257. else {
  15258. _this._delayLoadingFunction(JSON.parse(data), _this);
  15259. }
  15260. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15261. scene._removePendingData(_this);
  15262. }, function () { }, scene.database, getBinaryData);
  15263. }
  15264. };
  15265. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15266. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15267. return false;
  15268. }
  15269. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15270. return false;
  15271. }
  15272. this._checkDelayState();
  15273. return true;
  15274. };
  15275. Mesh.prototype.setMaterialByID = function (id) {
  15276. var materials = this.getScene().materials;
  15277. var index;
  15278. for (index = 0; index < materials.length; index++) {
  15279. if (materials[index].id === id) {
  15280. this.material = materials[index];
  15281. return;
  15282. }
  15283. }
  15284. // Multi
  15285. var multiMaterials = this.getScene().multiMaterials;
  15286. for (index = 0; index < multiMaterials.length; index++) {
  15287. if (multiMaterials[index].id === id) {
  15288. this.material = multiMaterials[index];
  15289. return;
  15290. }
  15291. }
  15292. };
  15293. Mesh.prototype.getAnimatables = function () {
  15294. var results = [];
  15295. if (this.material) {
  15296. results.push(this.material);
  15297. }
  15298. if (this.skeleton) {
  15299. results.push(this.skeleton);
  15300. }
  15301. return results;
  15302. };
  15303. // Geometry
  15304. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15305. // Position
  15306. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15307. return;
  15308. }
  15309. this._resetPointsArrayCache();
  15310. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15311. var temp = [];
  15312. var index;
  15313. for (index = 0; index < data.length; index += 3) {
  15314. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15315. }
  15316. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15317. // Normals
  15318. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15319. return;
  15320. }
  15321. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15322. temp = [];
  15323. for (index = 0; index < data.length; index += 3) {
  15324. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15325. }
  15326. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15327. // flip faces?
  15328. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15329. this.flipFaces();
  15330. }
  15331. };
  15332. // Will apply current transform to mesh and reset world matrix
  15333. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15334. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15335. this.scaling.copyFromFloats(1, 1, 1);
  15336. this.position.copyFromFloats(0, 0, 0);
  15337. this.rotation.copyFromFloats(0, 0, 0);
  15338. //only if quaternion is already set
  15339. if (this.rotationQuaternion) {
  15340. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15341. }
  15342. this._worldMatrix = BABYLON.Matrix.Identity();
  15343. };
  15344. // Cache
  15345. Mesh.prototype._resetPointsArrayCache = function () {
  15346. this._positions = null;
  15347. };
  15348. Mesh.prototype._generatePointsArray = function () {
  15349. if (this._positions)
  15350. return true;
  15351. this._positions = [];
  15352. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15353. if (!data) {
  15354. return false;
  15355. }
  15356. for (var index = 0; index < data.length; index += 3) {
  15357. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15358. }
  15359. return true;
  15360. };
  15361. // Clone
  15362. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15363. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15364. };
  15365. // Dispose
  15366. Mesh.prototype.dispose = function (doNotRecurse) {
  15367. if (this._geometry) {
  15368. this._geometry.releaseForMesh(this, true);
  15369. }
  15370. // Instances
  15371. if (this._worldMatricesInstancesBuffer) {
  15372. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15373. this._worldMatricesInstancesBuffer = null;
  15374. }
  15375. while (this.instances.length) {
  15376. this.instances[0].dispose();
  15377. }
  15378. _super.prototype.dispose.call(this, doNotRecurse);
  15379. };
  15380. // Geometric tools
  15381. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15382. var _this = this;
  15383. var scene = this.getScene();
  15384. var onload = function (img) {
  15385. // Getting height map data
  15386. var canvas = document.createElement("canvas");
  15387. var context = canvas.getContext("2d");
  15388. var heightMapWidth = img.width;
  15389. var heightMapHeight = img.height;
  15390. canvas.width = heightMapWidth;
  15391. canvas.height = heightMapHeight;
  15392. context.drawImage(img, 0, 0);
  15393. // Create VertexData from map data
  15394. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15395. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15396. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15397. //execute success callback, if set
  15398. if (onSuccess) {
  15399. onSuccess(_this);
  15400. }
  15401. };
  15402. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15403. };
  15404. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15405. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15406. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15407. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15408. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15409. return;
  15410. }
  15411. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15412. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15413. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15414. var position = BABYLON.Vector3.Zero();
  15415. var normal = BABYLON.Vector3.Zero();
  15416. var uv = BABYLON.Vector2.Zero();
  15417. for (var index = 0; index < positions.length; index += 3) {
  15418. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15419. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15420. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15421. // Compute height
  15422. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15423. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15424. var pos = (u + v * heightMapWidth) * 4;
  15425. var r = buffer[pos] / 255.0;
  15426. var g = buffer[pos + 1] / 255.0;
  15427. var b = buffer[pos + 2] / 255.0;
  15428. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15429. normal.normalize();
  15430. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15431. position = position.add(normal);
  15432. position.toArray(positions, index);
  15433. }
  15434. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15435. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15436. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15437. };
  15438. Mesh.prototype.convertToFlatShadedMesh = function () {
  15439. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15440. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15441. var kinds = this.getVerticesDataKinds();
  15442. var vbs = [];
  15443. var data = [];
  15444. var newdata = [];
  15445. var updatableNormals = false;
  15446. var kindIndex;
  15447. var kind;
  15448. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15449. kind = kinds[kindIndex];
  15450. var vertexBuffer = this.getVertexBuffer(kind);
  15451. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15452. updatableNormals = vertexBuffer.isUpdatable();
  15453. kinds.splice(kindIndex, 1);
  15454. kindIndex--;
  15455. continue;
  15456. }
  15457. vbs[kind] = vertexBuffer;
  15458. data[kind] = vbs[kind].getData();
  15459. newdata[kind] = [];
  15460. }
  15461. // Save previous submeshes
  15462. var previousSubmeshes = this.subMeshes.slice(0);
  15463. var indices = this.getIndices();
  15464. var totalIndices = this.getTotalIndices();
  15465. // Generating unique vertices per face
  15466. var index;
  15467. for (index = 0; index < totalIndices; index++) {
  15468. var vertexIndex = indices[index];
  15469. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15470. kind = kinds[kindIndex];
  15471. var stride = vbs[kind].getStrideSize();
  15472. for (var offset = 0; offset < stride; offset++) {
  15473. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15474. }
  15475. }
  15476. }
  15477. // Updating faces & normal
  15478. var normals = [];
  15479. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15480. for (index = 0; index < totalIndices; index += 3) {
  15481. indices[index] = index;
  15482. indices[index + 1] = index + 1;
  15483. indices[index + 2] = index + 2;
  15484. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15485. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15486. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15487. var p1p2 = p1.subtract(p2);
  15488. var p3p2 = p3.subtract(p2);
  15489. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15490. // Store same normals for every vertex
  15491. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15492. normals.push(normal.x);
  15493. normals.push(normal.y);
  15494. normals.push(normal.z);
  15495. }
  15496. }
  15497. this.setIndices(indices);
  15498. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15499. // Updating vertex buffers
  15500. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15501. kind = kinds[kindIndex];
  15502. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15503. }
  15504. // Updating submeshes
  15505. this.releaseSubMeshes();
  15506. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15507. var previousOne = previousSubmeshes[submeshIndex];
  15508. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15509. }
  15510. this.synchronizeInstances();
  15511. };
  15512. // will inverse faces orientations, and invert normals too if specified
  15513. Mesh.prototype.flipFaces = function (flipNormals) {
  15514. if (flipNormals === void 0) { flipNormals = false; }
  15515. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15516. var i;
  15517. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15518. for (i = 0; i < vertex_data.normals.length; i++) {
  15519. vertex_data.normals[i] *= -1;
  15520. }
  15521. }
  15522. var temp;
  15523. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15524. // reassign indices
  15525. temp = vertex_data.indices[i + 1];
  15526. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15527. vertex_data.indices[i + 2] = temp;
  15528. }
  15529. vertex_data.applyToMesh(this);
  15530. };
  15531. // Instances
  15532. Mesh.prototype.createInstance = function (name) {
  15533. return new BABYLON.InstancedMesh(name, this);
  15534. };
  15535. Mesh.prototype.synchronizeInstances = function () {
  15536. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15537. var instance = this.instances[instanceIndex];
  15538. instance._syncSubMeshes();
  15539. }
  15540. };
  15541. /**
  15542. * Simplify the mesh according to the given array of settings.
  15543. * Function will return immediately and will simplify async.
  15544. * @param settings a collection of simplification settings.
  15545. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15546. * @param type the type of simplification to run.
  15547. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15548. */
  15549. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15550. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15551. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15552. this.getScene().simplificationQueue.addTask({
  15553. settings: settings,
  15554. parallelProcessing: parallelProcessing,
  15555. mesh: this,
  15556. simplificationType: simplificationType,
  15557. successCallback: successCallback
  15558. });
  15559. };
  15560. /**
  15561. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15562. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15563. * This should be used together with the simplification to avoid disappearing triangles.
  15564. * @param successCallback an optional success callback to be called after the optimization finished.
  15565. */
  15566. Mesh.prototype.optimizeIndices = function (successCallback) {
  15567. var _this = this;
  15568. var indices = this.getIndices();
  15569. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15570. var vectorPositions = [];
  15571. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15572. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15573. }
  15574. var dupes = [];
  15575. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15576. var realPos = vectorPositions.length - 1 - iteration;
  15577. var testedPosition = vectorPositions[realPos];
  15578. for (var j = 0; j < realPos; ++j) {
  15579. var againstPosition = vectorPositions[j];
  15580. if (testedPosition.equals(againstPosition)) {
  15581. dupes[realPos] = j;
  15582. break;
  15583. }
  15584. }
  15585. }, function () {
  15586. for (var i = 0; i < indices.length; ++i) {
  15587. indices[i] = dupes[indices[i]] || indices[i];
  15588. }
  15589. //indices are now reordered
  15590. var originalSubMeshes = _this.subMeshes.slice(0);
  15591. _this.setIndices(indices);
  15592. _this.subMeshes = originalSubMeshes;
  15593. if (successCallback) {
  15594. successCallback(_this);
  15595. }
  15596. });
  15597. };
  15598. // Statics
  15599. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15600. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15601. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15602. if (ribbonInstance) {
  15603. // positionFunction : ribbon case
  15604. // only pathArray and sideOrientation parameters are taken into account for positions update
  15605. var positionFunction = function (positions) {
  15606. var minlg = pathArray[0].length;
  15607. var i = 0;
  15608. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15609. for (var si = 1; si <= ns; si++) {
  15610. for (var p = 0; p < pathArray.length; p++) {
  15611. var path = pathArray[p];
  15612. var l = path.length;
  15613. minlg = (minlg < l) ? minlg : l;
  15614. var j = 0;
  15615. while (j < minlg) {
  15616. positions[i] = path[j].x;
  15617. positions[i + 1] = path[j].y;
  15618. positions[i + 2] = path[j].z;
  15619. j++;
  15620. i += 3;
  15621. }
  15622. if (ribbonInstance._closePath) {
  15623. positions[i] = path[0].x;
  15624. positions[i + 1] = path[0].y;
  15625. positions[i + 2] = path[0].z;
  15626. i += 3;
  15627. }
  15628. }
  15629. }
  15630. };
  15631. var positions = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15632. positionFunction(positions);
  15633. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15634. if (!(ribbonInstance.areNormalsFrozen)) {
  15635. var indices = ribbonInstance.getIndices();
  15636. var normals = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15637. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15638. if (ribbonInstance._closePath) {
  15639. var indexFirst = 0;
  15640. var indexLast = 0;
  15641. for (var p = 0; p < pathArray.length; p++) {
  15642. indexFirst = ribbonInstance._idx[p] * 3;
  15643. if (p + 1 < pathArray.length) {
  15644. indexLast = (ribbonInstance._idx[p + 1] - 1) * 3;
  15645. }
  15646. else {
  15647. indexLast = normals.length - 3;
  15648. }
  15649. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15650. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15651. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15652. normals[indexLast] = normals[indexFirst];
  15653. normals[indexLast + 1] = normals[indexFirst + 1];
  15654. normals[indexLast + 2] = normals[indexFirst + 2];
  15655. }
  15656. }
  15657. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15658. }
  15659. return ribbonInstance;
  15660. }
  15661. else {
  15662. var ribbon = new Mesh(name, scene);
  15663. ribbon.sideOrientation = sideOrientation;
  15664. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15665. if (closePath) {
  15666. ribbon._idx = vertexData._idx;
  15667. }
  15668. ribbon._closePath = closePath;
  15669. vertexData.applyToMesh(ribbon, updatable);
  15670. return ribbon;
  15671. }
  15672. };
  15673. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15674. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15675. var disc = new Mesh(name, scene);
  15676. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15677. vertexData.applyToMesh(disc, updatable);
  15678. return disc;
  15679. };
  15680. Mesh.CreateBox = function (name, options, scene, updatable, sideOrientation) {
  15681. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15682. // Check parameters
  15683. updatable = updatable || options.updatable;
  15684. var box = new Mesh(name, scene);
  15685. var vertexData = BABYLON.VertexData.CreateBox(options, sideOrientation);
  15686. vertexData.applyToMesh(box, updatable);
  15687. return box;
  15688. };
  15689. Mesh.CreateSphere = function (name, options, diameterOrScene, scene, updatable, sideOrientation) {
  15690. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15691. if (diameterOrScene instanceof BABYLON.Scene) {
  15692. scene = diameterOrScene;
  15693. updatable = options.updatable;
  15694. }
  15695. else {
  15696. var segments = options;
  15697. options = {
  15698. segments: segments,
  15699. diameterX: diameterOrScene,
  15700. diameterY: diameterOrScene,
  15701. diameterZ: diameterOrScene,
  15702. sideOrientation: sideOrientation
  15703. };
  15704. }
  15705. var sphere = new Mesh(name, scene);
  15706. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15707. vertexData.applyToMesh(sphere, updatable);
  15708. return sphere;
  15709. };
  15710. // Cylinder and cone
  15711. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15712. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15713. // subdivisions is a new parameter, we need to support old signature
  15714. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15715. if (scene !== undefined) {
  15716. updatable = scene;
  15717. }
  15718. scene = subdivisions;
  15719. subdivisions = 1;
  15720. }
  15721. var cylinder = new Mesh(name, scene);
  15722. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation);
  15723. vertexData.applyToMesh(cylinder, updatable);
  15724. return cylinder;
  15725. };
  15726. // Torus (Code from SharpDX.org)
  15727. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15728. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15729. var torus = new Mesh(name, scene);
  15730. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15731. vertexData.applyToMesh(torus, updatable);
  15732. return torus;
  15733. };
  15734. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15735. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15736. var torusKnot = new Mesh(name, scene);
  15737. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15738. vertexData.applyToMesh(torusKnot, updatable);
  15739. return torusKnot;
  15740. };
  15741. // Lines
  15742. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15743. if (linesInstance === void 0) { linesInstance = null; }
  15744. if (linesInstance) {
  15745. var positionFunction = function (positions) {
  15746. var i = 0;
  15747. for (var p = 0; p < points.length; p++) {
  15748. positions[i] = points[p].x;
  15749. positions[i + 1] = points[p].y;
  15750. positions[i + 2] = points[p].z;
  15751. i += 3;
  15752. }
  15753. };
  15754. linesInstance.updateMeshPositions(positionFunction, false);
  15755. return linesInstance;
  15756. }
  15757. // lines creation
  15758. var lines = new BABYLON.LinesMesh(name, scene);
  15759. var vertexData = BABYLON.VertexData.CreateLines(points);
  15760. vertexData.applyToMesh(lines, updatable);
  15761. return lines;
  15762. };
  15763. // Dashed Lines
  15764. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15765. if (linesInstance === void 0) { linesInstance = null; }
  15766. if (linesInstance) {
  15767. var positionFunction = function (positions) {
  15768. var curvect = BABYLON.Vector3.Zero();
  15769. var nbSeg = positions.length / 6;
  15770. var lg = 0;
  15771. var nb = 0;
  15772. var shft = 0;
  15773. var dashshft = 0;
  15774. var curshft = 0;
  15775. var p = 0;
  15776. var i = 0;
  15777. var j = 0;
  15778. for (i = 0; i < points.length - 1; i++) {
  15779. points[i + 1].subtractToRef(points[i], curvect);
  15780. lg += curvect.length();
  15781. }
  15782. shft = lg / nbSeg;
  15783. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15784. for (i = 0; i < points.length - 1; i++) {
  15785. points[i + 1].subtractToRef(points[i], curvect);
  15786. nb = Math.floor(curvect.length() / shft);
  15787. curvect.normalize();
  15788. j = 0;
  15789. while (j < nb && p < positions.length) {
  15790. curshft = shft * j;
  15791. positions[p] = points[i].x + curshft * curvect.x;
  15792. positions[p + 1] = points[i].y + curshft * curvect.y;
  15793. positions[p + 2] = points[i].z + curshft * curvect.z;
  15794. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15795. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15796. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15797. p += 6;
  15798. j++;
  15799. }
  15800. }
  15801. while (p < positions.length) {
  15802. positions[p] = points[i].x;
  15803. positions[p + 1] = points[i].y;
  15804. positions[p + 2] = points[i].z;
  15805. p += 3;
  15806. }
  15807. };
  15808. linesInstance.updateMeshPositions(positionFunction, false);
  15809. return linesInstance;
  15810. }
  15811. // dashed lines creation
  15812. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15813. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15814. vertexData.applyToMesh(dashedLines, updatable);
  15815. dashedLines.dashSize = dashSize;
  15816. dashedLines.gapSize = gapSize;
  15817. return dashedLines;
  15818. };
  15819. // Extrusion
  15820. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15821. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15822. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15823. scale = scale || 1;
  15824. rotation = rotation || 0;
  15825. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15826. return extruded;
  15827. };
  15828. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15829. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15830. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15831. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15832. return extrudedCustom;
  15833. };
  15834. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15835. // extrusion geometry
  15836. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15837. var tangents = path3D.getTangents();
  15838. var normals = path3D.getNormals();
  15839. var binormals = path3D.getBinormals();
  15840. var distances = path3D.getDistances();
  15841. var angle = 0;
  15842. var returnScale = function (i, distance) { return scale; };
  15843. var returnRotation = function (i, distance) { return rotation; };
  15844. var rotate = custom ? rotateFunction : returnRotation;
  15845. var scl = custom ? scaleFunction : returnScale;
  15846. var index = 0;
  15847. for (var i = 0; i < curve.length; i++) {
  15848. var shapePath = new Array();
  15849. var angleStep = rotate(i, distances[i]);
  15850. var scaleRatio = scl(i, distances[i]);
  15851. for (var p = 0; p < shape.length; p++) {
  15852. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15853. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15854. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15855. shapePath.push(rotated);
  15856. }
  15857. shapePaths[index] = shapePath;
  15858. angle += angleStep;
  15859. index++;
  15860. }
  15861. // cap
  15862. var capPath = function (shapePath) {
  15863. var pointCap = Array();
  15864. var barycenter = BABYLON.Vector3.Zero();
  15865. var i;
  15866. for (i = 0; i < shapePath.length; i++) {
  15867. barycenter.addInPlace(shapePath[i]);
  15868. }
  15869. barycenter.scaleInPlace(1 / shapePath.length);
  15870. for (i = 0; i < shapePath.length; i++) {
  15871. pointCap.push(barycenter);
  15872. }
  15873. return pointCap;
  15874. };
  15875. switch (cap) {
  15876. case Mesh.NO_CAP:
  15877. break;
  15878. case Mesh.CAP_START:
  15879. shapePaths.unshift(capPath(shapePaths[0]));
  15880. break;
  15881. case Mesh.CAP_END:
  15882. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15883. break;
  15884. case Mesh.CAP_ALL:
  15885. shapePaths.unshift(capPath(shapePaths[0]));
  15886. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15887. break;
  15888. default:
  15889. break;
  15890. }
  15891. return shapePaths;
  15892. };
  15893. var path3D;
  15894. var pathArray;
  15895. if (instance) {
  15896. path3D = (instance.path3D).update(curve);
  15897. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15898. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15899. return instance;
  15900. }
  15901. // extruded shape creation
  15902. path3D = new BABYLON.Path3D(curve);
  15903. var newShapePaths = new Array();
  15904. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15905. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15906. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15907. extrudedGeneric.pathArray = pathArray;
  15908. extrudedGeneric.path3D = path3D;
  15909. extrudedGeneric.cap = cap;
  15910. return extrudedGeneric;
  15911. };
  15912. // Lathe
  15913. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15914. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15915. radius = radius || 1;
  15916. tessellation = tessellation || radius * 60;
  15917. var pi2 = Math.PI * 2;
  15918. var shapeLathe = new Array();
  15919. // first rotatable point
  15920. var i = 0;
  15921. while (shape[i].x === 0) {
  15922. i++;
  15923. }
  15924. var pt = shape[i];
  15925. for (i = 0; i < shape.length; i++) {
  15926. shapeLathe.push(shape[i].subtract(pt));
  15927. }
  15928. // circle path
  15929. var step = pi2 / tessellation;
  15930. var rotated;
  15931. var path = new Array();
  15932. ;
  15933. for (i = 0; i < tessellation; i++) {
  15934. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15935. path.push(rotated);
  15936. }
  15937. path.push(path[0]);
  15938. // extrusion
  15939. var scaleFunction = function () { return 1; };
  15940. var rotateFunction = function () { return 0; };
  15941. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15942. return lathe;
  15943. };
  15944. Mesh.CreatePlane = function (name, options, scene, updatable, sideOrientation) {
  15945. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15946. var plane = new Mesh(name, scene);
  15947. var vertexData = BABYLON.VertexData.CreatePlane(options, sideOrientation);
  15948. vertexData.applyToMesh(plane, updatable || options.updatable);
  15949. return plane;
  15950. };
  15951. Mesh.CreateGround = function (name, options, heightOrScene, subdivisions, scene, updatable) {
  15952. if (heightOrScene instanceof BABYLON.Scene) {
  15953. scene = heightOrScene;
  15954. updatable = options.updatable;
  15955. }
  15956. else {
  15957. var width = options;
  15958. options = {
  15959. width: width,
  15960. height: heightOrScene,
  15961. subdivisions: subdivisions
  15962. };
  15963. }
  15964. var ground = new BABYLON.GroundMesh(name, scene);
  15965. ground._setReady(false);
  15966. ground._subdivisions = options.subdivisions || 1;
  15967. var vertexData = BABYLON.VertexData.CreateGround(options);
  15968. vertexData.applyToMesh(ground, updatable || options.updatable);
  15969. ground._setReady(true);
  15970. return ground;
  15971. };
  15972. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15973. var tiledGround = new Mesh(name, scene);
  15974. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15975. vertexData.applyToMesh(tiledGround, updatable);
  15976. return tiledGround;
  15977. };
  15978. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15979. var ground = new BABYLON.GroundMesh(name, scene);
  15980. ground._subdivisions = subdivisions;
  15981. ground._setReady(false);
  15982. var onload = function (img) {
  15983. // Getting height map data
  15984. var canvas = document.createElement("canvas");
  15985. var context = canvas.getContext("2d");
  15986. var heightMapWidth = img.width;
  15987. var heightMapHeight = img.height;
  15988. canvas.width = heightMapWidth;
  15989. canvas.height = heightMapHeight;
  15990. context.drawImage(img, 0, 0);
  15991. // Create VertexData from map data
  15992. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15993. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15994. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15995. vertexData.applyToMesh(ground, updatable);
  15996. ground._setReady(true);
  15997. //execute ready callback, if set
  15998. if (onReady) {
  15999. onReady(ground);
  16000. }
  16001. };
  16002. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16003. return ground;
  16004. };
  16005. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  16006. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16007. if (tubeInstance === void 0) { tubeInstance = null; }
  16008. // tube geometry
  16009. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  16010. var tangents = path3D.getTangents();
  16011. var normals = path3D.getNormals();
  16012. var distances = path3D.getDistances();
  16013. var pi2 = Math.PI * 2;
  16014. var step = pi2 / tessellation;
  16015. var returnRadius = function (i, distance) { return radius; };
  16016. var radiusFunctionFinal = radiusFunction || returnRadius;
  16017. var circlePath;
  16018. var rad;
  16019. var normal;
  16020. var rotated;
  16021. var rotationMatrix;
  16022. var index = 0;
  16023. for (var i = 0; i < path.length; i++) {
  16024. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16025. circlePath = Array(); // current circle array
  16026. normal = normals[i]; // current normal
  16027. for (var t = 0; t < tessellation; t++) {
  16028. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  16029. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16030. circlePath.push(rotated);
  16031. }
  16032. circlePaths[index] = circlePath;
  16033. index++;
  16034. }
  16035. // cap
  16036. var capPath = function (nbPoints, pathIndex) {
  16037. var pointCap = Array();
  16038. for (var i = 0; i < nbPoints; i++) {
  16039. pointCap.push(path[pathIndex]);
  16040. }
  16041. return pointCap;
  16042. };
  16043. switch (cap) {
  16044. case Mesh.NO_CAP:
  16045. break;
  16046. case Mesh.CAP_START:
  16047. circlePaths.unshift(capPath(tessellation + 1, 0));
  16048. break;
  16049. case Mesh.CAP_END:
  16050. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  16051. break;
  16052. case Mesh.CAP_ALL:
  16053. circlePaths.unshift(capPath(tessellation + 1, 0));
  16054. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  16055. break;
  16056. default:
  16057. break;
  16058. }
  16059. return circlePaths;
  16060. };
  16061. var path3D;
  16062. var pathArray;
  16063. if (tubeInstance) {
  16064. path3D = (tubeInstance.path3D).update(path);
  16065. pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  16066. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  16067. return tubeInstance;
  16068. }
  16069. // tube creation
  16070. path3D = new BABYLON.Path3D(path);
  16071. var newPathArray = new Array();
  16072. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16073. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  16074. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  16075. tube.pathArray = pathArray;
  16076. tube.path3D = path3D;
  16077. tube.tessellation = tessellation;
  16078. tube.cap = cap;
  16079. return tube;
  16080. };
  16081. // Decals
  16082. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16083. if (angle === void 0) { angle = 0; }
  16084. var indices = sourceMesh.getIndices();
  16085. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16086. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16087. // Getting correct rotation
  16088. if (!normal) {
  16089. var target = new BABYLON.Vector3(0, 0, 1);
  16090. var camera = sourceMesh.getScene().activeCamera;
  16091. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16092. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16093. }
  16094. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16095. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16096. var pitch = Math.atan2(normal.y, len);
  16097. // Matrix
  16098. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16099. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16100. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16101. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16102. var vertexData = new BABYLON.VertexData();
  16103. vertexData.indices = [];
  16104. vertexData.positions = [];
  16105. vertexData.normals = [];
  16106. vertexData.uvs = [];
  16107. var currentVertexDataIndex = 0;
  16108. var extractDecalVector3 = function (indexId) {
  16109. var vertexId = indices[indexId];
  16110. var result = new BABYLON.PositionNormalVertex();
  16111. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16112. // Send vector to decal local world
  16113. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16114. // Get normal
  16115. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16116. return result;
  16117. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16118. var clip = function (vertices, axis) {
  16119. if (vertices.length === 0) {
  16120. return vertices;
  16121. }
  16122. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16123. var clipVertices = function (v0, v1) {
  16124. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16125. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16126. };
  16127. var result = new Array();
  16128. for (var index = 0; index < vertices.length; index += 3) {
  16129. var v1Out;
  16130. var v2Out;
  16131. var v3Out;
  16132. var total = 0;
  16133. var nV1, nV2, nV3, nV4;
  16134. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16135. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16136. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16137. v1Out = d1 > 0;
  16138. v2Out = d2 > 0;
  16139. v3Out = d3 > 0;
  16140. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16141. switch (total) {
  16142. case 0:
  16143. result.push(vertices[index]);
  16144. result.push(vertices[index + 1]);
  16145. result.push(vertices[index + 2]);
  16146. break;
  16147. case 1:
  16148. if (v1Out) {
  16149. nV1 = vertices[index + 1];
  16150. nV2 = vertices[index + 2];
  16151. nV3 = clipVertices(vertices[index], nV1);
  16152. nV4 = clipVertices(vertices[index], nV2);
  16153. }
  16154. if (v2Out) {
  16155. nV1 = vertices[index];
  16156. nV2 = vertices[index + 2];
  16157. nV3 = clipVertices(vertices[index + 1], nV1);
  16158. nV4 = clipVertices(vertices[index + 1], nV2);
  16159. result.push(nV3);
  16160. result.push(nV2.clone());
  16161. result.push(nV1.clone());
  16162. result.push(nV2.clone());
  16163. result.push(nV3.clone());
  16164. result.push(nV4);
  16165. break;
  16166. }
  16167. if (v3Out) {
  16168. nV1 = vertices[index];
  16169. nV2 = vertices[index + 1];
  16170. nV3 = clipVertices(vertices[index + 2], nV1);
  16171. nV4 = clipVertices(vertices[index + 2], nV2);
  16172. }
  16173. result.push(nV1.clone());
  16174. result.push(nV2.clone());
  16175. result.push(nV3);
  16176. result.push(nV4);
  16177. result.push(nV3.clone());
  16178. result.push(nV2.clone());
  16179. break;
  16180. case 2:
  16181. if (!v1Out) {
  16182. nV1 = vertices[index].clone();
  16183. nV2 = clipVertices(nV1, vertices[index + 1]);
  16184. nV3 = clipVertices(nV1, vertices[index + 2]);
  16185. result.push(nV1);
  16186. result.push(nV2);
  16187. result.push(nV3);
  16188. }
  16189. if (!v2Out) {
  16190. nV1 = vertices[index + 1].clone();
  16191. nV2 = clipVertices(nV1, vertices[index + 2]);
  16192. nV3 = clipVertices(nV1, vertices[index]);
  16193. result.push(nV1);
  16194. result.push(nV2);
  16195. result.push(nV3);
  16196. }
  16197. if (!v3Out) {
  16198. nV1 = vertices[index + 2].clone();
  16199. nV2 = clipVertices(nV1, vertices[index]);
  16200. nV3 = clipVertices(nV1, vertices[index + 1]);
  16201. result.push(nV1);
  16202. result.push(nV2);
  16203. result.push(nV3);
  16204. }
  16205. break;
  16206. case 3:
  16207. break;
  16208. }
  16209. }
  16210. return result;
  16211. };
  16212. for (var index = 0; index < indices.length; index += 3) {
  16213. var faceVertices = new Array();
  16214. faceVertices.push(extractDecalVector3(index));
  16215. faceVertices.push(extractDecalVector3(index + 1));
  16216. faceVertices.push(extractDecalVector3(index + 2));
  16217. // Clip
  16218. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16219. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16220. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16221. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16222. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16223. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16224. if (faceVertices.length === 0) {
  16225. continue;
  16226. }
  16227. // Add UVs and get back to world
  16228. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16229. var vertex = faceVertices[vIndex];
  16230. vertexData.indices.push(currentVertexDataIndex);
  16231. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16232. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16233. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16234. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16235. currentVertexDataIndex++;
  16236. }
  16237. }
  16238. // Return mesh
  16239. var decal = new Mesh(name, sourceMesh.getScene());
  16240. vertexData.applyToMesh(decal);
  16241. decal.position = position.clone();
  16242. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16243. return decal;
  16244. };
  16245. // Skeletons
  16246. /**
  16247. * Update the vertex buffers by applying transformation from the bones
  16248. * @param {skeleton} skeleton to apply
  16249. */
  16250. Mesh.prototype.applySkeleton = function (skeleton) {
  16251. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16252. return this;
  16253. }
  16254. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16255. return this;
  16256. }
  16257. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16258. return this;
  16259. }
  16260. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16261. return this;
  16262. }
  16263. var source;
  16264. if (!this._sourcePositions) {
  16265. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16266. this._sourcePositions = new Float32Array(source);
  16267. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16268. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16269. }
  16270. }
  16271. if (!this._sourceNormals) {
  16272. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16273. this._sourceNormals = new Float32Array(source);
  16274. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16275. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16276. }
  16277. }
  16278. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16279. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16280. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16281. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16282. var skeletonMatrices = skeleton.getTransformMatrices();
  16283. var tempVector3 = BABYLON.Vector3.Zero();
  16284. var finalMatrix = new BABYLON.Matrix();
  16285. var tempMatrix = new BABYLON.Matrix();
  16286. for (var index = 0; index < positionsData.length; index += 3) {
  16287. var index4 = (index / 3) * 4;
  16288. var matricesWeight0 = matricesWeightsData[index4];
  16289. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16290. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16291. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16292. if (matricesWeight0 > 0) {
  16293. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16294. finalMatrix.addToSelf(tempMatrix);
  16295. }
  16296. if (matricesWeight1 > 0) {
  16297. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16298. finalMatrix.addToSelf(tempMatrix);
  16299. }
  16300. if (matricesWeight2 > 0) {
  16301. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16302. finalMatrix.addToSelf(tempMatrix);
  16303. }
  16304. if (matricesWeight3 > 0) {
  16305. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16306. finalMatrix.addToSelf(tempMatrix);
  16307. }
  16308. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16309. tempVector3.toArray(positionsData, index);
  16310. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16311. tempVector3.toArray(normalsData, index);
  16312. finalMatrix.reset();
  16313. }
  16314. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16315. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16316. return this;
  16317. };
  16318. // Tools
  16319. Mesh.MinMax = function (meshes) {
  16320. var minVector = null;
  16321. var maxVector = null;
  16322. for (var i in meshes) {
  16323. var mesh = meshes[i];
  16324. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16325. if (!minVector) {
  16326. minVector = boundingBox.minimumWorld;
  16327. maxVector = boundingBox.maximumWorld;
  16328. continue;
  16329. }
  16330. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16331. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16332. }
  16333. return {
  16334. min: minVector,
  16335. max: maxVector
  16336. };
  16337. };
  16338. Mesh.Center = function (meshesOrMinMaxVector) {
  16339. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16340. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16341. };
  16342. /**
  16343. * Merge the array of meshes into a single mesh for performance reasons.
  16344. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16345. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16346. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16347. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16348. */
  16349. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16350. if (disposeSource === void 0) { disposeSource = true; }
  16351. var index;
  16352. if (!allow32BitsIndices) {
  16353. var totalVertices = 0;
  16354. // Counting vertices
  16355. for (index = 0; index < meshes.length; index++) {
  16356. if (meshes[index]) {
  16357. totalVertices += meshes[index].getTotalVertices();
  16358. if (totalVertices > 65536) {
  16359. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16360. return null;
  16361. }
  16362. }
  16363. }
  16364. }
  16365. // Merge
  16366. var vertexData;
  16367. var otherVertexData;
  16368. var source;
  16369. for (index = 0; index < meshes.length; index++) {
  16370. if (meshes[index]) {
  16371. meshes[index].computeWorldMatrix(true);
  16372. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16373. otherVertexData.transform(meshes[index].getWorldMatrix());
  16374. if (vertexData) {
  16375. vertexData.merge(otherVertexData);
  16376. }
  16377. else {
  16378. vertexData = otherVertexData;
  16379. source = meshes[index];
  16380. }
  16381. }
  16382. }
  16383. if (!meshSubclass) {
  16384. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16385. }
  16386. vertexData.applyToMesh(meshSubclass);
  16387. // Setting properties
  16388. meshSubclass.material = source.material;
  16389. meshSubclass.checkCollisions = source.checkCollisions;
  16390. // Cleaning
  16391. if (disposeSource) {
  16392. for (index = 0; index < meshes.length; index++) {
  16393. if (meshes[index]) {
  16394. meshes[index].dispose();
  16395. }
  16396. }
  16397. }
  16398. return meshSubclass;
  16399. };
  16400. // Consts
  16401. Mesh._FRONTSIDE = 0;
  16402. Mesh._BACKSIDE = 1;
  16403. Mesh._DOUBLESIDE = 2;
  16404. Mesh._DEFAULTSIDE = 0;
  16405. Mesh._NO_CAP = 0;
  16406. Mesh._CAP_START = 1;
  16407. Mesh._CAP_END = 2;
  16408. Mesh._CAP_ALL = 3;
  16409. return Mesh;
  16410. })(BABYLON.AbstractMesh);
  16411. BABYLON.Mesh = Mesh;
  16412. })(BABYLON || (BABYLON = {}));
  16413. var BABYLON;
  16414. (function (BABYLON) {
  16415. var SubMesh = (function () {
  16416. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16417. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16418. this.materialIndex = materialIndex;
  16419. this.verticesStart = verticesStart;
  16420. this.verticesCount = verticesCount;
  16421. this.indexStart = indexStart;
  16422. this.indexCount = indexCount;
  16423. this._renderId = 0;
  16424. this._mesh = mesh;
  16425. this._renderingMesh = renderingMesh || mesh;
  16426. mesh.subMeshes.push(this);
  16427. this._trianglePlanes = [];
  16428. this._id = mesh.subMeshes.length - 1;
  16429. if (createBoundingBox) {
  16430. this.refreshBoundingInfo();
  16431. mesh.computeWorldMatrix(true);
  16432. }
  16433. }
  16434. SubMesh.prototype.getBoundingInfo = function () {
  16435. return this._boundingInfo;
  16436. };
  16437. SubMesh.prototype.getMesh = function () {
  16438. return this._mesh;
  16439. };
  16440. SubMesh.prototype.getRenderingMesh = function () {
  16441. return this._renderingMesh;
  16442. };
  16443. SubMesh.prototype.getMaterial = function () {
  16444. var rootMaterial = this._renderingMesh.material;
  16445. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16446. var multiMaterial = rootMaterial;
  16447. return multiMaterial.getSubMaterial(this.materialIndex);
  16448. }
  16449. if (!rootMaterial) {
  16450. return this._mesh.getScene().defaultMaterial;
  16451. }
  16452. return rootMaterial;
  16453. };
  16454. // Methods
  16455. SubMesh.prototype.refreshBoundingInfo = function () {
  16456. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16457. if (!data) {
  16458. this._boundingInfo = this._mesh._boundingInfo;
  16459. return;
  16460. }
  16461. var indices = this._renderingMesh.getIndices();
  16462. var extend;
  16463. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16464. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16465. }
  16466. else {
  16467. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16468. }
  16469. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16470. };
  16471. SubMesh.prototype._checkCollision = function (collider) {
  16472. return this._boundingInfo._checkCollision(collider);
  16473. };
  16474. SubMesh.prototype.updateBoundingInfo = function (world) {
  16475. if (!this._boundingInfo) {
  16476. this.refreshBoundingInfo();
  16477. }
  16478. this._boundingInfo._update(world);
  16479. };
  16480. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16481. return this._boundingInfo.isInFrustum(frustumPlanes);
  16482. };
  16483. SubMesh.prototype.render = function (enableAlphaMode) {
  16484. this._renderingMesh.render(this, enableAlphaMode);
  16485. };
  16486. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16487. if (!this._linesIndexBuffer) {
  16488. var linesIndices = [];
  16489. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16490. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16491. }
  16492. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16493. this.linesIndexCount = linesIndices.length;
  16494. }
  16495. return this._linesIndexBuffer;
  16496. };
  16497. SubMesh.prototype.canIntersects = function (ray) {
  16498. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16499. };
  16500. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16501. var intersectInfo = null;
  16502. // Triangles test
  16503. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16504. var p0 = positions[indices[index]];
  16505. var p1 = positions[indices[index + 1]];
  16506. var p2 = positions[indices[index + 2]];
  16507. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16508. if (currentIntersectInfo) {
  16509. if (currentIntersectInfo.distance < 0) {
  16510. continue;
  16511. }
  16512. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16513. intersectInfo = currentIntersectInfo;
  16514. intersectInfo.faceId = index / 3;
  16515. if (fastCheck) {
  16516. break;
  16517. }
  16518. }
  16519. }
  16520. }
  16521. return intersectInfo;
  16522. };
  16523. // Clone
  16524. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16525. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16526. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16527. return result;
  16528. };
  16529. // Dispose
  16530. SubMesh.prototype.dispose = function () {
  16531. if (this._linesIndexBuffer) {
  16532. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16533. this._linesIndexBuffer = null;
  16534. }
  16535. // Remove from mesh
  16536. var index = this._mesh.subMeshes.indexOf(this);
  16537. this._mesh.subMeshes.splice(index, 1);
  16538. };
  16539. // Statics
  16540. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16541. var minVertexIndex = Number.MAX_VALUE;
  16542. var maxVertexIndex = -Number.MAX_VALUE;
  16543. renderingMesh = renderingMesh || mesh;
  16544. var indices = renderingMesh.getIndices();
  16545. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16546. var vertexIndex = indices[index];
  16547. if (vertexIndex < minVertexIndex)
  16548. minVertexIndex = vertexIndex;
  16549. if (vertexIndex > maxVertexIndex)
  16550. maxVertexIndex = vertexIndex;
  16551. }
  16552. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16553. };
  16554. return SubMesh;
  16555. })();
  16556. BABYLON.SubMesh = SubMesh;
  16557. })(BABYLON || (BABYLON = {}));
  16558. var BABYLON;
  16559. (function (BABYLON) {
  16560. var BaseTexture = (function () {
  16561. function BaseTexture(scene) {
  16562. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16563. this.hasAlpha = false;
  16564. this.getAlphaFromRGB = false;
  16565. this.level = 1;
  16566. this.isCube = false;
  16567. this.isRenderTarget = false;
  16568. this.animations = new Array();
  16569. this.coordinatesIndex = 0;
  16570. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16571. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16572. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16573. this.anisotropicFilteringLevel = 4;
  16574. this._scene = scene;
  16575. this._scene.textures.push(this);
  16576. }
  16577. BaseTexture.prototype.getScene = function () {
  16578. return this._scene;
  16579. };
  16580. BaseTexture.prototype.getTextureMatrix = function () {
  16581. return null;
  16582. };
  16583. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16584. return null;
  16585. };
  16586. BaseTexture.prototype.getInternalTexture = function () {
  16587. return this._texture;
  16588. };
  16589. BaseTexture.prototype.isReady = function () {
  16590. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16591. return true;
  16592. }
  16593. if (this._texture) {
  16594. return this._texture.isReady;
  16595. }
  16596. return false;
  16597. };
  16598. BaseTexture.prototype.getSize = function () {
  16599. if (this._texture._width) {
  16600. return { width: this._texture._width, height: this._texture._height };
  16601. }
  16602. if (this._texture._size) {
  16603. return { width: this._texture._size, height: this._texture._size };
  16604. }
  16605. return { width: 0, height: 0 };
  16606. };
  16607. BaseTexture.prototype.getBaseSize = function () {
  16608. if (!this.isReady())
  16609. return { width: 0, height: 0 };
  16610. if (this._texture._size) {
  16611. return { width: this._texture._size, height: this._texture._size };
  16612. }
  16613. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16614. };
  16615. BaseTexture.prototype.scale = function (ratio) {
  16616. };
  16617. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16618. get: function () {
  16619. return false;
  16620. },
  16621. enumerable: true,
  16622. configurable: true
  16623. });
  16624. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16625. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16626. for (var index = 0; index < texturesCache.length; index++) {
  16627. var texturesCacheEntry = texturesCache[index];
  16628. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16629. texturesCache.splice(index, 1);
  16630. return;
  16631. }
  16632. }
  16633. };
  16634. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16635. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16636. for (var index = 0; index < texturesCache.length; index++) {
  16637. var texturesCacheEntry = texturesCache[index];
  16638. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16639. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16640. texturesCacheEntry.references++;
  16641. return texturesCacheEntry;
  16642. }
  16643. }
  16644. }
  16645. return null;
  16646. };
  16647. BaseTexture.prototype.delayLoad = function () {
  16648. };
  16649. BaseTexture.prototype.releaseInternalTexture = function () {
  16650. if (!this._texture) {
  16651. return;
  16652. }
  16653. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16654. this._texture.references--;
  16655. // Final reference ?
  16656. if (this._texture.references === 0) {
  16657. var index = texturesCache.indexOf(this._texture);
  16658. texturesCache.splice(index, 1);
  16659. this._scene.getEngine()._releaseTexture(this._texture);
  16660. delete this._texture;
  16661. }
  16662. };
  16663. BaseTexture.prototype.clone = function () {
  16664. return null;
  16665. };
  16666. BaseTexture.prototype.dispose = function () {
  16667. // Remove from scene
  16668. var index = this._scene.textures.indexOf(this);
  16669. if (index >= 0) {
  16670. this._scene.textures.splice(index, 1);
  16671. }
  16672. if (this._texture === undefined) {
  16673. return;
  16674. }
  16675. this.releaseInternalTexture();
  16676. // Callback
  16677. if (this.onDispose) {
  16678. this.onDispose();
  16679. }
  16680. };
  16681. return BaseTexture;
  16682. })();
  16683. BABYLON.BaseTexture = BaseTexture;
  16684. })(BABYLON || (BABYLON = {}));
  16685. var BABYLON;
  16686. (function (BABYLON) {
  16687. var Texture = (function (_super) {
  16688. __extends(Texture, _super);
  16689. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16690. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16691. if (onLoad === void 0) { onLoad = null; }
  16692. if (onError === void 0) { onError = null; }
  16693. if (buffer === void 0) { buffer = null; }
  16694. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16695. _super.call(this, scene);
  16696. this.uOffset = 0;
  16697. this.vOffset = 0;
  16698. this.uScale = 1.0;
  16699. this.vScale = 1.0;
  16700. this.uAng = 0;
  16701. this.vAng = 0;
  16702. this.wAng = 0;
  16703. this.name = url;
  16704. this.url = url;
  16705. this._noMipmap = noMipmap;
  16706. this._invertY = invertY;
  16707. this._samplingMode = samplingMode;
  16708. this._buffer = buffer;
  16709. this._deleteBuffer = deleteBuffer;
  16710. if (!url) {
  16711. return;
  16712. }
  16713. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16714. if (!this._texture) {
  16715. if (!scene.useDelayedTextureLoading) {
  16716. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16717. if (deleteBuffer) {
  16718. delete this._buffer;
  16719. }
  16720. }
  16721. else {
  16722. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16723. }
  16724. }
  16725. else {
  16726. BABYLON.Tools.SetImmediate(function () {
  16727. if (onLoad) {
  16728. onLoad();
  16729. }
  16730. });
  16731. }
  16732. }
  16733. Texture.prototype.delayLoad = function () {
  16734. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16735. return;
  16736. }
  16737. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16738. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16739. if (!this._texture) {
  16740. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16741. if (this._deleteBuffer) {
  16742. delete this._buffer;
  16743. }
  16744. }
  16745. };
  16746. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16747. if (!this._texture) {
  16748. return;
  16749. }
  16750. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16751. };
  16752. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16753. x -= this.uOffset + 0.5;
  16754. y -= this.vOffset + 0.5;
  16755. z -= 0.5;
  16756. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16757. t.x *= this.uScale;
  16758. t.y *= this.vScale;
  16759. t.x += 0.5;
  16760. t.y += 0.5;
  16761. t.z += 0.5;
  16762. };
  16763. Texture.prototype.getTextureMatrix = function () {
  16764. if (this.uOffset === this._cachedUOffset &&
  16765. this.vOffset === this._cachedVOffset &&
  16766. this.uScale === this._cachedUScale &&
  16767. this.vScale === this._cachedVScale &&
  16768. this.uAng === this._cachedUAng &&
  16769. this.vAng === this._cachedVAng &&
  16770. this.wAng === this._cachedWAng) {
  16771. return this._cachedTextureMatrix;
  16772. }
  16773. this._cachedUOffset = this.uOffset;
  16774. this._cachedVOffset = this.vOffset;
  16775. this._cachedUScale = this.uScale;
  16776. this._cachedVScale = this.vScale;
  16777. this._cachedUAng = this.uAng;
  16778. this._cachedVAng = this.vAng;
  16779. this._cachedWAng = this.wAng;
  16780. if (!this._cachedTextureMatrix) {
  16781. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16782. this._rowGenerationMatrix = new BABYLON.Matrix();
  16783. this._t0 = BABYLON.Vector3.Zero();
  16784. this._t1 = BABYLON.Vector3.Zero();
  16785. this._t2 = BABYLON.Vector3.Zero();
  16786. }
  16787. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16788. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16789. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16790. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16791. this._t1.subtractInPlace(this._t0);
  16792. this._t2.subtractInPlace(this._t0);
  16793. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16794. this._cachedTextureMatrix.m[0] = this._t1.x;
  16795. this._cachedTextureMatrix.m[1] = this._t1.y;
  16796. this._cachedTextureMatrix.m[2] = this._t1.z;
  16797. this._cachedTextureMatrix.m[4] = this._t2.x;
  16798. this._cachedTextureMatrix.m[5] = this._t2.y;
  16799. this._cachedTextureMatrix.m[6] = this._t2.z;
  16800. this._cachedTextureMatrix.m[8] = this._t0.x;
  16801. this._cachedTextureMatrix.m[9] = this._t0.y;
  16802. this._cachedTextureMatrix.m[10] = this._t0.z;
  16803. return this._cachedTextureMatrix;
  16804. };
  16805. Texture.prototype.getReflectionTextureMatrix = function () {
  16806. if (this.uOffset === this._cachedUOffset &&
  16807. this.vOffset === this._cachedVOffset &&
  16808. this.uScale === this._cachedUScale &&
  16809. this.vScale === this._cachedVScale &&
  16810. this.coordinatesMode === this._cachedCoordinatesMode) {
  16811. return this._cachedTextureMatrix;
  16812. }
  16813. if (!this._cachedTextureMatrix) {
  16814. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16815. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16816. }
  16817. this._cachedCoordinatesMode = this.coordinatesMode;
  16818. switch (this.coordinatesMode) {
  16819. case Texture.SPHERICAL_MODE:
  16820. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16821. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16822. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16823. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16824. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16825. break;
  16826. case Texture.PLANAR_MODE:
  16827. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16828. this._cachedTextureMatrix[0] = this.uScale;
  16829. this._cachedTextureMatrix[5] = this.vScale;
  16830. this._cachedTextureMatrix[12] = this.uOffset;
  16831. this._cachedTextureMatrix[13] = this.vOffset;
  16832. break;
  16833. case Texture.PROJECTION_MODE:
  16834. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16835. this._projectionModeMatrix.m[0] = 0.5;
  16836. this._projectionModeMatrix.m[5] = -0.5;
  16837. this._projectionModeMatrix.m[10] = 0.0;
  16838. this._projectionModeMatrix.m[12] = 0.5;
  16839. this._projectionModeMatrix.m[13] = 0.5;
  16840. this._projectionModeMatrix.m[14] = 1.0;
  16841. this._projectionModeMatrix.m[15] = 1.0;
  16842. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16843. break;
  16844. default:
  16845. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16846. break;
  16847. }
  16848. return this._cachedTextureMatrix;
  16849. };
  16850. Texture.prototype.clone = function () {
  16851. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16852. // Base texture
  16853. newTexture.hasAlpha = this.hasAlpha;
  16854. newTexture.level = this.level;
  16855. newTexture.wrapU = this.wrapU;
  16856. newTexture.wrapV = this.wrapV;
  16857. newTexture.coordinatesIndex = this.coordinatesIndex;
  16858. newTexture.coordinatesMode = this.coordinatesMode;
  16859. // Texture
  16860. newTexture.uOffset = this.uOffset;
  16861. newTexture.vOffset = this.vOffset;
  16862. newTexture.uScale = this.uScale;
  16863. newTexture.vScale = this.vScale;
  16864. newTexture.uAng = this.uAng;
  16865. newTexture.vAng = this.vAng;
  16866. newTexture.wAng = this.wAng;
  16867. return newTexture;
  16868. };
  16869. // Statics
  16870. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16871. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16872. if (onLoad === void 0) { onLoad = null; }
  16873. if (onError === void 0) { onError = null; }
  16874. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16875. };
  16876. // Constants
  16877. Texture.NEAREST_SAMPLINGMODE = 1;
  16878. Texture.BILINEAR_SAMPLINGMODE = 2;
  16879. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16880. Texture.EXPLICIT_MODE = 0;
  16881. Texture.SPHERICAL_MODE = 1;
  16882. Texture.PLANAR_MODE = 2;
  16883. Texture.CUBIC_MODE = 3;
  16884. Texture.PROJECTION_MODE = 4;
  16885. Texture.SKYBOX_MODE = 5;
  16886. Texture.CLAMP_ADDRESSMODE = 0;
  16887. Texture.WRAP_ADDRESSMODE = 1;
  16888. Texture.MIRROR_ADDRESSMODE = 2;
  16889. return Texture;
  16890. })(BABYLON.BaseTexture);
  16891. BABYLON.Texture = Texture;
  16892. })(BABYLON || (BABYLON = {}));
  16893. var BABYLON;
  16894. (function (BABYLON) {
  16895. var CubeTexture = (function (_super) {
  16896. __extends(CubeTexture, _super);
  16897. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16898. _super.call(this, scene);
  16899. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16900. this.name = rootUrl;
  16901. this.url = rootUrl;
  16902. this._noMipmap = noMipmap;
  16903. this.hasAlpha = false;
  16904. this._texture = this._getFromCache(rootUrl, noMipmap);
  16905. if (!extensions) {
  16906. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16907. }
  16908. this._extensions = extensions;
  16909. if (!this._texture) {
  16910. if (!scene.useDelayedTextureLoading) {
  16911. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16912. }
  16913. else {
  16914. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16915. }
  16916. }
  16917. this.isCube = true;
  16918. this._textureMatrix = BABYLON.Matrix.Identity();
  16919. }
  16920. CubeTexture.prototype.clone = function () {
  16921. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16922. // Base texture
  16923. newTexture.level = this.level;
  16924. newTexture.wrapU = this.wrapU;
  16925. newTexture.wrapV = this.wrapV;
  16926. newTexture.coordinatesIndex = this.coordinatesIndex;
  16927. newTexture.coordinatesMode = this.coordinatesMode;
  16928. return newTexture;
  16929. };
  16930. // Methods
  16931. CubeTexture.prototype.delayLoad = function () {
  16932. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16933. return;
  16934. }
  16935. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16936. this._texture = this._getFromCache(this.url, this._noMipmap);
  16937. if (!this._texture) {
  16938. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16939. }
  16940. };
  16941. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16942. return this._textureMatrix;
  16943. };
  16944. return CubeTexture;
  16945. })(BABYLON.BaseTexture);
  16946. BABYLON.CubeTexture = CubeTexture;
  16947. })(BABYLON || (BABYLON = {}));
  16948. var BABYLON;
  16949. (function (BABYLON) {
  16950. var RenderTargetTexture = (function (_super) {
  16951. __extends(RenderTargetTexture, _super);
  16952. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16953. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16954. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16955. _super.call(this, null, scene, !generateMipMaps);
  16956. this.renderList = new Array();
  16957. this.renderParticles = true;
  16958. this.renderSprites = false;
  16959. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16960. this._currentRefreshId = -1;
  16961. this._refreshRate = 1;
  16962. this.name = name;
  16963. this.isRenderTarget = true;
  16964. this._size = size;
  16965. this._generateMipMaps = generateMipMaps;
  16966. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16967. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16968. // Rendering groups
  16969. this._renderingManager = new BABYLON.RenderingManager(scene);
  16970. }
  16971. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16972. this._currentRefreshId = -1;
  16973. };
  16974. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16975. get: function () {
  16976. return this._refreshRate;
  16977. },
  16978. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16979. set: function (value) {
  16980. this._refreshRate = value;
  16981. this.resetRefreshCounter();
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. RenderTargetTexture.prototype._shouldRender = function () {
  16987. if (this._currentRefreshId === -1) {
  16988. this._currentRefreshId = 1;
  16989. return true;
  16990. }
  16991. if (this.refreshRate === this._currentRefreshId) {
  16992. this._currentRefreshId = 1;
  16993. return true;
  16994. }
  16995. this._currentRefreshId++;
  16996. return false;
  16997. };
  16998. RenderTargetTexture.prototype.isReady = function () {
  16999. if (!this.getScene().renderTargetsEnabled) {
  17000. return false;
  17001. }
  17002. return _super.prototype.isReady.call(this);
  17003. };
  17004. RenderTargetTexture.prototype.getRenderSize = function () {
  17005. return this._size;
  17006. };
  17007. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17008. get: function () {
  17009. return true;
  17010. },
  17011. enumerable: true,
  17012. configurable: true
  17013. });
  17014. RenderTargetTexture.prototype.scale = function (ratio) {
  17015. var newSize = this._size * ratio;
  17016. this.resize(newSize, this._generateMipMaps);
  17017. };
  17018. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17019. this.releaseInternalTexture();
  17020. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17021. };
  17022. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17023. var scene = this.getScene();
  17024. var engine = scene.getEngine();
  17025. if (this._waitingRenderList) {
  17026. this.renderList = [];
  17027. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17028. var id = this._waitingRenderList[index];
  17029. this.renderList.push(scene.getMeshByID(id));
  17030. }
  17031. delete this._waitingRenderList;
  17032. }
  17033. if (this.renderList && this.renderList.length === 0) {
  17034. return;
  17035. }
  17036. // Bind
  17037. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17038. engine.bindFramebuffer(this._texture);
  17039. }
  17040. this._renderingManager.reset();
  17041. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17042. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17043. var mesh = currentRenderList[meshIndex];
  17044. if (mesh) {
  17045. if (!mesh.isReady()) {
  17046. // Reset _currentRefreshId
  17047. this.resetRefreshCounter();
  17048. continue;
  17049. }
  17050. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17051. mesh._activate(scene.getRenderId());
  17052. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17053. var subMesh = mesh.subMeshes[subIndex];
  17054. scene._activeIndices += subMesh.indexCount;
  17055. this._renderingManager.dispatch(subMesh);
  17056. }
  17057. }
  17058. }
  17059. }
  17060. if (this.onBeforeRender) {
  17061. this.onBeforeRender();
  17062. }
  17063. // Clear
  17064. if (this.onClear) {
  17065. this.onClear(engine);
  17066. }
  17067. else {
  17068. engine.clear(scene.clearColor, true, true);
  17069. }
  17070. if (!this._doNotChangeAspectRatio) {
  17071. scene.updateTransformMatrix(true);
  17072. }
  17073. // Render
  17074. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17075. if (useCameraPostProcess) {
  17076. scene.postProcessManager._finalizeFrame(false, this._texture);
  17077. }
  17078. if (!this._doNotChangeAspectRatio) {
  17079. scene.updateTransformMatrix(true);
  17080. }
  17081. if (this.onAfterRender) {
  17082. this.onAfterRender();
  17083. }
  17084. // Dump ?
  17085. if (dumpForDebug) {
  17086. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17087. }
  17088. // Unbind
  17089. engine.unBindFramebuffer(this._texture);
  17090. if (this.onAfterUnbind) {
  17091. this.onAfterUnbind();
  17092. }
  17093. };
  17094. RenderTargetTexture.prototype.clone = function () {
  17095. var textureSize = this.getSize();
  17096. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17097. // Base texture
  17098. newTexture.hasAlpha = this.hasAlpha;
  17099. newTexture.level = this.level;
  17100. // RenderTarget Texture
  17101. newTexture.coordinatesMode = this.coordinatesMode;
  17102. newTexture.renderList = this.renderList.slice(0);
  17103. return newTexture;
  17104. };
  17105. return RenderTargetTexture;
  17106. })(BABYLON.Texture);
  17107. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17108. })(BABYLON || (BABYLON = {}));
  17109. var BABYLON;
  17110. (function (BABYLON) {
  17111. var ProceduralTexture = (function (_super) {
  17112. __extends(ProceduralTexture, _super);
  17113. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17114. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17115. _super.call(this, null, scene, !generateMipMaps);
  17116. this.isEnabled = true;
  17117. this._currentRefreshId = -1;
  17118. this._refreshRate = 1;
  17119. this._vertexDeclaration = [2];
  17120. this._vertexStrideSize = 2 * 4;
  17121. this._uniforms = new Array();
  17122. this._samplers = new Array();
  17123. this._textures = new Array();
  17124. this._floats = new Array();
  17125. this._floatsArrays = {};
  17126. this._colors3 = new Array();
  17127. this._colors4 = new Array();
  17128. this._vectors2 = new Array();
  17129. this._vectors3 = new Array();
  17130. this._matrices = new Array();
  17131. this._fallbackTextureUsed = false;
  17132. scene._proceduralTextures.push(this);
  17133. this.name = name;
  17134. this.isRenderTarget = true;
  17135. this._size = size;
  17136. this._generateMipMaps = generateMipMaps;
  17137. this.setFragment(fragment);
  17138. this._fallbackTexture = fallbackTexture;
  17139. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17140. // VBO
  17141. var vertices = [];
  17142. vertices.push(1, 1);
  17143. vertices.push(-1, 1);
  17144. vertices.push(-1, -1);
  17145. vertices.push(1, -1);
  17146. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17147. // Indices
  17148. var indices = [];
  17149. indices.push(0);
  17150. indices.push(1);
  17151. indices.push(2);
  17152. indices.push(0);
  17153. indices.push(2);
  17154. indices.push(3);
  17155. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17156. }
  17157. ProceduralTexture.prototype.reset = function () {
  17158. if (this._effect === undefined) {
  17159. return;
  17160. }
  17161. var engine = this.getScene().getEngine();
  17162. engine._releaseEffect(this._effect);
  17163. };
  17164. ProceduralTexture.prototype.isReady = function () {
  17165. var _this = this;
  17166. var engine = this.getScene().getEngine();
  17167. var shaders;
  17168. if (!this._fragment) {
  17169. return false;
  17170. }
  17171. if (this._fallbackTextureUsed) {
  17172. return true;
  17173. }
  17174. if (this._fragment.fragmentElement !== undefined) {
  17175. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17176. }
  17177. else {
  17178. shaders = { vertex: "procedural", fragment: this._fragment };
  17179. }
  17180. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17181. _this.releaseInternalTexture();
  17182. if (_this._fallbackTexture) {
  17183. _this._texture = _this._fallbackTexture._texture;
  17184. _this._texture.references++;
  17185. }
  17186. _this._fallbackTextureUsed = true;
  17187. });
  17188. return this._effect.isReady();
  17189. };
  17190. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17191. this._currentRefreshId = -1;
  17192. };
  17193. ProceduralTexture.prototype.setFragment = function (fragment) {
  17194. this._fragment = fragment;
  17195. };
  17196. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17197. get: function () {
  17198. return this._refreshRate;
  17199. },
  17200. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17201. set: function (value) {
  17202. this._refreshRate = value;
  17203. this.resetRefreshCounter();
  17204. },
  17205. enumerable: true,
  17206. configurable: true
  17207. });
  17208. ProceduralTexture.prototype._shouldRender = function () {
  17209. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17210. return false;
  17211. }
  17212. if (this._fallbackTextureUsed) {
  17213. return false;
  17214. }
  17215. if (this._currentRefreshId === -1) {
  17216. this._currentRefreshId = 1;
  17217. return true;
  17218. }
  17219. if (this.refreshRate === this._currentRefreshId) {
  17220. this._currentRefreshId = 1;
  17221. return true;
  17222. }
  17223. this._currentRefreshId++;
  17224. return false;
  17225. };
  17226. ProceduralTexture.prototype.getRenderSize = function () {
  17227. return this._size;
  17228. };
  17229. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17230. if (this._fallbackTextureUsed) {
  17231. return;
  17232. }
  17233. this.releaseInternalTexture();
  17234. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17235. };
  17236. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17237. if (this._uniforms.indexOf(uniformName) === -1) {
  17238. this._uniforms.push(uniformName);
  17239. }
  17240. };
  17241. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17242. if (this._samplers.indexOf(name) === -1) {
  17243. this._samplers.push(name);
  17244. }
  17245. this._textures[name] = texture;
  17246. return this;
  17247. };
  17248. ProceduralTexture.prototype.setFloat = function (name, value) {
  17249. this._checkUniform(name);
  17250. this._floats[name] = value;
  17251. return this;
  17252. };
  17253. ProceduralTexture.prototype.setFloats = function (name, value) {
  17254. this._checkUniform(name);
  17255. this._floatsArrays[name] = value;
  17256. return this;
  17257. };
  17258. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17259. this._checkUniform(name);
  17260. this._colors3[name] = value;
  17261. return this;
  17262. };
  17263. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17264. this._checkUniform(name);
  17265. this._colors4[name] = value;
  17266. return this;
  17267. };
  17268. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17269. this._checkUniform(name);
  17270. this._vectors2[name] = value;
  17271. return this;
  17272. };
  17273. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17274. this._checkUniform(name);
  17275. this._vectors3[name] = value;
  17276. return this;
  17277. };
  17278. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17279. this._checkUniform(name);
  17280. this._matrices[name] = value;
  17281. return this;
  17282. };
  17283. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17284. var scene = this.getScene();
  17285. var engine = scene.getEngine();
  17286. engine.bindFramebuffer(this._texture);
  17287. // Clear
  17288. engine.clear(scene.clearColor, true, true);
  17289. // Render
  17290. engine.enableEffect(this._effect);
  17291. engine.setState(false);
  17292. // Texture
  17293. for (var name in this._textures) {
  17294. this._effect.setTexture(name, this._textures[name]);
  17295. }
  17296. // Float
  17297. for (name in this._floats) {
  17298. this._effect.setFloat(name, this._floats[name]);
  17299. }
  17300. // Floats
  17301. for (name in this._floatsArrays) {
  17302. this._effect.setArray(name, this._floatsArrays[name]);
  17303. }
  17304. // Color3
  17305. for (name in this._colors3) {
  17306. this._effect.setColor3(name, this._colors3[name]);
  17307. }
  17308. // Color4
  17309. for (name in this._colors4) {
  17310. var color = this._colors4[name];
  17311. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17312. }
  17313. // Vector2
  17314. for (name in this._vectors2) {
  17315. this._effect.setVector2(name, this._vectors2[name]);
  17316. }
  17317. // Vector3
  17318. for (name in this._vectors3) {
  17319. this._effect.setVector3(name, this._vectors3[name]);
  17320. }
  17321. // Matrix
  17322. for (name in this._matrices) {
  17323. this._effect.setMatrix(name, this._matrices[name]);
  17324. }
  17325. // VBOs
  17326. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17327. // Draw order
  17328. engine.draw(true, 0, 6);
  17329. // Unbind
  17330. engine.unBindFramebuffer(this._texture);
  17331. };
  17332. ProceduralTexture.prototype.clone = function () {
  17333. var textureSize = this.getSize();
  17334. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17335. // Base texture
  17336. newTexture.hasAlpha = this.hasAlpha;
  17337. newTexture.level = this.level;
  17338. // RenderTarget Texture
  17339. newTexture.coordinatesMode = this.coordinatesMode;
  17340. return newTexture;
  17341. };
  17342. ProceduralTexture.prototype.dispose = function () {
  17343. var index = this.getScene()._proceduralTextures.indexOf(this);
  17344. if (index >= 0) {
  17345. this.getScene()._proceduralTextures.splice(index, 1);
  17346. }
  17347. _super.prototype.dispose.call(this);
  17348. };
  17349. return ProceduralTexture;
  17350. })(BABYLON.Texture);
  17351. BABYLON.ProceduralTexture = ProceduralTexture;
  17352. })(BABYLON || (BABYLON = {}));
  17353. var BABYLON;
  17354. (function (BABYLON) {
  17355. var MirrorTexture = (function (_super) {
  17356. __extends(MirrorTexture, _super);
  17357. function MirrorTexture(name, size, scene, generateMipMaps) {
  17358. var _this = this;
  17359. _super.call(this, name, size, scene, generateMipMaps, true);
  17360. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17361. this._transformMatrix = BABYLON.Matrix.Zero();
  17362. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17363. this.onBeforeRender = function () {
  17364. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17365. _this._savedViewMatrix = scene.getViewMatrix();
  17366. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17367. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17368. scene.clipPlane = _this.mirrorPlane;
  17369. scene.getEngine().cullBackFaces = false;
  17370. };
  17371. this.onAfterRender = function () {
  17372. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17373. scene.getEngine().cullBackFaces = true;
  17374. delete scene.clipPlane;
  17375. };
  17376. }
  17377. MirrorTexture.prototype.clone = function () {
  17378. var textureSize = this.getSize();
  17379. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17380. // Base texture
  17381. newTexture.hasAlpha = this.hasAlpha;
  17382. newTexture.level = this.level;
  17383. // Mirror Texture
  17384. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17385. newTexture.renderList = this.renderList.slice(0);
  17386. return newTexture;
  17387. };
  17388. return MirrorTexture;
  17389. })(BABYLON.RenderTargetTexture);
  17390. BABYLON.MirrorTexture = MirrorTexture;
  17391. })(BABYLON || (BABYLON = {}));
  17392. var BABYLON;
  17393. (function (BABYLON) {
  17394. var DynamicTexture = (function (_super) {
  17395. __extends(DynamicTexture, _super);
  17396. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17397. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17398. _super.call(this, null, scene, !generateMipMaps);
  17399. this.name = name;
  17400. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17401. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17402. this._generateMipMaps = generateMipMaps;
  17403. if (options.getContext) {
  17404. this._canvas = options;
  17405. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17406. }
  17407. else {
  17408. this._canvas = document.createElement("canvas");
  17409. if (options.width) {
  17410. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17411. }
  17412. else {
  17413. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17414. }
  17415. }
  17416. var textureSize = this.getSize();
  17417. this._canvas.width = textureSize.width;
  17418. this._canvas.height = textureSize.height;
  17419. this._context = this._canvas.getContext("2d");
  17420. }
  17421. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17422. get: function () {
  17423. return true;
  17424. },
  17425. enumerable: true,
  17426. configurable: true
  17427. });
  17428. DynamicTexture.prototype.scale = function (ratio) {
  17429. var textureSize = this.getSize();
  17430. textureSize.width *= ratio;
  17431. textureSize.height *= ratio;
  17432. this._canvas.width = textureSize.width;
  17433. this._canvas.height = textureSize.height;
  17434. this.releaseInternalTexture();
  17435. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17436. };
  17437. DynamicTexture.prototype.getContext = function () {
  17438. return this._context;
  17439. };
  17440. DynamicTexture.prototype.clear = function () {
  17441. var size = this.getSize();
  17442. this._context.fillRect(0, 0, size.width, size.height);
  17443. };
  17444. DynamicTexture.prototype.update = function (invertY) {
  17445. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17446. };
  17447. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17448. if (update === void 0) { update = true; }
  17449. var size = this.getSize();
  17450. if (clearColor) {
  17451. this._context.fillStyle = clearColor;
  17452. this._context.fillRect(0, 0, size.width, size.height);
  17453. }
  17454. this._context.font = font;
  17455. if (x === null) {
  17456. var textSize = this._context.measureText(text);
  17457. x = (size.width - textSize.width) / 2;
  17458. }
  17459. this._context.fillStyle = color;
  17460. this._context.fillText(text, x, y);
  17461. if (update) {
  17462. this.update(invertY);
  17463. }
  17464. };
  17465. DynamicTexture.prototype.clone = function () {
  17466. var textureSize = this.getSize();
  17467. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17468. // Base texture
  17469. newTexture.hasAlpha = this.hasAlpha;
  17470. newTexture.level = this.level;
  17471. // Dynamic Texture
  17472. newTexture.wrapU = this.wrapU;
  17473. newTexture.wrapV = this.wrapV;
  17474. return newTexture;
  17475. };
  17476. return DynamicTexture;
  17477. })(BABYLON.Texture);
  17478. BABYLON.DynamicTexture = DynamicTexture;
  17479. })(BABYLON || (BABYLON = {}));
  17480. var BABYLON;
  17481. (function (BABYLON) {
  17482. var VideoTexture = (function (_super) {
  17483. __extends(VideoTexture, _super);
  17484. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17485. var _this = this;
  17486. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17487. if (invertY === void 0) { invertY = false; }
  17488. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17489. _super.call(this, null, scene, !generateMipMaps, invertY);
  17490. this._autoLaunch = true;
  17491. this.name = name;
  17492. this.video = document.createElement("video");
  17493. this.video.autoplay = false;
  17494. this.video.loop = true;
  17495. this.video.addEventListener("canplaythrough", function () {
  17496. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17497. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17498. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17499. }
  17500. else {
  17501. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17502. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17503. generateMipMaps = false;
  17504. }
  17505. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17506. _this._texture.isReady = true;
  17507. });
  17508. urls.forEach(function (url) {
  17509. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17510. var source = document.createElement("source");
  17511. source.src = url;
  17512. _this.video.appendChild(source);
  17513. });
  17514. this._lastUpdate = BABYLON.Tools.Now;
  17515. }
  17516. VideoTexture.prototype.update = function () {
  17517. if (this._autoLaunch) {
  17518. this._autoLaunch = false;
  17519. this.video.play();
  17520. }
  17521. var now = BABYLON.Tools.Now;
  17522. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17523. return false;
  17524. }
  17525. this._lastUpdate = now;
  17526. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17527. return true;
  17528. };
  17529. return VideoTexture;
  17530. })(BABYLON.Texture);
  17531. BABYLON.VideoTexture = VideoTexture;
  17532. })(BABYLON || (BABYLON = {}));
  17533. var BABYLON;
  17534. (function (BABYLON) {
  17535. var CustomProceduralTexture = (function (_super) {
  17536. __extends(CustomProceduralTexture, _super);
  17537. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17538. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17539. this._animate = true;
  17540. this._time = 0;
  17541. this._texturePath = texturePath;
  17542. //Try to load json
  17543. this.loadJson(texturePath);
  17544. this.refreshRate = 1;
  17545. }
  17546. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17547. var _this = this;
  17548. var that = this;
  17549. function noConfigFile() {
  17550. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17551. try {
  17552. that.setFragment(that._texturePath);
  17553. }
  17554. catch (ex) {
  17555. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17556. }
  17557. }
  17558. var configFileUrl = jsonUrl + "/config.json";
  17559. var xhr = new XMLHttpRequest();
  17560. xhr.open("GET", configFileUrl, true);
  17561. xhr.addEventListener("load", function () {
  17562. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17563. try {
  17564. _this._config = JSON.parse(xhr.response);
  17565. _this.updateShaderUniforms();
  17566. _this.updateTextures();
  17567. _this.setFragment(_this._texturePath + "/custom");
  17568. _this._animate = _this._config.animate;
  17569. _this.refreshRate = _this._config.refreshrate;
  17570. }
  17571. catch (ex) {
  17572. noConfigFile();
  17573. }
  17574. }
  17575. else {
  17576. noConfigFile();
  17577. }
  17578. }, false);
  17579. xhr.addEventListener("error", function () {
  17580. noConfigFile();
  17581. }, false);
  17582. try {
  17583. xhr.send();
  17584. }
  17585. catch (ex) {
  17586. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17587. }
  17588. };
  17589. CustomProceduralTexture.prototype.isReady = function () {
  17590. if (!_super.prototype.isReady.call(this)) {
  17591. return false;
  17592. }
  17593. for (var name in this._textures) {
  17594. var texture = this._textures[name];
  17595. if (!texture.isReady()) {
  17596. return false;
  17597. }
  17598. }
  17599. return true;
  17600. };
  17601. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17602. if (this._animate) {
  17603. this._time += this.getScene().getAnimationRatio() * 0.03;
  17604. this.updateShaderUniforms();
  17605. }
  17606. _super.prototype.render.call(this, useCameraPostProcess);
  17607. };
  17608. CustomProceduralTexture.prototype.updateTextures = function () {
  17609. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17610. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17611. }
  17612. };
  17613. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17614. if (this._config) {
  17615. for (var j = 0; j < this._config.uniforms.length; j++) {
  17616. var uniform = this._config.uniforms[j];
  17617. switch (uniform.type) {
  17618. case "float":
  17619. this.setFloat(uniform.name, uniform.value);
  17620. break;
  17621. case "color3":
  17622. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17623. break;
  17624. case "color4":
  17625. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17626. break;
  17627. case "vector2":
  17628. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17629. break;
  17630. case "vector3":
  17631. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17632. break;
  17633. }
  17634. }
  17635. }
  17636. this.setFloat("time", this._time);
  17637. };
  17638. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17639. get: function () {
  17640. return this._animate;
  17641. },
  17642. set: function (value) {
  17643. this._animate = value;
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. return CustomProceduralTexture;
  17649. })(BABYLON.ProceduralTexture);
  17650. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17651. })(BABYLON || (BABYLON = {}));
  17652. var BABYLON;
  17653. (function (BABYLON) {
  17654. var WoodProceduralTexture = (function (_super) {
  17655. __extends(WoodProceduralTexture, _super);
  17656. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17657. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17658. this._ampScale = 100.0;
  17659. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17660. this.updateShaderUniforms();
  17661. this.refreshRate = 0;
  17662. }
  17663. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17664. this.setFloat("ampScale", this._ampScale);
  17665. this.setColor3("woodColor", this._woodColor);
  17666. };
  17667. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17668. get: function () {
  17669. return this._ampScale;
  17670. },
  17671. set: function (value) {
  17672. this._ampScale = value;
  17673. this.updateShaderUniforms();
  17674. },
  17675. enumerable: true,
  17676. configurable: true
  17677. });
  17678. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17679. get: function () {
  17680. return this._woodColor;
  17681. },
  17682. set: function (value) {
  17683. this._woodColor = value;
  17684. this.updateShaderUniforms();
  17685. },
  17686. enumerable: true,
  17687. configurable: true
  17688. });
  17689. return WoodProceduralTexture;
  17690. })(BABYLON.ProceduralTexture);
  17691. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17692. var FireProceduralTexture = (function (_super) {
  17693. __extends(FireProceduralTexture, _super);
  17694. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17695. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17696. this._time = 0.0;
  17697. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17698. this._autoGenerateTime = true;
  17699. this._alphaThreshold = 0.5;
  17700. this._fireColors = FireProceduralTexture.RedFireColors;
  17701. this.updateShaderUniforms();
  17702. this.refreshRate = 1;
  17703. }
  17704. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17705. this.setFloat("time", this._time);
  17706. this.setVector2("speed", this._speed);
  17707. this.setColor3("c1", this._fireColors[0]);
  17708. this.setColor3("c2", this._fireColors[1]);
  17709. this.setColor3("c3", this._fireColors[2]);
  17710. this.setColor3("c4", this._fireColors[3]);
  17711. this.setColor3("c5", this._fireColors[4]);
  17712. this.setColor3("c6", this._fireColors[5]);
  17713. this.setFloat("alphaThreshold", this._alphaThreshold);
  17714. };
  17715. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17716. if (this._autoGenerateTime) {
  17717. this._time += this.getScene().getAnimationRatio() * 0.03;
  17718. this.updateShaderUniforms();
  17719. }
  17720. _super.prototype.render.call(this, useCameraPostProcess);
  17721. };
  17722. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17723. get: function () {
  17724. return [
  17725. new BABYLON.Color3(0.5, 0.0, 1.0),
  17726. new BABYLON.Color3(0.9, 0.0, 1.0),
  17727. new BABYLON.Color3(0.2, 0.0, 1.0),
  17728. new BABYLON.Color3(1.0, 0.9, 1.0),
  17729. new BABYLON.Color3(0.1, 0.1, 1.0),
  17730. new BABYLON.Color3(0.9, 0.9, 1.0)
  17731. ];
  17732. },
  17733. enumerable: true,
  17734. configurable: true
  17735. });
  17736. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17737. get: function () {
  17738. return [
  17739. new BABYLON.Color3(0.5, 1.0, 0.0),
  17740. new BABYLON.Color3(0.5, 1.0, 0.0),
  17741. new BABYLON.Color3(0.3, 0.4, 0.0),
  17742. new BABYLON.Color3(0.5, 1.0, 0.0),
  17743. new BABYLON.Color3(0.2, 0.0, 0.0),
  17744. new BABYLON.Color3(0.5, 1.0, 0.0)
  17745. ];
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17751. get: function () {
  17752. return [
  17753. new BABYLON.Color3(0.5, 0.0, 0.1),
  17754. new BABYLON.Color3(0.9, 0.0, 0.0),
  17755. new BABYLON.Color3(0.2, 0.0, 0.0),
  17756. new BABYLON.Color3(1.0, 0.9, 0.0),
  17757. new BABYLON.Color3(0.1, 0.1, 0.1),
  17758. new BABYLON.Color3(0.9, 0.9, 0.9)
  17759. ];
  17760. },
  17761. enumerable: true,
  17762. configurable: true
  17763. });
  17764. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17765. get: function () {
  17766. return [
  17767. new BABYLON.Color3(0.1, 0.0, 0.5),
  17768. new BABYLON.Color3(0.0, 0.0, 0.5),
  17769. new BABYLON.Color3(0.1, 0.0, 0.2),
  17770. new BABYLON.Color3(0.0, 0.0, 1.0),
  17771. new BABYLON.Color3(0.1, 0.2, 0.3),
  17772. new BABYLON.Color3(0.0, 0.2, 0.9)
  17773. ];
  17774. },
  17775. enumerable: true,
  17776. configurable: true
  17777. });
  17778. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17779. get: function () {
  17780. return this._fireColors;
  17781. },
  17782. set: function (value) {
  17783. this._fireColors = value;
  17784. this.updateShaderUniforms();
  17785. },
  17786. enumerable: true,
  17787. configurable: true
  17788. });
  17789. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17790. get: function () {
  17791. return this._time;
  17792. },
  17793. set: function (value) {
  17794. this._time = value;
  17795. this.updateShaderUniforms();
  17796. },
  17797. enumerable: true,
  17798. configurable: true
  17799. });
  17800. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17801. get: function () {
  17802. return this._speed;
  17803. },
  17804. set: function (value) {
  17805. this._speed = value;
  17806. this.updateShaderUniforms();
  17807. },
  17808. enumerable: true,
  17809. configurable: true
  17810. });
  17811. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17812. get: function () {
  17813. return this._alphaThreshold;
  17814. },
  17815. set: function (value) {
  17816. this._alphaThreshold = value;
  17817. this.updateShaderUniforms();
  17818. },
  17819. enumerable: true,
  17820. configurable: true
  17821. });
  17822. return FireProceduralTexture;
  17823. })(BABYLON.ProceduralTexture);
  17824. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17825. var CloudProceduralTexture = (function (_super) {
  17826. __extends(CloudProceduralTexture, _super);
  17827. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17828. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17829. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17830. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17831. this.updateShaderUniforms();
  17832. this.refreshRate = 0;
  17833. }
  17834. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17835. this.setColor4("skyColor", this._skyColor);
  17836. this.setColor4("cloudColor", this._cloudColor);
  17837. };
  17838. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17839. get: function () {
  17840. return this._skyColor;
  17841. },
  17842. set: function (value) {
  17843. this._skyColor = value;
  17844. this.updateShaderUniforms();
  17845. },
  17846. enumerable: true,
  17847. configurable: true
  17848. });
  17849. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17850. get: function () {
  17851. return this._cloudColor;
  17852. },
  17853. set: function (value) {
  17854. this._cloudColor = value;
  17855. this.updateShaderUniforms();
  17856. },
  17857. enumerable: true,
  17858. configurable: true
  17859. });
  17860. return CloudProceduralTexture;
  17861. })(BABYLON.ProceduralTexture);
  17862. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17863. var GrassProceduralTexture = (function (_super) {
  17864. __extends(GrassProceduralTexture, _super);
  17865. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17866. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17867. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17868. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17869. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17870. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17871. this._grassColors = [
  17872. new BABYLON.Color3(0.29, 0.38, 0.02),
  17873. new BABYLON.Color3(0.36, 0.49, 0.09),
  17874. new BABYLON.Color3(0.51, 0.6, 0.28)
  17875. ];
  17876. this.updateShaderUniforms();
  17877. this.refreshRate = 0;
  17878. }
  17879. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17880. this.setColor3("herb1Color", this._grassColors[0]);
  17881. this.setColor3("herb2Color", this._grassColors[1]);
  17882. this.setColor3("herb3Color", this._grassColors[2]);
  17883. this.setColor3("groundColor", this._groundColor);
  17884. };
  17885. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17886. get: function () {
  17887. return this._grassColors;
  17888. },
  17889. set: function (value) {
  17890. this._grassColors = value;
  17891. this.updateShaderUniforms();
  17892. },
  17893. enumerable: true,
  17894. configurable: true
  17895. });
  17896. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17897. get: function () {
  17898. return this._groundColor;
  17899. },
  17900. set: function (value) {
  17901. this.groundColor = value;
  17902. this.updateShaderUniforms();
  17903. },
  17904. enumerable: true,
  17905. configurable: true
  17906. });
  17907. return GrassProceduralTexture;
  17908. })(BABYLON.ProceduralTexture);
  17909. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17910. var RoadProceduralTexture = (function (_super) {
  17911. __extends(RoadProceduralTexture, _super);
  17912. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17913. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17914. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17915. this.updateShaderUniforms();
  17916. this.refreshRate = 0;
  17917. }
  17918. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17919. this.setColor3("roadColor", this._roadColor);
  17920. };
  17921. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17922. get: function () {
  17923. return this._roadColor;
  17924. },
  17925. set: function (value) {
  17926. this._roadColor = value;
  17927. this.updateShaderUniforms();
  17928. },
  17929. enumerable: true,
  17930. configurable: true
  17931. });
  17932. return RoadProceduralTexture;
  17933. })(BABYLON.ProceduralTexture);
  17934. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17935. var BrickProceduralTexture = (function (_super) {
  17936. __extends(BrickProceduralTexture, _super);
  17937. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17938. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17939. this._numberOfBricksHeight = 15;
  17940. this._numberOfBricksWidth = 5;
  17941. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17942. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17943. this.updateShaderUniforms();
  17944. this.refreshRate = 0;
  17945. }
  17946. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17947. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17948. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17949. this.setColor3("brickColor", this._brickColor);
  17950. this.setColor3("jointColor", this._jointColor);
  17951. };
  17952. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17953. get: function () {
  17954. return this._numberOfBricksHeight;
  17955. },
  17956. set: function (value) {
  17957. this._numberOfBricksHeight = value;
  17958. this.updateShaderUniforms();
  17959. },
  17960. enumerable: true,
  17961. configurable: true
  17962. });
  17963. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17964. get: function () {
  17965. return this._numberOfBricksWidth;
  17966. },
  17967. set: function (value) {
  17968. this._numberOfBricksWidth = value;
  17969. this.updateShaderUniforms();
  17970. },
  17971. enumerable: true,
  17972. configurable: true
  17973. });
  17974. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17975. get: function () {
  17976. return this._jointColor;
  17977. },
  17978. set: function (value) {
  17979. this._jointColor = value;
  17980. this.updateShaderUniforms();
  17981. },
  17982. enumerable: true,
  17983. configurable: true
  17984. });
  17985. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17986. get: function () {
  17987. return this._brickColor;
  17988. },
  17989. set: function (value) {
  17990. this._brickColor = value;
  17991. this.updateShaderUniforms();
  17992. },
  17993. enumerable: true,
  17994. configurable: true
  17995. });
  17996. return BrickProceduralTexture;
  17997. })(BABYLON.ProceduralTexture);
  17998. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17999. var MarbleProceduralTexture = (function (_super) {
  18000. __extends(MarbleProceduralTexture, _super);
  18001. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18002. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  18003. this._numberOfTilesHeight = 3;
  18004. this._numberOfTilesWidth = 3;
  18005. this._amplitude = 9.0;
  18006. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  18007. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  18008. this.updateShaderUniforms();
  18009. this.refreshRate = 0;
  18010. }
  18011. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  18012. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  18013. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  18014. this.setFloat("amplitude", this._amplitude);
  18015. this.setColor3("marbleColor", this._marbleColor);
  18016. this.setColor3("jointColor", this._jointColor);
  18017. };
  18018. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  18019. get: function () {
  18020. return this._numberOfTilesHeight;
  18021. },
  18022. set: function (value) {
  18023. this._numberOfTilesHeight = value;
  18024. this.updateShaderUniforms();
  18025. },
  18026. enumerable: true,
  18027. configurable: true
  18028. });
  18029. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  18030. get: function () {
  18031. return this._numberOfTilesWidth;
  18032. },
  18033. set: function (value) {
  18034. this._numberOfTilesWidth = value;
  18035. this.updateShaderUniforms();
  18036. },
  18037. enumerable: true,
  18038. configurable: true
  18039. });
  18040. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  18041. get: function () {
  18042. return this._jointColor;
  18043. },
  18044. set: function (value) {
  18045. this._jointColor = value;
  18046. this.updateShaderUniforms();
  18047. },
  18048. enumerable: true,
  18049. configurable: true
  18050. });
  18051. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  18052. get: function () {
  18053. return this._marbleColor;
  18054. },
  18055. set: function (value) {
  18056. this._marbleColor = value;
  18057. this.updateShaderUniforms();
  18058. },
  18059. enumerable: true,
  18060. configurable: true
  18061. });
  18062. return MarbleProceduralTexture;
  18063. })(BABYLON.ProceduralTexture);
  18064. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  18065. })(BABYLON || (BABYLON = {}));
  18066. var BABYLON;
  18067. (function (BABYLON) {
  18068. var EffectFallbacks = (function () {
  18069. function EffectFallbacks() {
  18070. this._defines = {};
  18071. this._currentRank = 32;
  18072. this._maxRank = -1;
  18073. }
  18074. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18075. if (!this._defines[rank]) {
  18076. if (rank < this._currentRank) {
  18077. this._currentRank = rank;
  18078. }
  18079. if (rank > this._maxRank) {
  18080. this._maxRank = rank;
  18081. }
  18082. this._defines[rank] = new Array();
  18083. }
  18084. this._defines[rank].push(define);
  18085. };
  18086. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18087. get: function () {
  18088. return this._currentRank <= this._maxRank;
  18089. },
  18090. enumerable: true,
  18091. configurable: true
  18092. });
  18093. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18094. var currentFallbacks = this._defines[this._currentRank];
  18095. for (var index = 0; index < currentFallbacks.length; index++) {
  18096. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18097. }
  18098. this._currentRank++;
  18099. return currentDefines;
  18100. };
  18101. return EffectFallbacks;
  18102. })();
  18103. BABYLON.EffectFallbacks = EffectFallbacks;
  18104. var Effect = (function () {
  18105. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18106. var _this = this;
  18107. this._isReady = false;
  18108. this._compilationError = "";
  18109. this._valueCache = [];
  18110. this._engine = engine;
  18111. this.name = baseName;
  18112. this.defines = defines;
  18113. this._uniformsNames = uniformsNames.concat(samplers);
  18114. this._samplers = samplers;
  18115. this._attributesNames = attributesNames;
  18116. this.onError = onError;
  18117. this.onCompiled = onCompiled;
  18118. var vertexSource;
  18119. var fragmentSource;
  18120. if (baseName.vertexElement) {
  18121. vertexSource = document.getElementById(baseName.vertexElement);
  18122. if (!vertexSource) {
  18123. vertexSource = baseName.vertexElement;
  18124. }
  18125. }
  18126. else {
  18127. vertexSource = baseName.vertex || baseName;
  18128. }
  18129. if (baseName.fragmentElement) {
  18130. fragmentSource = document.getElementById(baseName.fragmentElement);
  18131. if (!fragmentSource) {
  18132. fragmentSource = baseName.fragmentElement;
  18133. }
  18134. }
  18135. else {
  18136. fragmentSource = baseName.fragment || baseName;
  18137. }
  18138. this._loadVertexShader(vertexSource, function (vertexCode) {
  18139. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18140. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18141. });
  18142. });
  18143. }
  18144. // Properties
  18145. Effect.prototype.isReady = function () {
  18146. return this._isReady;
  18147. };
  18148. Effect.prototype.getProgram = function () {
  18149. return this._program;
  18150. };
  18151. Effect.prototype.getAttributesNames = function () {
  18152. return this._attributesNames;
  18153. };
  18154. Effect.prototype.getAttributeLocation = function (index) {
  18155. return this._attributes[index];
  18156. };
  18157. Effect.prototype.getAttributeLocationByName = function (name) {
  18158. var index = this._attributesNames.indexOf(name);
  18159. return this._attributes[index];
  18160. };
  18161. Effect.prototype.getAttributesCount = function () {
  18162. return this._attributes.length;
  18163. };
  18164. Effect.prototype.getUniformIndex = function (uniformName) {
  18165. return this._uniformsNames.indexOf(uniformName);
  18166. };
  18167. Effect.prototype.getUniform = function (uniformName) {
  18168. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18169. };
  18170. Effect.prototype.getSamplers = function () {
  18171. return this._samplers;
  18172. };
  18173. Effect.prototype.getCompilationError = function () {
  18174. return this._compilationError;
  18175. };
  18176. // Methods
  18177. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18178. // DOM element ?
  18179. if (vertex instanceof HTMLElement) {
  18180. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18181. callback(vertexCode);
  18182. return;
  18183. }
  18184. // Is in local store ?
  18185. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18186. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18187. return;
  18188. }
  18189. var vertexShaderUrl;
  18190. if (vertex[0] === "." || vertex[0] === "/") {
  18191. vertexShaderUrl = vertex;
  18192. }
  18193. else {
  18194. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18195. }
  18196. // Vertex shader
  18197. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18198. };
  18199. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18200. // DOM element ?
  18201. if (fragment instanceof HTMLElement) {
  18202. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18203. callback(fragmentCode);
  18204. return;
  18205. }
  18206. // Is in local store ?
  18207. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18208. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18209. return;
  18210. }
  18211. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18212. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18213. return;
  18214. }
  18215. var fragmentShaderUrl;
  18216. if (fragment[0] === "." || fragment[0] === "/") {
  18217. fragmentShaderUrl = fragment;
  18218. }
  18219. else {
  18220. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18221. }
  18222. // Fragment shader
  18223. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18224. };
  18225. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18226. try {
  18227. var engine = this._engine;
  18228. if (!engine.getCaps().highPrecisionShaderSupported) {
  18229. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18230. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18231. }
  18232. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18233. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18234. this._attributes = engine.getAttributes(this._program, attributesNames);
  18235. for (var index = 0; index < this._samplers.length; index++) {
  18236. var sampler = this.getUniform(this._samplers[index]);
  18237. if (sampler == null) {
  18238. this._samplers.splice(index, 1);
  18239. index--;
  18240. }
  18241. }
  18242. engine.bindSamplers(this);
  18243. this._isReady = true;
  18244. if (this.onCompiled) {
  18245. this.onCompiled(this);
  18246. }
  18247. }
  18248. catch (e) {
  18249. // Is it a problem with precision?
  18250. if (e.message.indexOf("highp") !== -1) {
  18251. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18252. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18253. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18254. return;
  18255. }
  18256. // Let's go through fallbacks then
  18257. if (fallbacks && fallbacks.isMoreFallbacks) {
  18258. defines = fallbacks.reduce(defines);
  18259. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18260. }
  18261. else {
  18262. BABYLON.Tools.Error("Unable to compile effect: ");
  18263. if (this.name.vertexElement) {
  18264. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18265. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18266. }
  18267. else if (this.name.vertex) {
  18268. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18269. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18270. }
  18271. else {
  18272. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18273. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18274. }
  18275. BABYLON.Tools.Error("Defines: " + defines);
  18276. BABYLON.Tools.Error("Error: " + e.message);
  18277. this._compilationError = e.message;
  18278. if (this.onError) {
  18279. this.onError(this, this._compilationError);
  18280. }
  18281. }
  18282. }
  18283. };
  18284. Effect.prototype._bindTexture = function (channel, texture) {
  18285. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18286. };
  18287. Effect.prototype.setTexture = function (channel, texture) {
  18288. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18289. };
  18290. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18291. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18292. };
  18293. //public _cacheMatrix(uniformName, matrix) {
  18294. // if (!this._valueCache[uniformName]) {
  18295. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18296. // }
  18297. // for (var index = 0; index < 16; index++) {
  18298. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18299. // }
  18300. //};
  18301. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18302. if (!this._valueCache[uniformName]) {
  18303. this._valueCache[uniformName] = [x, y];
  18304. return;
  18305. }
  18306. this._valueCache[uniformName][0] = x;
  18307. this._valueCache[uniformName][1] = y;
  18308. };
  18309. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18310. if (!this._valueCache[uniformName]) {
  18311. this._valueCache[uniformName] = [x, y, z];
  18312. return;
  18313. }
  18314. this._valueCache[uniformName][0] = x;
  18315. this._valueCache[uniformName][1] = y;
  18316. this._valueCache[uniformName][2] = z;
  18317. };
  18318. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18319. if (!this._valueCache[uniformName]) {
  18320. this._valueCache[uniformName] = [x, y, z, w];
  18321. return;
  18322. }
  18323. this._valueCache[uniformName][0] = x;
  18324. this._valueCache[uniformName][1] = y;
  18325. this._valueCache[uniformName][2] = z;
  18326. this._valueCache[uniformName][3] = w;
  18327. };
  18328. Effect.prototype.setArray = function (uniformName, array) {
  18329. this._engine.setArray(this.getUniform(uniformName), array);
  18330. return this;
  18331. };
  18332. Effect.prototype.setArray2 = function (uniformName, array) {
  18333. this._engine.setArray2(this.getUniform(uniformName), array);
  18334. return this;
  18335. };
  18336. Effect.prototype.setArray3 = function (uniformName, array) {
  18337. this._engine.setArray3(this.getUniform(uniformName), array);
  18338. return this;
  18339. };
  18340. Effect.prototype.setArray4 = function (uniformName, array) {
  18341. this._engine.setArray4(this.getUniform(uniformName), array);
  18342. return this;
  18343. };
  18344. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18345. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18346. return this;
  18347. };
  18348. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18349. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18350. // return;
  18351. //this._cacheMatrix(uniformName, matrix);
  18352. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18353. return this;
  18354. };
  18355. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18356. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18357. return this;
  18358. };
  18359. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18360. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18361. return this;
  18362. };
  18363. Effect.prototype.setFloat = function (uniformName, value) {
  18364. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18365. return this;
  18366. this._valueCache[uniformName] = value;
  18367. this._engine.setFloat(this.getUniform(uniformName), value);
  18368. return this;
  18369. };
  18370. Effect.prototype.setBool = function (uniformName, bool) {
  18371. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18372. return this;
  18373. this._valueCache[uniformName] = bool;
  18374. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18375. return this;
  18376. };
  18377. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18378. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18379. return this;
  18380. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18381. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18382. return this;
  18383. };
  18384. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18385. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18386. return this;
  18387. this._cacheFloat2(uniformName, x, y);
  18388. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18389. return this;
  18390. };
  18391. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18392. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18393. return this;
  18394. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18395. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18396. return this;
  18397. };
  18398. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18399. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18400. return this;
  18401. this._cacheFloat3(uniformName, x, y, z);
  18402. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18403. return this;
  18404. };
  18405. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18406. 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)
  18407. return this;
  18408. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18409. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18410. return this;
  18411. };
  18412. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18413. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18414. return this;
  18415. this._cacheFloat4(uniformName, x, y, z, w);
  18416. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18417. return this;
  18418. };
  18419. Effect.prototype.setColor3 = function (uniformName, color3) {
  18420. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18421. return this;
  18422. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18423. this._engine.setColor3(this.getUniform(uniformName), color3);
  18424. return this;
  18425. };
  18426. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18427. 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)
  18428. return this;
  18429. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18430. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18431. return this;
  18432. };
  18433. // Statics
  18434. Effect.ShadersStore = {};
  18435. return Effect;
  18436. })();
  18437. BABYLON.Effect = Effect;
  18438. })(BABYLON || (BABYLON = {}));
  18439. var BABYLON;
  18440. (function (BABYLON) {
  18441. var Material = (function () {
  18442. function Material(name, scene, doNotAdd) {
  18443. this.name = name;
  18444. this.checkReadyOnEveryCall = true;
  18445. this.checkReadyOnlyOnce = false;
  18446. this.state = "";
  18447. this.alpha = 1.0;
  18448. this.backFaceCulling = true;
  18449. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18450. this.disableDepthWrite = false;
  18451. this._wasPreviouslyReady = false;
  18452. this._fillMode = Material.TriangleFillMode;
  18453. this.pointSize = 1.0;
  18454. this.zOffset = 0;
  18455. this.id = name;
  18456. this._scene = scene;
  18457. if (!doNotAdd) {
  18458. scene.materials.push(this);
  18459. }
  18460. }
  18461. Object.defineProperty(Material, "TriangleFillMode", {
  18462. get: function () {
  18463. return Material._TriangleFillMode;
  18464. },
  18465. enumerable: true,
  18466. configurable: true
  18467. });
  18468. Object.defineProperty(Material, "WireFrameFillMode", {
  18469. get: function () {
  18470. return Material._WireFrameFillMode;
  18471. },
  18472. enumerable: true,
  18473. configurable: true
  18474. });
  18475. Object.defineProperty(Material, "PointFillMode", {
  18476. get: function () {
  18477. return Material._PointFillMode;
  18478. },
  18479. enumerable: true,
  18480. configurable: true
  18481. });
  18482. Object.defineProperty(Material.prototype, "wireframe", {
  18483. get: function () {
  18484. return this._fillMode === Material.WireFrameFillMode;
  18485. },
  18486. set: function (value) {
  18487. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. Object.defineProperty(Material.prototype, "pointsCloud", {
  18493. get: function () {
  18494. return this._fillMode === Material.PointFillMode;
  18495. },
  18496. set: function (value) {
  18497. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18498. },
  18499. enumerable: true,
  18500. configurable: true
  18501. });
  18502. Object.defineProperty(Material.prototype, "fillMode", {
  18503. get: function () {
  18504. return this._fillMode;
  18505. },
  18506. set: function (value) {
  18507. this._fillMode = value;
  18508. },
  18509. enumerable: true,
  18510. configurable: true
  18511. });
  18512. Material.prototype.isReady = function (mesh, useInstances) {
  18513. return true;
  18514. };
  18515. Material.prototype.getEffect = function () {
  18516. return this._effect;
  18517. };
  18518. Material.prototype.getScene = function () {
  18519. return this._scene;
  18520. };
  18521. Material.prototype.needAlphaBlending = function () {
  18522. return (this.alpha < 1.0);
  18523. };
  18524. Material.prototype.needAlphaTesting = function () {
  18525. return false;
  18526. };
  18527. Material.prototype.getAlphaTestTexture = function () {
  18528. return null;
  18529. };
  18530. Material.prototype.trackCreation = function (onCompiled, onError) {
  18531. };
  18532. Material.prototype._preBind = function () {
  18533. var engine = this._scene.getEngine();
  18534. engine.enableEffect(this._effect);
  18535. engine.setState(this.backFaceCulling, this.zOffset);
  18536. };
  18537. Material.prototype.bind = function (world, mesh) {
  18538. this._scene._cachedMaterial = this;
  18539. if (this.onBind) {
  18540. this.onBind(this, mesh);
  18541. }
  18542. if (this.disableDepthWrite) {
  18543. var engine = this._scene.getEngine();
  18544. this._cachedDepthWriteState = engine.getDepthWrite();
  18545. engine.setDepthWrite(false);
  18546. }
  18547. };
  18548. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18549. };
  18550. Material.prototype.unbind = function () {
  18551. if (this.disableDepthWrite) {
  18552. var engine = this._scene.getEngine();
  18553. engine.setDepthWrite(this._cachedDepthWriteState);
  18554. }
  18555. };
  18556. Material.prototype.clone = function (name) {
  18557. return null;
  18558. };
  18559. Material.prototype.dispose = function (forceDisposeEffect) {
  18560. // Remove from scene
  18561. var index = this._scene.materials.indexOf(this);
  18562. this._scene.materials.splice(index, 1);
  18563. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18564. if (forceDisposeEffect && this._effect) {
  18565. this._scene.getEngine()._releaseEffect(this._effect);
  18566. this._effect = null;
  18567. }
  18568. // Callback
  18569. if (this.onDispose) {
  18570. this.onDispose();
  18571. }
  18572. };
  18573. Material._TriangleFillMode = 0;
  18574. Material._WireFrameFillMode = 1;
  18575. Material._PointFillMode = 2;
  18576. return Material;
  18577. })();
  18578. BABYLON.Material = Material;
  18579. })(BABYLON || (BABYLON = {}));
  18580. var BABYLON;
  18581. (function (BABYLON) {
  18582. var maxSimultaneousLights = 4;
  18583. var FresnelParameters = (function () {
  18584. function FresnelParameters() {
  18585. this.isEnabled = true;
  18586. this.leftColor = BABYLON.Color3.White();
  18587. this.rightColor = BABYLON.Color3.Black();
  18588. this.bias = 0;
  18589. this.power = 1;
  18590. }
  18591. return FresnelParameters;
  18592. })();
  18593. BABYLON.FresnelParameters = FresnelParameters;
  18594. var StandardMaterialDefines = (function () {
  18595. function StandardMaterialDefines() {
  18596. this.DIFFUSE = false;
  18597. this.AMBIENT = false;
  18598. this.OPACITY = false;
  18599. this.OPACITYRGB = false;
  18600. this.REFLECTION = false;
  18601. this.EMISSIVE = false;
  18602. this.SPECULAR = false;
  18603. this.BUMP = false;
  18604. this.SPECULAROVERALPHA = false;
  18605. this.CLIPPLANE = false;
  18606. this.ALPHATEST = false;
  18607. this.ALPHAFROMDIFFUSE = false;
  18608. this.POINTSIZE = false;
  18609. this.FOG = false;
  18610. this.LIGHT0 = false;
  18611. this.LIGHT1 = false;
  18612. this.LIGHT2 = false;
  18613. this.LIGHT3 = false;
  18614. this.SPOTLIGHT0 = false;
  18615. this.SPOTLIGHT1 = false;
  18616. this.SPOTLIGHT2 = false;
  18617. this.SPOTLIGHT3 = false;
  18618. this.HEMILIGHT0 = false;
  18619. this.HEMILIGHT1 = false;
  18620. this.HEMILIGHT2 = false;
  18621. this.HEMILIGHT3 = false;
  18622. this.POINTDIRLIGHT0 = false;
  18623. this.POINTDIRLIGHT1 = false;
  18624. this.POINTDIRLIGHT2 = false;
  18625. this.POINTDIRLIGHT3 = false;
  18626. this.SPECULARTERM = false;
  18627. this.SHADOW0 = false;
  18628. this.SHADOW1 = false;
  18629. this.SHADOW2 = false;
  18630. this.SHADOW3 = false;
  18631. this.SHADOWS = false;
  18632. this.SHADOWVSM0 = false;
  18633. this.SHADOWVSM1 = false;
  18634. this.SHADOWVSM2 = false;
  18635. this.SHADOWVSM3 = false;
  18636. this.SHADOWPCF0 = false;
  18637. this.SHADOWPCF1 = false;
  18638. this.SHADOWPCF2 = false;
  18639. this.SHADOWPCF3 = false;
  18640. this.DIFFUSEFRESNEL = false;
  18641. this.OPACITYFRESNEL = false;
  18642. this.REFLECTIONFRESNEL = false;
  18643. this.EMISSIVEFRESNEL = false;
  18644. this.FRESNEL = false;
  18645. this.NORMAL = false;
  18646. this.UV1 = false;
  18647. this.UV2 = false;
  18648. this.VERTEXCOLOR = false;
  18649. this.VERTEXALPHA = false;
  18650. this.BONES = false;
  18651. this.BONES4 = false;
  18652. this.BonesPerMesh = 0;
  18653. this.INSTANCES = false;
  18654. this.GLOSSINESS = false;
  18655. this.ROUGHNESS = false;
  18656. this.EMISSIVEASILLUMINATION = false;
  18657. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18658. this._keys = Object.keys(this);
  18659. }
  18660. StandardMaterialDefines.prototype.isEqual = function (other) {
  18661. for (var index = 0; index < this._keys.length; index++) {
  18662. var prop = this._keys[index];
  18663. if (this[prop] !== other[prop]) {
  18664. return false;
  18665. }
  18666. }
  18667. return true;
  18668. };
  18669. StandardMaterialDefines.prototype.cloneTo = function (other) {
  18670. for (var index = 0; index < this._keys.length; index++) {
  18671. var prop = this._keys[index];
  18672. other[prop] = this[prop];
  18673. }
  18674. };
  18675. StandardMaterialDefines.prototype.reset = function () {
  18676. for (var index = 0; index < this._keys.length; index++) {
  18677. var prop = this._keys[index];
  18678. if (prop === "BonesPerMesh") {
  18679. this[prop] = 0;
  18680. continue;
  18681. }
  18682. this[prop] = false;
  18683. }
  18684. };
  18685. StandardMaterialDefines.prototype.toString = function () {
  18686. var result = "";
  18687. for (var index = 0; index < this._keys.length; index++) {
  18688. var prop = this._keys[index];
  18689. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18690. result += "#define BonesPerMesh " + this[prop] + "\n";
  18691. continue;
  18692. }
  18693. if (this[prop]) {
  18694. result += "#define " + prop + "\n";
  18695. }
  18696. }
  18697. return result;
  18698. };
  18699. return StandardMaterialDefines;
  18700. })();
  18701. var StandardMaterial = (function (_super) {
  18702. __extends(StandardMaterial, _super);
  18703. function StandardMaterial(name, scene) {
  18704. var _this = this;
  18705. _super.call(this, name, scene);
  18706. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18707. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18708. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18709. this.specularPower = 64;
  18710. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18711. this.useAlphaFromDiffuseTexture = false;
  18712. this.useEmissiveAsIllumination = false;
  18713. this.useReflectionFresnelFromSpecular = false;
  18714. this.useSpecularOverAlpha = true;
  18715. this.fogEnabled = true;
  18716. this.roughness = 0;
  18717. this.useGlossinessFromSpecularMapAlpha = false;
  18718. this._renderTargets = new BABYLON.SmartArray(16);
  18719. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18720. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18721. this._scaledDiffuse = new BABYLON.Color3();
  18722. this._scaledSpecular = new BABYLON.Color3();
  18723. this._defines = new StandardMaterialDefines();
  18724. this._cachedDefines = new StandardMaterialDefines();
  18725. this._cachedDefines.BonesPerMesh = -1;
  18726. this.getRenderTargetTextures = function () {
  18727. _this._renderTargets.reset();
  18728. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18729. _this._renderTargets.push(_this.reflectionTexture);
  18730. }
  18731. return _this._renderTargets;
  18732. };
  18733. }
  18734. StandardMaterial.prototype.needAlphaBlending = function () {
  18735. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18736. };
  18737. StandardMaterial.prototype.needAlphaTesting = function () {
  18738. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18739. };
  18740. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18741. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18742. };
  18743. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18744. return this.diffuseTexture;
  18745. };
  18746. // Methods
  18747. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18748. if (this.checkReadyOnlyOnce) {
  18749. if (this._wasPreviouslyReady) {
  18750. return true;
  18751. }
  18752. }
  18753. var scene = this.getScene();
  18754. if (!this.checkReadyOnEveryCall) {
  18755. if (this._renderId === scene.getRenderId()) {
  18756. return true;
  18757. }
  18758. }
  18759. var engine = scene.getEngine();
  18760. var needNormals = false;
  18761. var needUVs = false;
  18762. this._defines.reset();
  18763. // Textures
  18764. if (scene.texturesEnabled) {
  18765. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18766. if (!this.diffuseTexture.isReady()) {
  18767. return false;
  18768. }
  18769. else {
  18770. needUVs = true;
  18771. this._defines.DIFFUSE = true;
  18772. }
  18773. }
  18774. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18775. if (!this.ambientTexture.isReady()) {
  18776. return false;
  18777. }
  18778. else {
  18779. needUVs = true;
  18780. this._defines.AMBIENT = true;
  18781. }
  18782. }
  18783. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18784. if (!this.opacityTexture.isReady()) {
  18785. return false;
  18786. }
  18787. else {
  18788. needUVs = true;
  18789. this._defines.OPACITY = true;
  18790. if (this.opacityTexture.getAlphaFromRGB) {
  18791. this._defines.OPACITYRGB = true;
  18792. }
  18793. }
  18794. }
  18795. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18796. if (!this.reflectionTexture.isReady()) {
  18797. return false;
  18798. }
  18799. else {
  18800. needNormals = true;
  18801. needUVs = true;
  18802. this._defines.REFLECTION = true;
  18803. if (this.roughness > 0) {
  18804. this._defines.ROUGHNESS = true;
  18805. }
  18806. }
  18807. }
  18808. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18809. if (!this.emissiveTexture.isReady()) {
  18810. return false;
  18811. }
  18812. else {
  18813. needUVs = true;
  18814. this._defines.EMISSIVE = true;
  18815. }
  18816. }
  18817. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18818. if (!this.specularTexture.isReady()) {
  18819. return false;
  18820. }
  18821. else {
  18822. needUVs = true;
  18823. this._defines.SPECULAR = true;
  18824. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18825. }
  18826. }
  18827. }
  18828. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18829. if (!this.bumpTexture.isReady()) {
  18830. return false;
  18831. }
  18832. else {
  18833. needUVs = true;
  18834. this._defines.BUMP = true;
  18835. }
  18836. }
  18837. // Effect
  18838. if (scene.clipPlane) {
  18839. this._defines.CLIPPLANE = true;
  18840. }
  18841. if (engine.getAlphaTesting()) {
  18842. this._defines.ALPHATEST = true;
  18843. }
  18844. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18845. this._defines.ALPHAFROMDIFFUSE = true;
  18846. }
  18847. if (this.useEmissiveAsIllumination) {
  18848. this._defines.EMISSIVEASILLUMINATION = true;
  18849. }
  18850. if (this.useReflectionFresnelFromSpecular) {
  18851. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18852. }
  18853. // Point size
  18854. if (this.pointsCloud || scene.forcePointsCloud) {
  18855. this._defines.POINTSIZE = true;
  18856. }
  18857. // Fog
  18858. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18859. this._defines.FOG = true;
  18860. }
  18861. var lightIndex = 0;
  18862. if (scene.lightsEnabled) {
  18863. for (var index = 0; index < scene.lights.length; index++) {
  18864. var light = scene.lights[index];
  18865. if (!light.isEnabled()) {
  18866. continue;
  18867. }
  18868. // Excluded check
  18869. if (light._excludedMeshesIds.length > 0) {
  18870. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18871. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18872. if (excludedMesh) {
  18873. light.excludedMeshes.push(excludedMesh);
  18874. }
  18875. }
  18876. light._excludedMeshesIds = [];
  18877. }
  18878. // Included check
  18879. if (light._includedOnlyMeshesIds.length > 0) {
  18880. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18881. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18882. if (includedOnlyMesh) {
  18883. light.includedOnlyMeshes.push(includedOnlyMesh);
  18884. }
  18885. }
  18886. light._includedOnlyMeshesIds = [];
  18887. }
  18888. if (!light.canAffectMesh(mesh)) {
  18889. continue;
  18890. }
  18891. needNormals = true;
  18892. this._defines["LIGHT" + lightIndex] = true;
  18893. var type;
  18894. if (light instanceof BABYLON.SpotLight) {
  18895. type = "SPOTLIGHT" + lightIndex;
  18896. }
  18897. else if (light instanceof BABYLON.HemisphericLight) {
  18898. type = "HEMILIGHT" + lightIndex;
  18899. }
  18900. else {
  18901. type = "POINTDIRLIGHT" + lightIndex;
  18902. }
  18903. this._defines[type] = true;
  18904. // Specular
  18905. if (!light.specular.equalsFloats(0, 0, 0)) {
  18906. this._defines.SPECULARTERM = true;
  18907. }
  18908. // Shadows
  18909. if (scene.shadowsEnabled) {
  18910. var shadowGenerator = light.getShadowGenerator();
  18911. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18912. this._defines["SHADOW" + lightIndex] = true;
  18913. this._defines.SHADOWS = true;
  18914. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18915. this._defines["SHADOWVSM" + lightIndex] = true;
  18916. }
  18917. if (shadowGenerator.usePoissonSampling) {
  18918. this._defines["SHADOWPCF" + lightIndex] = true;
  18919. }
  18920. }
  18921. }
  18922. lightIndex++;
  18923. if (lightIndex === maxSimultaneousLights)
  18924. break;
  18925. }
  18926. }
  18927. if (StandardMaterial.FresnelEnabled) {
  18928. // Fresnel
  18929. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18930. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18931. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18932. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18933. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18934. this._defines.DIFFUSEFRESNEL = true;
  18935. }
  18936. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18937. this._defines.OPACITYFRESNEL = true;
  18938. }
  18939. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18940. this._defines.REFLECTIONFRESNEL = true;
  18941. }
  18942. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18943. this._defines.EMISSIVEFRESNEL = true;
  18944. }
  18945. needNormals = true;
  18946. this._defines.FRESNEL = true;
  18947. }
  18948. }
  18949. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18950. this._defines.SPECULAROVERALPHA = true;
  18951. }
  18952. // Attribs
  18953. if (mesh) {
  18954. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18955. this._defines.NORMAL = true;
  18956. }
  18957. if (needUVs) {
  18958. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18959. this._defines.UV1 = true;
  18960. }
  18961. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18962. this._defines.UV2 = true;
  18963. }
  18964. }
  18965. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18966. this._defines.VERTEXCOLOR = true;
  18967. if (mesh.hasVertexAlpha) {
  18968. this._defines.VERTEXALPHA = true;
  18969. }
  18970. }
  18971. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18972. this._defines.BONES = true;
  18973. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18974. this._defines.BONES4 = true;
  18975. }
  18976. // Instances
  18977. if (useInstances) {
  18978. this._defines.INSTANCES = true;
  18979. }
  18980. }
  18981. // Get correct effect
  18982. if (!this._defines.isEqual(this._cachedDefines)) {
  18983. this._defines.cloneTo(this._cachedDefines);
  18984. scene.resetCachedMaterial();
  18985. // Fallbacks
  18986. var fallbacks = new BABYLON.EffectFallbacks();
  18987. if (this._defines.REFLECTION) {
  18988. fallbacks.addFallback(0, "REFLECTION");
  18989. }
  18990. if (this._defines.SPECULAR) {
  18991. fallbacks.addFallback(0, "SPECULAR");
  18992. }
  18993. if (this._defines.BUMP) {
  18994. fallbacks.addFallback(0, "BUMP");
  18995. }
  18996. if (this._defines.SPECULAROVERALPHA) {
  18997. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18998. }
  18999. if (this._defines.FOG) {
  19000. fallbacks.addFallback(1, "FOG");
  19001. }
  19002. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19003. if (!this._defines["LIGHT" + lightIndex]) {
  19004. continue;
  19005. }
  19006. if (lightIndex > 0) {
  19007. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19008. }
  19009. if (this._defines["SHADOW" + lightIndex]) {
  19010. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19011. }
  19012. if (this._defines["SHADOWPCF" + lightIndex]) {
  19013. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19014. }
  19015. if (this._defines["SHADOWVSM" + lightIndex]) {
  19016. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19017. }
  19018. }
  19019. if (this._defines.SPECULARTERM) {
  19020. fallbacks.addFallback(0, "SPECULARTERM");
  19021. }
  19022. if (this._defines.DIFFUSEFRESNEL) {
  19023. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19024. }
  19025. if (this._defines.OPACITYFRESNEL) {
  19026. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19027. }
  19028. if (this._defines.REFLECTIONFRESNEL) {
  19029. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19030. }
  19031. if (this._defines.EMISSIVEFRESNEL) {
  19032. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19033. }
  19034. if (this._defines.FRESNEL) {
  19035. fallbacks.addFallback(4, "FRESNEL");
  19036. }
  19037. if (this._defines.BONES4) {
  19038. fallbacks.addFallback(0, "BONES4");
  19039. }
  19040. //Attributes
  19041. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19042. if (this._defines.NORMAL) {
  19043. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19044. }
  19045. if (this._defines.UV1) {
  19046. attribs.push(BABYLON.VertexBuffer.UVKind);
  19047. }
  19048. if (this._defines.UV2) {
  19049. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19050. }
  19051. if (this._defines.VERTEXCOLOR) {
  19052. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19053. }
  19054. if (this._defines.BONES) {
  19055. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19056. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19057. }
  19058. if (this._defines.INSTANCES) {
  19059. attribs.push("world0");
  19060. attribs.push("world1");
  19061. attribs.push("world2");
  19062. attribs.push("world3");
  19063. }
  19064. // Legacy browser patch
  19065. var shaderName = "default";
  19066. if (!scene.getEngine().getCaps().standardDerivatives) {
  19067. shaderName = "legacydefault";
  19068. }
  19069. var join = this._defines.toString();
  19070. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19071. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19072. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19073. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19074. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19075. "vFogInfos", "vFogColor", "pointSize",
  19076. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  19077. "mBones",
  19078. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  19079. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19080. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19081. "roughness"
  19082. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  19083. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19084. ], join, fallbacks, this.onCompiled, this.onError);
  19085. }
  19086. if (!this._effect.isReady()) {
  19087. return false;
  19088. }
  19089. this._renderId = scene.getRenderId();
  19090. this._wasPreviouslyReady = true;
  19091. return true;
  19092. };
  19093. StandardMaterial.prototype.unbind = function () {
  19094. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19095. this._effect.setTexture("reflection2DSampler", null);
  19096. }
  19097. _super.prototype.unbind.call(this);
  19098. };
  19099. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19100. this._effect.setMatrix("world", world);
  19101. };
  19102. StandardMaterial.prototype.bind = function (world, mesh) {
  19103. var scene = this.getScene();
  19104. // Matrices
  19105. this.bindOnlyWorldMatrix(world);
  19106. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19107. // Bones
  19108. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19109. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19110. }
  19111. if (scene.getCachedMaterial() !== this) {
  19112. if (StandardMaterial.FresnelEnabled) {
  19113. // Fresnel
  19114. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19115. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19116. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19117. }
  19118. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19119. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19120. }
  19121. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19122. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19123. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19124. }
  19125. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19126. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19127. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19128. }
  19129. }
  19130. // Textures
  19131. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19132. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19133. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19134. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19135. }
  19136. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19137. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19138. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19139. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19140. }
  19141. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19142. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19143. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19144. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19145. }
  19146. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19147. if (this.reflectionTexture.isCube) {
  19148. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19149. if (this._defines.ROUGHNESS) {
  19150. this._effect.setFloat("roughness", this.roughness);
  19151. }
  19152. }
  19153. else {
  19154. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19155. }
  19156. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19157. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  19158. }
  19159. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19160. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19161. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19162. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19163. }
  19164. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19165. this._effect.setTexture("specularSampler", this.specularTexture);
  19166. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19167. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19168. }
  19169. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19170. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19171. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19172. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19173. }
  19174. // Clip plane
  19175. if (scene.clipPlane) {
  19176. var clipPlane = scene.clipPlane;
  19177. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19178. }
  19179. // Point size
  19180. if (this.pointsCloud) {
  19181. this._effect.setFloat("pointSize", this.pointSize);
  19182. }
  19183. // Colors
  19184. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19185. // Scaling down color according to emissive
  19186. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19187. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19188. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19189. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  19190. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19191. if (this._defines.SPECULARTERM) {
  19192. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19193. }
  19194. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19195. }
  19196. // Scaling down color according to emissive
  19197. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19198. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19199. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19200. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19201. if (scene.lightsEnabled) {
  19202. var lightIndex = 0;
  19203. for (var index = 0; index < scene.lights.length; index++) {
  19204. var light = scene.lights[index];
  19205. if (!light.isEnabled()) {
  19206. continue;
  19207. }
  19208. if (!light.canAffectMesh(mesh)) {
  19209. continue;
  19210. }
  19211. if (light instanceof BABYLON.PointLight) {
  19212. // Point Light
  19213. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19214. }
  19215. else if (light instanceof BABYLON.DirectionalLight) {
  19216. // Directional Light
  19217. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19218. }
  19219. else if (light instanceof BABYLON.SpotLight) {
  19220. // Spot Light
  19221. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19222. }
  19223. else if (light instanceof BABYLON.HemisphericLight) {
  19224. // Hemispheric Light
  19225. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19226. }
  19227. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19228. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19229. if (this._defines.SPECULARTERM) {
  19230. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19231. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19232. }
  19233. // Shadows
  19234. if (scene.shadowsEnabled) {
  19235. var shadowGenerator = light.getShadowGenerator();
  19236. if (mesh.receiveShadows && shadowGenerator) {
  19237. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19238. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19239. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19240. }
  19241. }
  19242. lightIndex++;
  19243. if (lightIndex === maxSimultaneousLights)
  19244. break;
  19245. }
  19246. }
  19247. // View
  19248. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19249. this._effect.setMatrix("view", scene.getViewMatrix());
  19250. }
  19251. // Fog
  19252. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19253. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19254. this._effect.setColor3("vFogColor", scene.fogColor);
  19255. }
  19256. _super.prototype.bind.call(this, world, mesh);
  19257. };
  19258. StandardMaterial.prototype.getAnimatables = function () {
  19259. var results = [];
  19260. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19261. results.push(this.diffuseTexture);
  19262. }
  19263. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19264. results.push(this.ambientTexture);
  19265. }
  19266. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19267. results.push(this.opacityTexture);
  19268. }
  19269. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19270. results.push(this.reflectionTexture);
  19271. }
  19272. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19273. results.push(this.emissiveTexture);
  19274. }
  19275. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19276. results.push(this.specularTexture);
  19277. }
  19278. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19279. results.push(this.bumpTexture);
  19280. }
  19281. return results;
  19282. };
  19283. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19284. if (this.diffuseTexture) {
  19285. this.diffuseTexture.dispose();
  19286. }
  19287. if (this.ambientTexture) {
  19288. this.ambientTexture.dispose();
  19289. }
  19290. if (this.opacityTexture) {
  19291. this.opacityTexture.dispose();
  19292. }
  19293. if (this.reflectionTexture) {
  19294. this.reflectionTexture.dispose();
  19295. }
  19296. if (this.emissiveTexture) {
  19297. this.emissiveTexture.dispose();
  19298. }
  19299. if (this.specularTexture) {
  19300. this.specularTexture.dispose();
  19301. }
  19302. if (this.bumpTexture) {
  19303. this.bumpTexture.dispose();
  19304. }
  19305. _super.prototype.dispose.call(this, forceDisposeEffect);
  19306. };
  19307. StandardMaterial.prototype.clone = function (name) {
  19308. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19309. // Base material
  19310. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19311. newStandardMaterial.alpha = this.alpha;
  19312. newStandardMaterial.fillMode = this.fillMode;
  19313. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  19314. // Standard material
  19315. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19316. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19317. }
  19318. if (this.ambientTexture && this.ambientTexture.clone) {
  19319. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19320. }
  19321. if (this.opacityTexture && this.opacityTexture.clone) {
  19322. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19323. }
  19324. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19325. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19326. }
  19327. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19328. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19329. }
  19330. if (this.specularTexture && this.specularTexture.clone) {
  19331. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19332. }
  19333. if (this.bumpTexture && this.bumpTexture.clone) {
  19334. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19335. }
  19336. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19337. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19338. newStandardMaterial.specularColor = this.specularColor.clone();
  19339. newStandardMaterial.specularPower = this.specularPower;
  19340. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19341. return newStandardMaterial;
  19342. };
  19343. // Statics
  19344. // Flags used to enable or disable a type of texture for all Standard Materials
  19345. StandardMaterial.DiffuseTextureEnabled = true;
  19346. StandardMaterial.AmbientTextureEnabled = true;
  19347. StandardMaterial.OpacityTextureEnabled = true;
  19348. StandardMaterial.ReflectionTextureEnabled = true;
  19349. StandardMaterial.EmissiveTextureEnabled = true;
  19350. StandardMaterial.SpecularTextureEnabled = true;
  19351. StandardMaterial.BumpTextureEnabled = true;
  19352. StandardMaterial.FresnelEnabled = true;
  19353. return StandardMaterial;
  19354. })(BABYLON.Material);
  19355. BABYLON.StandardMaterial = StandardMaterial;
  19356. })(BABYLON || (BABYLON = {}));
  19357. var BABYLON;
  19358. (function (BABYLON) {
  19359. var MultiMaterial = (function (_super) {
  19360. __extends(MultiMaterial, _super);
  19361. function MultiMaterial(name, scene) {
  19362. _super.call(this, name, scene, true);
  19363. this.subMaterials = new Array();
  19364. scene.multiMaterials.push(this);
  19365. }
  19366. // Properties
  19367. MultiMaterial.prototype.getSubMaterial = function (index) {
  19368. if (index < 0 || index >= this.subMaterials.length) {
  19369. return this.getScene().defaultMaterial;
  19370. }
  19371. return this.subMaterials[index];
  19372. };
  19373. // Methods
  19374. MultiMaterial.prototype.isReady = function (mesh) {
  19375. for (var index = 0; index < this.subMaterials.length; index++) {
  19376. var subMaterial = this.subMaterials[index];
  19377. if (subMaterial) {
  19378. if (!this.subMaterials[index].isReady(mesh)) {
  19379. return false;
  19380. }
  19381. }
  19382. }
  19383. return true;
  19384. };
  19385. MultiMaterial.prototype.clone = function (name) {
  19386. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19387. for (var index = 0; index < this.subMaterials.length; index++) {
  19388. var subMaterial = this.subMaterials[index];
  19389. newMultiMaterial.subMaterials.push(subMaterial);
  19390. }
  19391. return newMultiMaterial;
  19392. };
  19393. return MultiMaterial;
  19394. })(BABYLON.Material);
  19395. BABYLON.MultiMaterial = MultiMaterial;
  19396. })(BABYLON || (BABYLON = {}));
  19397. var BABYLON;
  19398. (function (BABYLON) {
  19399. var SceneLoader = (function () {
  19400. function SceneLoader() {
  19401. }
  19402. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19403. get: function () {
  19404. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19405. },
  19406. set: function (value) {
  19407. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19413. get: function () {
  19414. return SceneLoader._ShowLoadingScreen;
  19415. },
  19416. set: function (value) {
  19417. SceneLoader._ShowLoadingScreen = value;
  19418. },
  19419. enumerable: true,
  19420. configurable: true
  19421. });
  19422. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19423. var dotPosition = sceneFilename.lastIndexOf(".");
  19424. var queryStringPosition = sceneFilename.indexOf("?");
  19425. if (queryStringPosition === -1) {
  19426. queryStringPosition = sceneFilename.length;
  19427. }
  19428. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19429. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19430. var plugin = this._registeredPlugins[index];
  19431. if (plugin.extensions.indexOf(extension) !== -1) {
  19432. return plugin;
  19433. }
  19434. }
  19435. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19436. };
  19437. // Public functions
  19438. SceneLoader.RegisterPlugin = function (plugin) {
  19439. plugin.extensions = plugin.extensions.toLowerCase();
  19440. SceneLoader._registeredPlugins.push(plugin);
  19441. };
  19442. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19443. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19444. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19445. return;
  19446. }
  19447. var loadingToken = {};
  19448. scene._addPendingData(loadingToken);
  19449. var manifestChecked = function (success) {
  19450. scene.database = database;
  19451. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19452. var importMeshFromData = function (data) {
  19453. var meshes = [];
  19454. var particleSystems = [];
  19455. var skeletons = [];
  19456. try {
  19457. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19458. if (onerror) {
  19459. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19460. }
  19461. scene._removePendingData(loadingToken);
  19462. return;
  19463. }
  19464. }
  19465. catch (e) {
  19466. if (onerror) {
  19467. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19468. }
  19469. scene._removePendingData(loadingToken);
  19470. return;
  19471. }
  19472. if (onsuccess) {
  19473. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19474. onsuccess(meshes, particleSystems, skeletons);
  19475. scene._removePendingData(loadingToken);
  19476. }
  19477. };
  19478. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19479. // Direct load
  19480. importMeshFromData(sceneFilename.substr(5));
  19481. return;
  19482. }
  19483. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19484. importMeshFromData(data);
  19485. }, progressCallBack, database);
  19486. };
  19487. if (scene.getEngine().enableOfflineSupport) {
  19488. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19489. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19490. }
  19491. else {
  19492. manifestChecked(true);
  19493. }
  19494. };
  19495. /**
  19496. * Load a scene
  19497. * @param rootUrl a string that defines the root url for scene and resources
  19498. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19499. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19500. */
  19501. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19502. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19503. };
  19504. /**
  19505. * Append a scene
  19506. * @param rootUrl a string that defines the root url for scene and resources
  19507. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19508. * @param scene is the instance of BABYLON.Scene to append to
  19509. */
  19510. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19511. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19512. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19513. return;
  19514. }
  19515. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19516. var database;
  19517. var loadingToken = {};
  19518. scene._addPendingData(loadingToken);
  19519. if (SceneLoader.ShowLoadingScreen) {
  19520. scene.getEngine().displayLoadingUI();
  19521. }
  19522. var loadSceneFromData = function (data) {
  19523. scene.database = database;
  19524. if (!plugin.load(scene, data, rootUrl)) {
  19525. if (onerror) {
  19526. onerror(scene);
  19527. }
  19528. scene._removePendingData(loadingToken);
  19529. scene.getEngine().hideLoadingUI();
  19530. return;
  19531. }
  19532. if (onsuccess) {
  19533. onsuccess(scene);
  19534. }
  19535. scene._removePendingData(loadingToken);
  19536. if (SceneLoader.ShowLoadingScreen) {
  19537. scene.executeWhenReady(function () {
  19538. scene.getEngine().hideLoadingUI();
  19539. });
  19540. }
  19541. };
  19542. var manifestChecked = function (success) {
  19543. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19544. };
  19545. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19546. // Direct load
  19547. loadSceneFromData(sceneFilename.substr(5));
  19548. return;
  19549. }
  19550. if (rootUrl.indexOf("file:") === -1) {
  19551. if (scene.getEngine().enableOfflineSupport) {
  19552. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19553. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19554. }
  19555. else {
  19556. manifestChecked(true);
  19557. }
  19558. }
  19559. else {
  19560. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19561. }
  19562. };
  19563. // Flags
  19564. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19565. SceneLoader._ShowLoadingScreen = true;
  19566. // Members
  19567. SceneLoader._registeredPlugins = new Array();
  19568. return SceneLoader;
  19569. })();
  19570. BABYLON.SceneLoader = SceneLoader;
  19571. ;
  19572. })(BABYLON || (BABYLON = {}));
  19573. var BABYLON;
  19574. (function (BABYLON) {
  19575. var Internals;
  19576. (function (Internals) {
  19577. var checkColors4 = function (colors, count) {
  19578. // Check if color3 was used
  19579. if (colors.length === count * 3) {
  19580. var colors4 = [];
  19581. for (var index = 0; index < colors.length; index += 3) {
  19582. var newIndex = (index / 3) * 4;
  19583. colors4[newIndex] = colors[index];
  19584. colors4[newIndex + 1] = colors[index + 1];
  19585. colors4[newIndex + 2] = colors[index + 2];
  19586. colors4[newIndex + 3] = 1.0;
  19587. }
  19588. return colors4;
  19589. }
  19590. return colors;
  19591. };
  19592. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19593. var texture = null;
  19594. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19595. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19596. texture.name = parsedTexture.name;
  19597. texture.hasAlpha = parsedTexture.hasAlpha;
  19598. texture.level = parsedTexture.level;
  19599. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19600. }
  19601. return texture;
  19602. };
  19603. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19604. if (parsedTexture.isCube) {
  19605. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19606. }
  19607. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19608. return null;
  19609. }
  19610. var texture;
  19611. if (parsedTexture.mirrorPlane) {
  19612. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19613. texture._waitingRenderList = parsedTexture.renderList;
  19614. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19615. }
  19616. else if (parsedTexture.isRenderTarget) {
  19617. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19618. texture._waitingRenderList = parsedTexture.renderList;
  19619. }
  19620. else {
  19621. if (parsedTexture.base64String) {
  19622. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19623. }
  19624. else {
  19625. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19626. }
  19627. }
  19628. texture.name = parsedTexture.name;
  19629. texture.hasAlpha = parsedTexture.hasAlpha;
  19630. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19631. texture.level = parsedTexture.level;
  19632. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19633. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19634. texture.uOffset = parsedTexture.uOffset;
  19635. texture.vOffset = parsedTexture.vOffset;
  19636. texture.uScale = parsedTexture.uScale;
  19637. texture.vScale = parsedTexture.vScale;
  19638. texture.uAng = parsedTexture.uAng;
  19639. texture.vAng = parsedTexture.vAng;
  19640. texture.wAng = parsedTexture.wAng;
  19641. texture.wrapU = parsedTexture.wrapU;
  19642. texture.wrapV = parsedTexture.wrapV;
  19643. // Animations
  19644. if (parsedTexture.animations) {
  19645. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19646. var parsedAnimation = parsedTexture.animations[animationIndex];
  19647. texture.animations.push(parseAnimation(parsedAnimation));
  19648. }
  19649. }
  19650. return texture;
  19651. };
  19652. var parseSkeleton = function (parsedSkeleton, scene) {
  19653. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19654. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19655. var parsedBone = parsedSkeleton.bones[index];
  19656. var parentBone = null;
  19657. if (parsedBone.parentBoneIndex > -1) {
  19658. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19659. }
  19660. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19661. if (parsedBone.animation) {
  19662. bone.animations.push(parseAnimation(parsedBone.animation));
  19663. }
  19664. }
  19665. return skeleton;
  19666. };
  19667. var parseFresnelParameters = function (parsedFresnelParameters) {
  19668. var fresnelParameters = new BABYLON.FresnelParameters();
  19669. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19670. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19671. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19672. fresnelParameters.bias = parsedFresnelParameters.bias;
  19673. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19674. return fresnelParameters;
  19675. };
  19676. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19677. var material;
  19678. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19679. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19680. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19681. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19682. material.specularPower = parsedMaterial.specularPower;
  19683. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19684. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19685. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19686. material.alpha = parsedMaterial.alpha;
  19687. material.id = parsedMaterial.id;
  19688. if (parsedMaterial.disableDepthWrite) {
  19689. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19690. }
  19691. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19692. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19693. material.wireframe = parsedMaterial.wireframe;
  19694. if (parsedMaterial.diffuseTexture) {
  19695. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19696. }
  19697. if (parsedMaterial.diffuseFresnelParameters) {
  19698. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19699. }
  19700. if (parsedMaterial.ambientTexture) {
  19701. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19702. }
  19703. if (parsedMaterial.opacityTexture) {
  19704. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19705. }
  19706. if (parsedMaterial.opacityFresnelParameters) {
  19707. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19708. }
  19709. if (parsedMaterial.reflectionTexture) {
  19710. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19711. }
  19712. if (parsedMaterial.reflectionFresnelParameters) {
  19713. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19714. }
  19715. if (parsedMaterial.emissiveTexture) {
  19716. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19717. }
  19718. if (parsedMaterial.emissiveFresnelParameters) {
  19719. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19720. }
  19721. if (parsedMaterial.specularTexture) {
  19722. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19723. }
  19724. if (parsedMaterial.bumpTexture) {
  19725. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19726. }
  19727. if (parsedMaterial.checkReadyOnlyOnce) {
  19728. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19729. }
  19730. return material;
  19731. };
  19732. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19733. for (var index = 0; index < parsedData.materials.length; index++) {
  19734. var parsedMaterial = parsedData.materials[index];
  19735. if (parsedMaterial.id === id) {
  19736. return parseMaterial(parsedMaterial, scene, rootUrl);
  19737. }
  19738. }
  19739. return null;
  19740. };
  19741. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19742. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19743. multiMaterial.id = parsedMultiMaterial.id;
  19744. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19745. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19746. var subMatId = parsedMultiMaterial.materials[matIndex];
  19747. if (subMatId) {
  19748. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19749. }
  19750. else {
  19751. multiMaterial.subMaterials.push(null);
  19752. }
  19753. }
  19754. return multiMaterial;
  19755. };
  19756. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19757. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19758. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19759. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19760. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19761. var parsedFlare = parsedLensFlareSystem.flares[index];
  19762. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19763. }
  19764. return lensFlareSystem;
  19765. };
  19766. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19767. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19768. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19769. if (parsedParticleSystem.textureName) {
  19770. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19771. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19772. }
  19773. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19774. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19775. particleSystem.minSize = parsedParticleSystem.minSize;
  19776. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19777. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19778. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19779. particleSystem.emitter = emitter;
  19780. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19781. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19782. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19783. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19784. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19785. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19786. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19787. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19788. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19789. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19790. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19791. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19792. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19793. particleSystem.start();
  19794. return particleSystem;
  19795. };
  19796. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19797. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19798. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19799. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19800. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19801. shadowGenerator.getShadowMap().renderList.push(mesh);
  19802. }
  19803. if (parsedShadowGenerator.usePoissonSampling) {
  19804. shadowGenerator.usePoissonSampling = true;
  19805. }
  19806. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19807. shadowGenerator.useVarianceShadowMap = true;
  19808. }
  19809. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19810. shadowGenerator.useBlurVarianceShadowMap = true;
  19811. if (parsedShadowGenerator.blurScale) {
  19812. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19813. }
  19814. if (parsedShadowGenerator.blurBoxOffset) {
  19815. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19816. }
  19817. }
  19818. if (parsedShadowGenerator.bias !== undefined) {
  19819. shadowGenerator.bias = parsedShadowGenerator.bias;
  19820. }
  19821. return shadowGenerator;
  19822. };
  19823. var parseAnimation = function (parsedAnimation) {
  19824. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19825. var dataType = parsedAnimation.dataType;
  19826. var keys = [];
  19827. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19828. var key = parsedAnimation.keys[index];
  19829. var data;
  19830. switch (dataType) {
  19831. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19832. data = key.values[0];
  19833. break;
  19834. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19835. data = BABYLON.Quaternion.FromArray(key.values);
  19836. break;
  19837. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19838. data = BABYLON.Matrix.FromArray(key.values);
  19839. break;
  19840. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19841. default:
  19842. data = BABYLON.Vector3.FromArray(key.values);
  19843. break;
  19844. }
  19845. keys.push({
  19846. frame: key.frame,
  19847. value: data
  19848. });
  19849. }
  19850. animation.setKeys(keys);
  19851. return animation;
  19852. };
  19853. var parseLight = function (parsedLight, scene) {
  19854. var light;
  19855. switch (parsedLight.type) {
  19856. case 0:
  19857. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19858. break;
  19859. case 1:
  19860. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19861. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19862. break;
  19863. case 2:
  19864. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19865. break;
  19866. case 3:
  19867. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19868. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19869. break;
  19870. }
  19871. light.id = parsedLight.id;
  19872. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19873. if (parsedLight.intensity !== undefined) {
  19874. light.intensity = parsedLight.intensity;
  19875. }
  19876. if (parsedLight.range) {
  19877. light.range = parsedLight.range;
  19878. }
  19879. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19880. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19881. if (parsedLight.excludedMeshesIds) {
  19882. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19883. }
  19884. // Parent
  19885. if (parsedLight.parentId) {
  19886. light._waitingParentId = parsedLight.parentId;
  19887. }
  19888. if (parsedLight.includedOnlyMeshesIds) {
  19889. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19890. }
  19891. // Animations
  19892. if (parsedLight.animations) {
  19893. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19894. var parsedAnimation = parsedLight.animations[animationIndex];
  19895. light.animations.push(parseAnimation(parsedAnimation));
  19896. }
  19897. }
  19898. if (parsedLight.autoAnimate) {
  19899. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19900. }
  19901. };
  19902. var parseCamera = function (parsedCamera, scene) {
  19903. var camera;
  19904. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19905. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19906. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19907. var alpha = parsedCamera.alpha;
  19908. var beta = parsedCamera.beta;
  19909. var radius = parsedCamera.radius;
  19910. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19911. var interaxial_distance = parsedCamera.interaxial_distance;
  19912. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19913. }
  19914. else {
  19915. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19916. }
  19917. }
  19918. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19919. interaxial_distance = parsedCamera.interaxial_distance;
  19920. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19921. }
  19922. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19923. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19924. }
  19925. else if (parsedCamera.type === "FollowCamera") {
  19926. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19927. camera.heightOffset = parsedCamera.heightOffset;
  19928. camera.radius = parsedCamera.radius;
  19929. camera.rotationOffset = parsedCamera.rotationOffset;
  19930. if (lockedTargetMesh)
  19931. camera.target = lockedTargetMesh;
  19932. }
  19933. else if (parsedCamera.type === "GamepadCamera") {
  19934. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19935. }
  19936. else if (parsedCamera.type === "TouchCamera") {
  19937. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19938. }
  19939. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19940. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19941. }
  19942. else if (parsedCamera.type === "WebVRFreeCamera") {
  19943. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19944. }
  19945. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19946. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19947. }
  19948. else {
  19949. // Free Camera is the default value
  19950. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19951. }
  19952. // apply 3d rig, when found
  19953. if (parsedCamera.cameraRigMode) {
  19954. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19955. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19956. }
  19957. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19958. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19959. camera.lockedTarget = lockedTargetMesh;
  19960. }
  19961. camera.id = parsedCamera.id;
  19962. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19963. // Parent
  19964. if (parsedCamera.parentId) {
  19965. camera._waitingParentId = parsedCamera.parentId;
  19966. }
  19967. // Target
  19968. if (parsedCamera.target) {
  19969. if (camera.setTarget) {
  19970. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19971. }
  19972. else {
  19973. //For ArcRotate
  19974. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19975. }
  19976. }
  19977. else {
  19978. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19979. }
  19980. camera.fov = parsedCamera.fov;
  19981. camera.minZ = parsedCamera.minZ;
  19982. camera.maxZ = parsedCamera.maxZ;
  19983. camera.speed = parsedCamera.speed;
  19984. camera.inertia = parsedCamera.inertia;
  19985. camera.checkCollisions = parsedCamera.checkCollisions;
  19986. camera.applyGravity = parsedCamera.applyGravity;
  19987. if (parsedCamera.ellipsoid) {
  19988. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19989. }
  19990. // Animations
  19991. if (parsedCamera.animations) {
  19992. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19993. var parsedAnimation = parsedCamera.animations[animationIndex];
  19994. camera.animations.push(parseAnimation(parsedAnimation));
  19995. }
  19996. }
  19997. if (parsedCamera.autoAnimate) {
  19998. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19999. }
  20000. // Layer Mask
  20001. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20002. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20003. }
  20004. else {
  20005. camera.layerMask = 0x0FFFFFFF;
  20006. }
  20007. return camera;
  20008. };
  20009. var parseGeometry = function (parsedGeometry, scene) {
  20010. var id = parsedGeometry.id;
  20011. return scene.getGeometryByID(id);
  20012. };
  20013. var parseBox = function (parsedBox, scene) {
  20014. if (parseGeometry(parsedBox, scene)) {
  20015. return null; // null since geometry could be something else than a box...
  20016. }
  20017. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20018. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20019. scene.pushGeometry(box, true);
  20020. return box;
  20021. };
  20022. var parseSphere = function (parsedSphere, scene) {
  20023. if (parseGeometry(parsedSphere, scene)) {
  20024. return null; // null since geometry could be something else than a sphere...
  20025. }
  20026. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20027. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20028. scene.pushGeometry(sphere, true);
  20029. return sphere;
  20030. };
  20031. var parseCylinder = function (parsedCylinder, scene) {
  20032. if (parseGeometry(parsedCylinder, scene)) {
  20033. return null; // null since geometry could be something else than a cylinder...
  20034. }
  20035. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20036. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20037. scene.pushGeometry(cylinder, true);
  20038. return cylinder;
  20039. };
  20040. var parseTorus = function (parsedTorus, scene) {
  20041. if (parseGeometry(parsedTorus, scene)) {
  20042. return null; // null since geometry could be something else than a torus...
  20043. }
  20044. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20045. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20046. scene.pushGeometry(torus, true);
  20047. return torus;
  20048. };
  20049. var parseGround = function (parsedGround, scene) {
  20050. if (parseGeometry(parsedGround, scene)) {
  20051. return null; // null since geometry could be something else than a ground...
  20052. }
  20053. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20054. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20055. scene.pushGeometry(ground, true);
  20056. return ground;
  20057. };
  20058. var parsePlane = function (parsedPlane, scene) {
  20059. if (parseGeometry(parsedPlane, scene)) {
  20060. return null; // null since geometry could be something else than a plane...
  20061. }
  20062. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20063. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20064. scene.pushGeometry(plane, true);
  20065. return plane;
  20066. };
  20067. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20068. if (parseGeometry(parsedTorusKnot, scene)) {
  20069. return null; // null since geometry could be something else than a torusKnot...
  20070. }
  20071. 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);
  20072. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20073. scene.pushGeometry(torusKnot, true);
  20074. return torusKnot;
  20075. };
  20076. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20077. if (parseGeometry(parsedVertexData, scene)) {
  20078. return null; // null since geometry could be a primitive
  20079. }
  20080. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20081. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20082. if (parsedVertexData.delayLoadingFile) {
  20083. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20084. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20085. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20086. geometry._delayInfo = [];
  20087. if (parsedVertexData.hasUVs) {
  20088. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20089. }
  20090. if (parsedVertexData.hasUVs2) {
  20091. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20092. }
  20093. if (parsedVertexData.hasUVs3) {
  20094. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20095. }
  20096. if (parsedVertexData.hasUVs4) {
  20097. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20098. }
  20099. if (parsedVertexData.hasUVs5) {
  20100. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20101. }
  20102. if (parsedVertexData.hasUVs6) {
  20103. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20104. }
  20105. if (parsedVertexData.hasColors) {
  20106. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20107. }
  20108. if (parsedVertexData.hasMatricesIndices) {
  20109. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20110. }
  20111. if (parsedVertexData.hasMatricesWeights) {
  20112. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20113. }
  20114. geometry._delayLoadingFunction = importVertexData;
  20115. }
  20116. else {
  20117. importVertexData(parsedVertexData, geometry);
  20118. }
  20119. scene.pushGeometry(geometry, true);
  20120. return geometry;
  20121. };
  20122. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20123. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20124. mesh.id = parsedMesh.id;
  20125. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20126. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20127. if (parsedMesh.rotationQuaternion) {
  20128. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20129. }
  20130. else if (parsedMesh.rotation) {
  20131. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20132. }
  20133. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20134. if (parsedMesh.localMatrix) {
  20135. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20136. }
  20137. else if (parsedMesh.pivotMatrix) {
  20138. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20139. }
  20140. mesh.setEnabled(parsedMesh.isEnabled);
  20141. mesh.isVisible = parsedMesh.isVisible;
  20142. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20143. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20144. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20145. if (parsedMesh.applyFog !== undefined) {
  20146. mesh.applyFog = parsedMesh.applyFog;
  20147. }
  20148. if (parsedMesh.pickable !== undefined) {
  20149. mesh.isPickable = parsedMesh.pickable;
  20150. }
  20151. if (parsedMesh.alphaIndex !== undefined) {
  20152. mesh.alphaIndex = parsedMesh.alphaIndex;
  20153. }
  20154. mesh.receiveShadows = parsedMesh.receiveShadows;
  20155. mesh.billboardMode = parsedMesh.billboardMode;
  20156. if (parsedMesh.visibility !== undefined) {
  20157. mesh.visibility = parsedMesh.visibility;
  20158. }
  20159. mesh.checkCollisions = parsedMesh.checkCollisions;
  20160. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20161. // freezeWorldMatrix
  20162. if (parsedMesh.freezeWorldMatrix) {
  20163. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20164. }
  20165. // Parent
  20166. if (parsedMesh.parentId) {
  20167. mesh._waitingParentId = parsedMesh.parentId;
  20168. }
  20169. // Actions
  20170. if (parsedMesh.actions !== undefined) {
  20171. mesh._waitingActions = parsedMesh.actions;
  20172. }
  20173. // Geometry
  20174. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20175. if (parsedMesh.delayLoadingFile) {
  20176. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20177. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20178. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20179. if (parsedMesh._binaryInfo) {
  20180. mesh._binaryInfo = parsedMesh._binaryInfo;
  20181. }
  20182. mesh._delayInfo = [];
  20183. if (parsedMesh.hasUVs) {
  20184. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20185. }
  20186. if (parsedMesh.hasUVs2) {
  20187. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20188. }
  20189. if (parsedMesh.hasUVs3) {
  20190. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20191. }
  20192. if (parsedMesh.hasUVs4) {
  20193. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20194. }
  20195. if (parsedMesh.hasUVs5) {
  20196. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20197. }
  20198. if (parsedMesh.hasUVs6) {
  20199. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20200. }
  20201. if (parsedMesh.hasColors) {
  20202. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20203. }
  20204. if (parsedMesh.hasMatricesIndices) {
  20205. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20206. }
  20207. if (parsedMesh.hasMatricesWeights) {
  20208. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20209. }
  20210. mesh._delayLoadingFunction = importGeometry;
  20211. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20212. mesh._checkDelayState();
  20213. }
  20214. }
  20215. else {
  20216. importGeometry(parsedMesh, mesh);
  20217. }
  20218. // Material
  20219. if (parsedMesh.materialId) {
  20220. mesh.setMaterialByID(parsedMesh.materialId);
  20221. }
  20222. else {
  20223. mesh.material = null;
  20224. }
  20225. // Skeleton
  20226. if (parsedMesh.skeletonId > -1) {
  20227. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20228. }
  20229. // Physics
  20230. if (parsedMesh.physicsImpostor) {
  20231. if (!scene.isPhysicsEnabled()) {
  20232. scene.enablePhysics();
  20233. }
  20234. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20235. }
  20236. // Animations
  20237. if (parsedMesh.animations) {
  20238. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20239. var parsedAnimation = parsedMesh.animations[animationIndex];
  20240. mesh.animations.push(parseAnimation(parsedAnimation));
  20241. }
  20242. }
  20243. if (parsedMesh.autoAnimate) {
  20244. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20245. }
  20246. // Layer Mask
  20247. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20248. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20249. }
  20250. else {
  20251. mesh.layerMask = 0x0FFFFFFF;
  20252. }
  20253. // Instances
  20254. if (parsedMesh.instances) {
  20255. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20256. var parsedInstance = parsedMesh.instances[index];
  20257. var instance = mesh.createInstance(parsedInstance.name);
  20258. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20259. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20260. if (parsedInstance.rotationQuaternion) {
  20261. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20262. }
  20263. else if (parsedInstance.rotation) {
  20264. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20265. }
  20266. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20267. instance.checkCollisions = mesh.checkCollisions;
  20268. if (parsedMesh.animations) {
  20269. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20270. parsedAnimation = parsedMesh.animations[animationIndex];
  20271. instance.animations.push(parseAnimation(parsedAnimation));
  20272. }
  20273. }
  20274. }
  20275. }
  20276. return mesh;
  20277. };
  20278. var parseActions = function (parsedActions, object, scene) {
  20279. var actionManager = new BABYLON.ActionManager(scene);
  20280. if (object === null)
  20281. scene.actionManager = actionManager;
  20282. else
  20283. object.actionManager = actionManager;
  20284. // instanciate a new object
  20285. var instanciate = function (name, params) {
  20286. var newInstance = Object.create(BABYLON[name].prototype);
  20287. newInstance.constructor.apply(newInstance, params);
  20288. return newInstance;
  20289. };
  20290. var parseParameter = function (name, value, target, propertyPath) {
  20291. if (propertyPath === null) {
  20292. // String, boolean or float
  20293. var floatValue = parseFloat(value);
  20294. if (value === "true" || value === "false")
  20295. return value === "true";
  20296. else
  20297. return isNaN(floatValue) ? value : floatValue;
  20298. }
  20299. var effectiveTarget = propertyPath.split(".");
  20300. var values = value.split(",");
  20301. // Get effective Target
  20302. for (var i = 0; i < effectiveTarget.length; i++) {
  20303. target = target[effectiveTarget[i]];
  20304. }
  20305. // Return appropriate value with its type
  20306. if (typeof (target) === "boolean")
  20307. return values[0] === "true";
  20308. if (typeof (target) === "string")
  20309. return values[0];
  20310. // Parameters with multiple values such as Vector3 etc.
  20311. var split = new Array();
  20312. for (var i = 0; i < values.length; i++)
  20313. split.push(parseFloat(values[i]));
  20314. if (target instanceof BABYLON.Vector3)
  20315. return BABYLON.Vector3.FromArray(split);
  20316. if (target instanceof BABYLON.Vector4)
  20317. return BABYLON.Vector4.FromArray(split);
  20318. if (target instanceof BABYLON.Color3)
  20319. return BABYLON.Color3.FromArray(split);
  20320. if (target instanceof BABYLON.Color4)
  20321. return BABYLON.Color4.FromArray(split);
  20322. return parseFloat(values[0]);
  20323. };
  20324. // traverse graph per trigger
  20325. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20326. if (combineArray === void 0) { combineArray = null; }
  20327. if (parsedAction.detached)
  20328. return;
  20329. var parameters = new Array();
  20330. var target = null;
  20331. var propertyPath = null;
  20332. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20333. // Parameters
  20334. if (parsedAction.type === 2)
  20335. parameters.push(actionManager);
  20336. else
  20337. parameters.push(trigger);
  20338. if (combine) {
  20339. var actions = new Array();
  20340. for (var j = 0; j < parsedAction.combine.length; j++) {
  20341. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20342. }
  20343. parameters.push(actions);
  20344. }
  20345. else {
  20346. for (var i = 0; i < parsedAction.properties.length; i++) {
  20347. var value = parsedAction.properties[i].value;
  20348. var name = parsedAction.properties[i].name;
  20349. var targetType = parsedAction.properties[i].targetType;
  20350. if (name === "target")
  20351. if (targetType !== null && targetType === "SceneProperties")
  20352. value = target = scene;
  20353. else
  20354. value = target = scene.getNodeByName(value);
  20355. else if (name === "parent")
  20356. value = scene.getNodeByName(value);
  20357. else if (name === "sound")
  20358. value = scene.getSoundByName(value);
  20359. else if (name !== "propertyPath") {
  20360. if (parsedAction.type === 2 && name === "operator")
  20361. value = BABYLON.ValueCondition[value];
  20362. else
  20363. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20364. }
  20365. else {
  20366. propertyPath = value;
  20367. }
  20368. parameters.push(value);
  20369. }
  20370. }
  20371. if (combineArray === null) {
  20372. parameters.push(condition);
  20373. }
  20374. else {
  20375. parameters.push(null);
  20376. }
  20377. // If interpolate value action
  20378. if (parsedAction.name === "InterpolateValueAction") {
  20379. var param = parameters[parameters.length - 2];
  20380. parameters[parameters.length - 1] = param;
  20381. parameters[parameters.length - 2] = condition;
  20382. }
  20383. // Action or condition(s) and not CombineAction
  20384. var newAction = instanciate(parsedAction.name, parameters);
  20385. if (combineArray === null) {
  20386. if (newAction instanceof BABYLON.Condition) {
  20387. condition = newAction;
  20388. newAction = action;
  20389. }
  20390. else {
  20391. condition = null;
  20392. if (action)
  20393. action.then(newAction);
  20394. else
  20395. actionManager.registerAction(newAction);
  20396. }
  20397. }
  20398. else {
  20399. combineArray.push(newAction);
  20400. }
  20401. for (var i = 0; i < parsedAction.children.length; i++)
  20402. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20403. };
  20404. // triggers
  20405. for (var i = 0; i < parsedActions.children.length; i++) {
  20406. var triggerParams;
  20407. var trigger = parsedActions.children[i];
  20408. if (trigger.properties.length > 0) {
  20409. var param = trigger.properties[0].value;
  20410. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20411. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20412. }
  20413. else
  20414. triggerParams = BABYLON.ActionManager[trigger.name];
  20415. for (var j = 0; j < trigger.children.length; j++) {
  20416. if (!trigger.detached)
  20417. traverse(trigger.children[j], triggerParams, null, null);
  20418. }
  20419. }
  20420. };
  20421. var parseSound = function (parsedSound, scene, rootUrl) {
  20422. var soundName = parsedSound.name;
  20423. var soundUrl = rootUrl + soundName;
  20424. var options = {
  20425. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20426. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20427. rolloffFactor: parsedSound.rolloffFactor,
  20428. refDistance: parsedSound.refDistance,
  20429. distanceModel: parsedSound.distanceModel,
  20430. playbackRate: parsedSound.playbackRate
  20431. };
  20432. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20433. scene._addPendingData(newSound);
  20434. if (parsedSound.position) {
  20435. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20436. newSound.setPosition(soundPosition);
  20437. }
  20438. if (parsedSound.isDirectional) {
  20439. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20440. if (parsedSound.localDirectionToMesh) {
  20441. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20442. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20443. }
  20444. }
  20445. if (parsedSound.connectedMeshId) {
  20446. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20447. if (connectedMesh) {
  20448. newSound.attachToMesh(connectedMesh);
  20449. }
  20450. }
  20451. };
  20452. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20453. names = (names instanceof Array) ? names : [names];
  20454. for (var i in names) {
  20455. if (mesh.name === names[i]) {
  20456. hierarchyIds.push(mesh.id);
  20457. return true;
  20458. }
  20459. }
  20460. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20461. hierarchyIds.push(mesh.id);
  20462. return true;
  20463. }
  20464. return false;
  20465. };
  20466. var importVertexData = function (parsedVertexData, geometry) {
  20467. var vertexData = new BABYLON.VertexData();
  20468. // positions
  20469. var positions = parsedVertexData.positions;
  20470. if (positions) {
  20471. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20472. }
  20473. // normals
  20474. var normals = parsedVertexData.normals;
  20475. if (normals) {
  20476. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20477. }
  20478. // uvs
  20479. var uvs = parsedVertexData.uvs;
  20480. if (uvs) {
  20481. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20482. }
  20483. // uv2s
  20484. var uv2s = parsedVertexData.uv2s;
  20485. if (uv2s) {
  20486. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20487. }
  20488. // uv3s
  20489. var uv3s = parsedVertexData.uv3s;
  20490. if (uv3s) {
  20491. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20492. }
  20493. // uv4s
  20494. var uv4s = parsedVertexData.uv4s;
  20495. if (uv4s) {
  20496. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20497. }
  20498. // uv5s
  20499. var uv5s = parsedVertexData.uv5s;
  20500. if (uv5s) {
  20501. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20502. }
  20503. // uv6s
  20504. var uv6s = parsedVertexData.uv6s;
  20505. if (uv6s) {
  20506. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20507. }
  20508. // colors
  20509. var colors = parsedVertexData.colors;
  20510. if (colors) {
  20511. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20512. }
  20513. // matricesIndices
  20514. var matricesIndices = parsedVertexData.matricesIndices;
  20515. if (matricesIndices) {
  20516. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20517. }
  20518. // matricesWeights
  20519. var matricesWeights = parsedVertexData.matricesWeights;
  20520. if (matricesWeights) {
  20521. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20522. }
  20523. // indices
  20524. var indices = parsedVertexData.indices;
  20525. if (indices) {
  20526. vertexData.indices = indices;
  20527. }
  20528. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20529. };
  20530. var importGeometry = function (parsedGeometry, mesh) {
  20531. var scene = mesh.getScene();
  20532. // Geometry
  20533. var geometryId = parsedGeometry.geometryId;
  20534. if (geometryId) {
  20535. var geometry = scene.getGeometryByID(geometryId);
  20536. if (geometry) {
  20537. geometry.applyToMesh(mesh);
  20538. }
  20539. }
  20540. else if (parsedGeometry instanceof ArrayBuffer) {
  20541. var binaryInfo = mesh._binaryInfo;
  20542. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20543. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20544. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20545. }
  20546. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20547. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20548. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20549. }
  20550. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20551. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20552. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20553. }
  20554. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20555. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20556. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20557. }
  20558. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20559. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20560. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20561. }
  20562. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20563. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20564. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20565. }
  20566. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20567. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20568. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20569. }
  20570. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20571. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20572. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20573. }
  20574. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20575. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20576. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20577. }
  20578. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20579. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20580. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20581. }
  20582. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20583. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20584. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20585. }
  20586. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20587. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20588. mesh.setIndices(indicesData);
  20589. }
  20590. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20591. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20592. mesh.subMeshes = [];
  20593. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20594. var materialIndex = subMeshesData[(i * 5) + 0];
  20595. var verticesStart = subMeshesData[(i * 5) + 1];
  20596. var verticesCount = subMeshesData[(i * 5) + 2];
  20597. var indexStart = subMeshesData[(i * 5) + 3];
  20598. var indexCount = subMeshesData[(i * 5) + 4];
  20599. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20600. }
  20601. }
  20602. }
  20603. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20604. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20605. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20606. if (parsedGeometry.uvs) {
  20607. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20608. }
  20609. if (parsedGeometry.uvs2) {
  20610. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20611. }
  20612. if (parsedGeometry.uvs3) {
  20613. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20614. }
  20615. if (parsedGeometry.uvs4) {
  20616. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20617. }
  20618. if (parsedGeometry.uvs5) {
  20619. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20620. }
  20621. if (parsedGeometry.uvs6) {
  20622. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20623. }
  20624. if (parsedGeometry.colors) {
  20625. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20626. }
  20627. if (parsedGeometry.matricesIndices) {
  20628. if (!parsedGeometry.matricesIndices._isExpanded) {
  20629. var floatIndices = [];
  20630. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20631. var matricesIndex = parsedGeometry.matricesIndices[i];
  20632. floatIndices.push(matricesIndex & 0x000000FF);
  20633. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20634. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20635. floatIndices.push(matricesIndex >> 24);
  20636. }
  20637. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20638. }
  20639. else {
  20640. delete parsedGeometry.matricesIndices._isExpanded;
  20641. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20642. }
  20643. }
  20644. if (parsedGeometry.matricesWeights) {
  20645. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20646. }
  20647. mesh.setIndices(parsedGeometry.indices);
  20648. }
  20649. // SubMeshes
  20650. if (parsedGeometry.subMeshes) {
  20651. mesh.subMeshes = [];
  20652. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20653. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20654. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20655. }
  20656. }
  20657. // Flat shading
  20658. if (mesh._shouldGenerateFlatShading) {
  20659. mesh.convertToFlatShadedMesh();
  20660. delete mesh._shouldGenerateFlatShading;
  20661. }
  20662. // Update
  20663. mesh.computeWorldMatrix(true);
  20664. // Octree
  20665. if (scene._selectionOctree) {
  20666. scene._selectionOctree.addMesh(mesh);
  20667. }
  20668. };
  20669. BABYLON.SceneLoader.RegisterPlugin({
  20670. extensions: ".babylon",
  20671. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20672. var parsedData = JSON.parse(data);
  20673. var loadedSkeletonsIds = [];
  20674. var loadedMaterialsIds = [];
  20675. var hierarchyIds = [];
  20676. for (var index = 0; index < parsedData.meshes.length; index++) {
  20677. var parsedMesh = parsedData.meshes[index];
  20678. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20679. if (meshesNames instanceof Array) {
  20680. // Remove found mesh name from list.
  20681. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20682. }
  20683. //Geometry?
  20684. if (parsedMesh.geometryId) {
  20685. //does the file contain geometries?
  20686. if (parsedData.geometries) {
  20687. //find the correct geometry and add it to the scene
  20688. var found = false;
  20689. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20690. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20691. return;
  20692. }
  20693. else {
  20694. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20695. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20696. switch (geometryType) {
  20697. case "boxes":
  20698. parseBox(parsedGeometryData, scene);
  20699. break;
  20700. case "spheres":
  20701. parseSphere(parsedGeometryData, scene);
  20702. break;
  20703. case "cylinders":
  20704. parseCylinder(parsedGeometryData, scene);
  20705. break;
  20706. case "toruses":
  20707. parseTorus(parsedGeometryData, scene);
  20708. break;
  20709. case "grounds":
  20710. parseGround(parsedGeometryData, scene);
  20711. break;
  20712. case "planes":
  20713. parsePlane(parsedGeometryData, scene);
  20714. break;
  20715. case "torusKnots":
  20716. parseTorusKnot(parsedGeometryData, scene);
  20717. break;
  20718. case "vertexData":
  20719. parseVertexData(parsedGeometryData, scene, rootUrl);
  20720. break;
  20721. }
  20722. found = true;
  20723. }
  20724. });
  20725. }
  20726. });
  20727. if (!found) {
  20728. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20729. }
  20730. }
  20731. }
  20732. // Material ?
  20733. if (parsedMesh.materialId) {
  20734. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20735. if (!materialFound && parsedData.multiMaterials) {
  20736. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20737. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20738. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20739. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20740. var subMatId = parsedMultiMaterial.materials[matIndex];
  20741. loadedMaterialsIds.push(subMatId);
  20742. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20743. }
  20744. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20745. parseMultiMaterial(parsedMultiMaterial, scene);
  20746. materialFound = true;
  20747. break;
  20748. }
  20749. }
  20750. }
  20751. if (!materialFound) {
  20752. loadedMaterialsIds.push(parsedMesh.materialId);
  20753. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20754. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20755. }
  20756. }
  20757. }
  20758. // Skeleton ?
  20759. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20760. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20761. if (!skeletonAlreadyLoaded) {
  20762. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20763. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20764. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20765. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20766. loadedSkeletonsIds.push(parsedSkeleton.id);
  20767. }
  20768. }
  20769. }
  20770. }
  20771. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20772. meshes.push(mesh);
  20773. }
  20774. }
  20775. // Connecting parents
  20776. for (index = 0; index < scene.meshes.length; index++) {
  20777. var currentMesh = scene.meshes[index];
  20778. if (currentMesh._waitingParentId) {
  20779. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20780. currentMesh._waitingParentId = undefined;
  20781. }
  20782. }
  20783. // freeze world matrix application
  20784. for (index = 0; index < scene.meshes.length; index++) {
  20785. var currentMesh = scene.meshes[index];
  20786. if (currentMesh._waitingFreezeWorldMatrix) {
  20787. currentMesh.freezeWorldMatrix();
  20788. currentMesh._waitingFreezeWorldMatrix = undefined;
  20789. }
  20790. }
  20791. // Particles
  20792. if (parsedData.particleSystems) {
  20793. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20794. var parsedParticleSystem = parsedData.particleSystems[index];
  20795. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20796. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20797. }
  20798. }
  20799. }
  20800. return true;
  20801. },
  20802. load: function (scene, data, rootUrl) {
  20803. var parsedData = JSON.parse(data);
  20804. // Scene
  20805. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20806. scene.autoClear = parsedData.autoClear;
  20807. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20808. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20809. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20810. // Fog
  20811. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20812. scene.fogMode = parsedData.fogMode;
  20813. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20814. scene.fogStart = parsedData.fogStart;
  20815. scene.fogEnd = parsedData.fogEnd;
  20816. scene.fogDensity = parsedData.fogDensity;
  20817. }
  20818. // Lights
  20819. for (var index = 0; index < parsedData.lights.length; index++) {
  20820. var parsedLight = parsedData.lights[index];
  20821. parseLight(parsedLight, scene);
  20822. }
  20823. // Materials
  20824. if (parsedData.materials) {
  20825. for (index = 0; index < parsedData.materials.length; index++) {
  20826. var parsedMaterial = parsedData.materials[index];
  20827. parseMaterial(parsedMaterial, scene, rootUrl);
  20828. }
  20829. }
  20830. if (parsedData.multiMaterials) {
  20831. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20832. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20833. parseMultiMaterial(parsedMultiMaterial, scene);
  20834. }
  20835. }
  20836. // Skeletons
  20837. if (parsedData.skeletons) {
  20838. for (index = 0; index < parsedData.skeletons.length; index++) {
  20839. var parsedSkeleton = parsedData.skeletons[index];
  20840. parseSkeleton(parsedSkeleton, scene);
  20841. }
  20842. }
  20843. // Geometries
  20844. var geometries = parsedData.geometries;
  20845. if (geometries) {
  20846. // Boxes
  20847. var boxes = geometries.boxes;
  20848. if (boxes) {
  20849. for (index = 0; index < boxes.length; index++) {
  20850. var parsedBox = boxes[index];
  20851. parseBox(parsedBox, scene);
  20852. }
  20853. }
  20854. // Spheres
  20855. var spheres = geometries.spheres;
  20856. if (spheres) {
  20857. for (index = 0; index < spheres.length; index++) {
  20858. var parsedSphere = spheres[index];
  20859. parseSphere(parsedSphere, scene);
  20860. }
  20861. }
  20862. // Cylinders
  20863. var cylinders = geometries.cylinders;
  20864. if (cylinders) {
  20865. for (index = 0; index < cylinders.length; index++) {
  20866. var parsedCylinder = cylinders[index];
  20867. parseCylinder(parsedCylinder, scene);
  20868. }
  20869. }
  20870. // Toruses
  20871. var toruses = geometries.toruses;
  20872. if (toruses) {
  20873. for (index = 0; index < toruses.length; index++) {
  20874. var parsedTorus = toruses[index];
  20875. parseTorus(parsedTorus, scene);
  20876. }
  20877. }
  20878. // Grounds
  20879. var grounds = geometries.grounds;
  20880. if (grounds) {
  20881. for (index = 0; index < grounds.length; index++) {
  20882. var parsedGround = grounds[index];
  20883. parseGround(parsedGround, scene);
  20884. }
  20885. }
  20886. // Planes
  20887. var planes = geometries.planes;
  20888. if (planes) {
  20889. for (index = 0; index < planes.length; index++) {
  20890. var parsedPlane = planes[index];
  20891. parsePlane(parsedPlane, scene);
  20892. }
  20893. }
  20894. // TorusKnots
  20895. var torusKnots = geometries.torusKnots;
  20896. if (torusKnots) {
  20897. for (index = 0; index < torusKnots.length; index++) {
  20898. var parsedTorusKnot = torusKnots[index];
  20899. parseTorusKnot(parsedTorusKnot, scene);
  20900. }
  20901. }
  20902. // VertexData
  20903. var vertexData = geometries.vertexData;
  20904. if (vertexData) {
  20905. for (index = 0; index < vertexData.length; index++) {
  20906. var parsedVertexData = vertexData[index];
  20907. parseVertexData(parsedVertexData, scene, rootUrl);
  20908. }
  20909. }
  20910. }
  20911. // Meshes
  20912. for (index = 0; index < parsedData.meshes.length; index++) {
  20913. var parsedMesh = parsedData.meshes[index];
  20914. parseMesh(parsedMesh, scene, rootUrl);
  20915. }
  20916. // Cameras
  20917. for (index = 0; index < parsedData.cameras.length; index++) {
  20918. var parsedCamera = parsedData.cameras[index];
  20919. parseCamera(parsedCamera, scene);
  20920. }
  20921. if (parsedData.activeCameraID) {
  20922. scene.setActiveCameraByID(parsedData.activeCameraID);
  20923. }
  20924. // Browsing all the graph to connect the dots
  20925. for (index = 0; index < scene.cameras.length; index++) {
  20926. var camera = scene.cameras[index];
  20927. if (camera._waitingParentId) {
  20928. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20929. camera._waitingParentId = undefined;
  20930. }
  20931. }
  20932. for (index = 0; index < scene.lights.length; index++) {
  20933. var light = scene.lights[index];
  20934. if (light._waitingParentId) {
  20935. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20936. light._waitingParentId = undefined;
  20937. }
  20938. }
  20939. // Sounds
  20940. if (parsedData.sounds) {
  20941. for (index = 0; index < parsedData.sounds.length; index++) {
  20942. var parsedSound = parsedData.sounds[index];
  20943. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20944. parseSound(parsedSound, scene, rootUrl);
  20945. }
  20946. else {
  20947. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20948. }
  20949. }
  20950. }
  20951. // Connect parents & children and parse actions
  20952. for (index = 0; index < scene.meshes.length; index++) {
  20953. var mesh = scene.meshes[index];
  20954. if (mesh._waitingParentId) {
  20955. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20956. mesh._waitingParentId = undefined;
  20957. }
  20958. if (mesh._waitingActions) {
  20959. parseActions(mesh._waitingActions, mesh, scene);
  20960. mesh._waitingActions = undefined;
  20961. }
  20962. }
  20963. // freeze world matrix application
  20964. for (index = 0; index < scene.meshes.length; index++) {
  20965. var currentMesh = scene.meshes[index];
  20966. if (currentMesh._waitingFreezeWorldMatrix) {
  20967. currentMesh.freezeWorldMatrix();
  20968. currentMesh._waitingFreezeWorldMatrix = undefined;
  20969. }
  20970. }
  20971. // Particles Systems
  20972. if (parsedData.particleSystems) {
  20973. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20974. var parsedParticleSystem = parsedData.particleSystems[index];
  20975. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20976. }
  20977. }
  20978. // Lens flares
  20979. if (parsedData.lensFlareSystems) {
  20980. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20981. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20982. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20983. }
  20984. }
  20985. // Shadows
  20986. if (parsedData.shadowGenerators) {
  20987. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20988. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20989. parseShadowGenerator(parsedShadowGenerator, scene);
  20990. }
  20991. }
  20992. // Actions (scene)
  20993. if (parsedData.actions) {
  20994. parseActions(parsedData.actions, null, scene);
  20995. }
  20996. // Finish
  20997. return true;
  20998. }
  20999. });
  21000. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21001. })(BABYLON || (BABYLON = {}));
  21002. var BABYLON;
  21003. (function (BABYLON) {
  21004. var SpriteManager = (function () {
  21005. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21007. this.name = name;
  21008. this.cellSize = cellSize;
  21009. this.sprites = new Array();
  21010. this.renderingGroupId = 0;
  21011. this.layerMask = 0x0FFFFFFF;
  21012. this.fogEnabled = true;
  21013. this._vertexDeclaration = [4, 4, 4, 4];
  21014. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21015. this._capacity = capacity;
  21016. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21017. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21018. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21019. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21020. this._scene = scene;
  21021. this._scene.spriteManagers.push(this);
  21022. // VBO
  21023. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21024. var indices = [];
  21025. var index = 0;
  21026. for (var count = 0; count < capacity; count++) {
  21027. indices.push(index);
  21028. indices.push(index + 1);
  21029. indices.push(index + 2);
  21030. indices.push(index);
  21031. indices.push(index + 2);
  21032. indices.push(index + 3);
  21033. index += 4;
  21034. }
  21035. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21036. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21037. // Effects
  21038. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21039. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21040. }
  21041. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21042. var arrayOffset = index * 16;
  21043. if (offsetX === 0)
  21044. offsetX = this._epsilon;
  21045. else if (offsetX === 1)
  21046. offsetX = 1 - this._epsilon;
  21047. if (offsetY === 0)
  21048. offsetY = this._epsilon;
  21049. else if (offsetY === 1)
  21050. offsetY = 1 - this._epsilon;
  21051. this._vertices[arrayOffset] = sprite.position.x;
  21052. this._vertices[arrayOffset + 1] = sprite.position.y;
  21053. this._vertices[arrayOffset + 2] = sprite.position.z;
  21054. this._vertices[arrayOffset + 3] = sprite.angle;
  21055. this._vertices[arrayOffset + 4] = sprite.width;
  21056. this._vertices[arrayOffset + 5] = sprite.height;
  21057. this._vertices[arrayOffset + 6] = offsetX;
  21058. this._vertices[arrayOffset + 7] = offsetY;
  21059. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21060. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21061. var offset = (sprite.cellIndex / rowSize) >> 0;
  21062. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21063. this._vertices[arrayOffset + 11] = offset;
  21064. // Color
  21065. this._vertices[arrayOffset + 12] = sprite.color.r;
  21066. this._vertices[arrayOffset + 13] = sprite.color.g;
  21067. this._vertices[arrayOffset + 14] = sprite.color.b;
  21068. this._vertices[arrayOffset + 15] = sprite.color.a;
  21069. };
  21070. SpriteManager.prototype.render = function () {
  21071. // Check
  21072. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21073. return;
  21074. var engine = this._scene.getEngine();
  21075. var baseSize = this._spriteTexture.getBaseSize();
  21076. // Sprites
  21077. var deltaTime = engine.getDeltaTime();
  21078. var max = Math.min(this._capacity, this.sprites.length);
  21079. var rowSize = baseSize.width / this.cellSize;
  21080. var offset = 0;
  21081. for (var index = 0; index < max; index++) {
  21082. var sprite = this.sprites[index];
  21083. if (!sprite) {
  21084. continue;
  21085. }
  21086. sprite._animate(deltaTime);
  21087. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21088. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21089. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21090. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21091. }
  21092. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21093. // Render
  21094. var effect = this._effectBase;
  21095. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21096. effect = this._effectFog;
  21097. }
  21098. engine.enableEffect(effect);
  21099. var viewMatrix = this._scene.getViewMatrix();
  21100. effect.setTexture("diffuseSampler", this._spriteTexture);
  21101. effect.setMatrix("view", viewMatrix);
  21102. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21103. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21104. // Fog
  21105. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21106. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21107. effect.setColor3("vFogColor", this._scene.fogColor);
  21108. }
  21109. // VBOs
  21110. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21111. // Draw order
  21112. engine.setDepthFunctionToLessOrEqual();
  21113. effect.setBool("alphaTest", true);
  21114. engine.setColorWrite(false);
  21115. engine.draw(true, 0, max * 6);
  21116. engine.setColorWrite(true);
  21117. effect.setBool("alphaTest", false);
  21118. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21119. engine.draw(true, 0, max * 6);
  21120. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21121. };
  21122. SpriteManager.prototype.dispose = function () {
  21123. if (this._vertexBuffer) {
  21124. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21125. this._vertexBuffer = null;
  21126. }
  21127. if (this._indexBuffer) {
  21128. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21129. this._indexBuffer = null;
  21130. }
  21131. if (this._spriteTexture) {
  21132. this._spriteTexture.dispose();
  21133. this._spriteTexture = null;
  21134. }
  21135. // Remove from scene
  21136. var index = this._scene.spriteManagers.indexOf(this);
  21137. this._scene.spriteManagers.splice(index, 1);
  21138. // Callback
  21139. if (this.onDispose) {
  21140. this.onDispose();
  21141. }
  21142. };
  21143. return SpriteManager;
  21144. })();
  21145. BABYLON.SpriteManager = SpriteManager;
  21146. })(BABYLON || (BABYLON = {}));
  21147. var BABYLON;
  21148. (function (BABYLON) {
  21149. var Sprite = (function () {
  21150. function Sprite(name, manager) {
  21151. this.name = name;
  21152. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21153. this.width = 1.0;
  21154. this.height = 1.0;
  21155. this.angle = 0;
  21156. this.cellIndex = 0;
  21157. this.invertU = 0;
  21158. this.invertV = 0;
  21159. this.animations = new Array();
  21160. this._animationStarted = false;
  21161. this._loopAnimation = false;
  21162. this._fromIndex = 0;
  21163. this._toIndex = 0;
  21164. this._delay = 0;
  21165. this._direction = 1;
  21166. this._frameCount = 0;
  21167. this._time = 0;
  21168. this._manager = manager;
  21169. this._manager.sprites.push(this);
  21170. this.position = BABYLON.Vector3.Zero();
  21171. }
  21172. Object.defineProperty(Sprite.prototype, "size", {
  21173. get: function () {
  21174. return this.width;
  21175. },
  21176. set: function (value) {
  21177. this.width = value;
  21178. this.height = value;
  21179. },
  21180. enumerable: true,
  21181. configurable: true
  21182. });
  21183. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21184. this._fromIndex = from;
  21185. this._toIndex = to;
  21186. this._loopAnimation = loop;
  21187. this._delay = delay;
  21188. this._animationStarted = true;
  21189. this._direction = from < to ? 1 : -1;
  21190. this.cellIndex = from;
  21191. this._time = 0;
  21192. };
  21193. Sprite.prototype.stopAnimation = function () {
  21194. this._animationStarted = false;
  21195. };
  21196. Sprite.prototype._animate = function (deltaTime) {
  21197. if (!this._animationStarted)
  21198. return;
  21199. this._time += deltaTime;
  21200. if (this._time > this._delay) {
  21201. this._time = this._time % this._delay;
  21202. this.cellIndex += this._direction;
  21203. if (this.cellIndex == this._toIndex) {
  21204. if (this._loopAnimation) {
  21205. this.cellIndex = this._fromIndex;
  21206. }
  21207. else {
  21208. this._animationStarted = false;
  21209. if (this.disposeWhenFinishedAnimating) {
  21210. this.dispose();
  21211. }
  21212. }
  21213. }
  21214. }
  21215. };
  21216. Sprite.prototype.dispose = function () {
  21217. for (var i = 0; i < this._manager.sprites.length; i++) {
  21218. if (this._manager.sprites[i] == this) {
  21219. this._manager.sprites.splice(i, 1);
  21220. }
  21221. }
  21222. };
  21223. return Sprite;
  21224. })();
  21225. BABYLON.Sprite = Sprite;
  21226. })(BABYLON || (BABYLON = {}));
  21227. var BABYLON;
  21228. (function (BABYLON) {
  21229. var Layer = (function () {
  21230. function Layer(name, imgUrl, scene, isBackground, color) {
  21231. this.name = name;
  21232. this._vertexDeclaration = [2];
  21233. this._vertexStrideSize = 2 * 4;
  21234. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21235. this.isBackground = isBackground === undefined ? true : isBackground;
  21236. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21237. this._scene = scene;
  21238. this._scene.layers.push(this);
  21239. // VBO
  21240. var vertices = [];
  21241. vertices.push(1, 1);
  21242. vertices.push(-1, 1);
  21243. vertices.push(-1, -1);
  21244. vertices.push(1, -1);
  21245. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21246. // Indices
  21247. var indices = [];
  21248. indices.push(0);
  21249. indices.push(1);
  21250. indices.push(2);
  21251. indices.push(0);
  21252. indices.push(2);
  21253. indices.push(3);
  21254. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21255. // Effects
  21256. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21257. }
  21258. Layer.prototype.render = function () {
  21259. // Check
  21260. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21261. return;
  21262. var engine = this._scene.getEngine();
  21263. // Render
  21264. engine.enableEffect(this._effect);
  21265. engine.setState(false);
  21266. // Texture
  21267. this._effect.setTexture("textureSampler", this.texture);
  21268. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21269. // Color
  21270. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21271. // VBOs
  21272. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21273. // Draw order
  21274. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21275. engine.draw(true, 0, 6);
  21276. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21277. };
  21278. Layer.prototype.dispose = function () {
  21279. if (this._vertexBuffer) {
  21280. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21281. this._vertexBuffer = null;
  21282. }
  21283. if (this._indexBuffer) {
  21284. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21285. this._indexBuffer = null;
  21286. }
  21287. if (this.texture) {
  21288. this.texture.dispose();
  21289. this.texture = null;
  21290. }
  21291. // Remove from scene
  21292. var index = this._scene.layers.indexOf(this);
  21293. this._scene.layers.splice(index, 1);
  21294. // Callback
  21295. if (this.onDispose) {
  21296. this.onDispose();
  21297. }
  21298. };
  21299. return Layer;
  21300. })();
  21301. BABYLON.Layer = Layer;
  21302. })(BABYLON || (BABYLON = {}));
  21303. var BABYLON;
  21304. (function (BABYLON) {
  21305. var Particle = (function () {
  21306. function Particle() {
  21307. this.position = BABYLON.Vector3.Zero();
  21308. this.direction = BABYLON.Vector3.Zero();
  21309. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21310. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21311. this.lifeTime = 1.0;
  21312. this.age = 0;
  21313. this.size = 0;
  21314. this.angle = 0;
  21315. this.angularSpeed = 0;
  21316. }
  21317. Particle.prototype.copyTo = function (other) {
  21318. other.position.copyFrom(this.position);
  21319. other.direction.copyFrom(this.direction);
  21320. other.color.copyFrom(this.color);
  21321. other.colorStep.copyFrom(this.colorStep);
  21322. other.lifeTime = this.lifeTime;
  21323. other.age = this.age;
  21324. other.size = this.size;
  21325. other.angle = this.angle;
  21326. other.angularSpeed = this.angularSpeed;
  21327. };
  21328. return Particle;
  21329. })();
  21330. BABYLON.Particle = Particle;
  21331. })(BABYLON || (BABYLON = {}));
  21332. var BABYLON;
  21333. (function (BABYLON) {
  21334. var randomNumber = function (min, max) {
  21335. if (min === max) {
  21336. return (min);
  21337. }
  21338. var random = Math.random();
  21339. return ((random * (max - min)) + min);
  21340. };
  21341. var ParticleSystem = (function () {
  21342. function ParticleSystem(name, capacity, scene, customEffect) {
  21343. var _this = this;
  21344. this.name = name;
  21345. this.renderingGroupId = 0;
  21346. this.emitter = null;
  21347. this.emitRate = 10;
  21348. this.manualEmitCount = -1;
  21349. this.updateSpeed = 0.01;
  21350. this.targetStopDuration = 0;
  21351. this.disposeOnStop = false;
  21352. this.minEmitPower = 1;
  21353. this.maxEmitPower = 1;
  21354. this.minLifeTime = 1;
  21355. this.maxLifeTime = 1;
  21356. this.minSize = 1;
  21357. this.maxSize = 1;
  21358. this.minAngularSpeed = 0;
  21359. this.maxAngularSpeed = 0;
  21360. this.layerMask = 0x0FFFFFFF;
  21361. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21362. this.forceDepthWrite = false;
  21363. this.gravity = BABYLON.Vector3.Zero();
  21364. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21365. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21366. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21367. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21368. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21369. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21370. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21371. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21372. this.particles = new Array();
  21373. this._vertexDeclaration = [3, 4, 4];
  21374. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21375. this._stockParticles = new Array();
  21376. this._newPartsExcess = 0;
  21377. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21378. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21379. this._scaledDirection = BABYLON.Vector3.Zero();
  21380. this._scaledGravity = BABYLON.Vector3.Zero();
  21381. this._currentRenderId = -1;
  21382. this._started = false;
  21383. this._stopped = false;
  21384. this._actualFrame = 0;
  21385. this.id = name;
  21386. this._capacity = capacity;
  21387. this._scene = scene;
  21388. this._customEffect = customEffect;
  21389. scene.particleSystems.push(this);
  21390. // VBO
  21391. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21392. var indices = [];
  21393. var index = 0;
  21394. for (var count = 0; count < capacity; count++) {
  21395. indices.push(index);
  21396. indices.push(index + 1);
  21397. indices.push(index + 2);
  21398. indices.push(index);
  21399. indices.push(index + 2);
  21400. indices.push(index + 3);
  21401. index += 4;
  21402. }
  21403. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21404. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21405. // Default behaviors
  21406. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21407. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21408. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21409. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21410. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21411. };
  21412. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21413. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21414. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21415. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21416. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21417. };
  21418. this.updateFunction = function (particles) {
  21419. for (var index = 0; index < particles.length; index++) {
  21420. var particle = particles[index];
  21421. particle.age += _this._scaledUpdateSpeed;
  21422. if (particle.age >= particle.lifeTime) {
  21423. _this.recycleParticle(particle);
  21424. index--;
  21425. continue;
  21426. }
  21427. else {
  21428. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21429. particle.color.addInPlace(_this._scaledColorStep);
  21430. if (particle.color.a < 0)
  21431. particle.color.a = 0;
  21432. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21433. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21434. particle.position.addInPlace(_this._scaledDirection);
  21435. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21436. particle.direction.addInPlace(_this._scaledGravity);
  21437. }
  21438. }
  21439. };
  21440. }
  21441. ParticleSystem.prototype.recycleParticle = function (particle) {
  21442. var lastParticle = this.particles.pop();
  21443. if (lastParticle !== particle) {
  21444. lastParticle.copyTo(particle);
  21445. this._stockParticles.push(lastParticle);
  21446. }
  21447. };
  21448. ParticleSystem.prototype.getCapacity = function () {
  21449. return this._capacity;
  21450. };
  21451. ParticleSystem.prototype.isAlive = function () {
  21452. return this._alive;
  21453. };
  21454. ParticleSystem.prototype.isStarted = function () {
  21455. return this._started;
  21456. };
  21457. ParticleSystem.prototype.start = function () {
  21458. this._started = true;
  21459. this._stopped = false;
  21460. this._actualFrame = 0;
  21461. };
  21462. ParticleSystem.prototype.stop = function () {
  21463. this._stopped = true;
  21464. };
  21465. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21466. var offset = index * 11;
  21467. this._vertices[offset] = particle.position.x;
  21468. this._vertices[offset + 1] = particle.position.y;
  21469. this._vertices[offset + 2] = particle.position.z;
  21470. this._vertices[offset + 3] = particle.color.r;
  21471. this._vertices[offset + 4] = particle.color.g;
  21472. this._vertices[offset + 5] = particle.color.b;
  21473. this._vertices[offset + 6] = particle.color.a;
  21474. this._vertices[offset + 7] = particle.angle;
  21475. this._vertices[offset + 8] = particle.size;
  21476. this._vertices[offset + 9] = offsetX;
  21477. this._vertices[offset + 10] = offsetY;
  21478. };
  21479. ParticleSystem.prototype._update = function (newParticles) {
  21480. // Update current
  21481. this._alive = this.particles.length > 0;
  21482. this.updateFunction(this.particles);
  21483. // Add new ones
  21484. var worldMatrix;
  21485. if (this.emitter.position) {
  21486. worldMatrix = this.emitter.getWorldMatrix();
  21487. }
  21488. else {
  21489. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21490. }
  21491. for (var index = 0; index < newParticles; index++) {
  21492. if (this.particles.length === this._capacity) {
  21493. break;
  21494. }
  21495. if (this._stockParticles.length !== 0) {
  21496. var particle = this._stockParticles.pop();
  21497. particle.age = 0;
  21498. }
  21499. else {
  21500. particle = new BABYLON.Particle();
  21501. }
  21502. this.particles.push(particle);
  21503. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21504. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21505. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21506. particle.size = randomNumber(this.minSize, this.maxSize);
  21507. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21508. this.startPositionFunction(worldMatrix, particle.position);
  21509. var step = randomNumber(0, 1.0);
  21510. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21511. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21512. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21513. }
  21514. };
  21515. ParticleSystem.prototype._getEffect = function () {
  21516. if (this._customEffect) {
  21517. return this._customEffect;
  21518. }
  21519. ;
  21520. var defines = [];
  21521. if (this._scene.clipPlane) {
  21522. defines.push("#define CLIPPLANE");
  21523. }
  21524. // Effect
  21525. var join = defines.join("\n");
  21526. if (this._cachedDefines !== join) {
  21527. this._cachedDefines = join;
  21528. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21529. }
  21530. return this._effect;
  21531. };
  21532. ParticleSystem.prototype.animate = function () {
  21533. if (!this._started)
  21534. return;
  21535. var effect = this._getEffect();
  21536. // Check
  21537. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21538. return;
  21539. if (this._currentRenderId === this._scene.getRenderId()) {
  21540. return;
  21541. }
  21542. this._currentRenderId = this._scene.getRenderId();
  21543. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21544. // determine the number of particles we need to create
  21545. var emitCout;
  21546. if (this.manualEmitCount > -1) {
  21547. emitCout = this.manualEmitCount;
  21548. this.manualEmitCount = 0;
  21549. }
  21550. else {
  21551. emitCout = this.emitRate;
  21552. }
  21553. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21554. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21555. if (this._newPartsExcess > 1.0) {
  21556. newParticles += this._newPartsExcess >> 0;
  21557. this._newPartsExcess -= this._newPartsExcess >> 0;
  21558. }
  21559. this._alive = false;
  21560. if (!this._stopped) {
  21561. this._actualFrame += this._scaledUpdateSpeed;
  21562. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21563. this.stop();
  21564. }
  21565. else {
  21566. newParticles = 0;
  21567. }
  21568. this._update(newParticles);
  21569. // Stopped?
  21570. if (this._stopped) {
  21571. if (!this._alive) {
  21572. this._started = false;
  21573. if (this.disposeOnStop) {
  21574. this._scene._toBeDisposed.push(this);
  21575. }
  21576. }
  21577. }
  21578. // Update VBO
  21579. var offset = 0;
  21580. for (var index = 0; index < this.particles.length; index++) {
  21581. var particle = this.particles[index];
  21582. this._appendParticleVertex(offset++, particle, 0, 0);
  21583. this._appendParticleVertex(offset++, particle, 1, 0);
  21584. this._appendParticleVertex(offset++, particle, 1, 1);
  21585. this._appendParticleVertex(offset++, particle, 0, 1);
  21586. }
  21587. var engine = this._scene.getEngine();
  21588. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21589. };
  21590. ParticleSystem.prototype.render = function () {
  21591. var effect = this._getEffect();
  21592. // Check
  21593. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21594. return 0;
  21595. var engine = this._scene.getEngine();
  21596. // Render
  21597. engine.enableEffect(effect);
  21598. engine.setState(false);
  21599. var viewMatrix = this._scene.getViewMatrix();
  21600. effect.setTexture("diffuseSampler", this.particleTexture);
  21601. effect.setMatrix("view", viewMatrix);
  21602. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21603. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21604. if (this._scene.clipPlane) {
  21605. var clipPlane = this._scene.clipPlane;
  21606. var invView = viewMatrix.clone();
  21607. invView.invert();
  21608. effect.setMatrix("invView", invView);
  21609. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21610. }
  21611. // VBOs
  21612. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21613. // Draw order
  21614. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21615. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21616. }
  21617. else {
  21618. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21619. }
  21620. if (this.forceDepthWrite) {
  21621. engine.setDepthWrite(true);
  21622. }
  21623. engine.draw(true, 0, this.particles.length * 6);
  21624. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21625. return this.particles.length;
  21626. };
  21627. ParticleSystem.prototype.dispose = function () {
  21628. if (this._vertexBuffer) {
  21629. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21630. this._vertexBuffer = null;
  21631. }
  21632. if (this._indexBuffer) {
  21633. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21634. this._indexBuffer = null;
  21635. }
  21636. if (this.particleTexture) {
  21637. this.particleTexture.dispose();
  21638. this.particleTexture = null;
  21639. }
  21640. // Remove from scene
  21641. var index = this._scene.particleSystems.indexOf(this);
  21642. this._scene.particleSystems.splice(index, 1);
  21643. // Callback
  21644. if (this.onDispose) {
  21645. this.onDispose();
  21646. }
  21647. };
  21648. // Clone
  21649. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21650. var result = new ParticleSystem(name, this._capacity, this._scene);
  21651. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21652. if (newEmitter === undefined) {
  21653. newEmitter = this.emitter;
  21654. }
  21655. result.emitter = newEmitter;
  21656. if (this.particleTexture) {
  21657. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21658. }
  21659. result.start();
  21660. return result;
  21661. };
  21662. // Statics
  21663. ParticleSystem.BLENDMODE_ONEONE = 0;
  21664. ParticleSystem.BLENDMODE_STANDARD = 1;
  21665. return ParticleSystem;
  21666. })();
  21667. BABYLON.ParticleSystem = ParticleSystem;
  21668. })(BABYLON || (BABYLON = {}));
  21669. var BABYLON;
  21670. (function (BABYLON) {
  21671. var Animation = (function () {
  21672. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21673. this.name = name;
  21674. this.targetProperty = targetProperty;
  21675. this.framePerSecond = framePerSecond;
  21676. this.dataType = dataType;
  21677. this.loopMode = loopMode;
  21678. this._offsetsCache = {};
  21679. this._highLimitsCache = {};
  21680. this._stopped = false;
  21681. this.allowMatricesInterpolation = false;
  21682. this.targetPropertyPath = targetProperty.split(".");
  21683. this.dataType = dataType;
  21684. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21685. }
  21686. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21687. var dataType = undefined;
  21688. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21689. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21690. }
  21691. else if (from instanceof BABYLON.Quaternion) {
  21692. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21693. }
  21694. else if (from instanceof BABYLON.Vector3) {
  21695. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21696. }
  21697. else if (from instanceof BABYLON.Vector2) {
  21698. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21699. }
  21700. else if (from instanceof BABYLON.Color3) {
  21701. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21702. }
  21703. if (dataType == undefined) {
  21704. return null;
  21705. }
  21706. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21707. var keys = [];
  21708. keys.push({ frame: 0, value: from });
  21709. keys.push({ frame: totalFrame, value: to });
  21710. animation.setKeys(keys);
  21711. if (easingFunction !== undefined) {
  21712. animation.setEasingFunction(easingFunction);
  21713. }
  21714. mesh.animations.push(animation);
  21715. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  21716. };
  21717. // Methods
  21718. Animation.prototype.reset = function () {
  21719. this._offsetsCache = {};
  21720. this._highLimitsCache = {};
  21721. this.currentFrame = 0;
  21722. };
  21723. Animation.prototype.isStopped = function () {
  21724. return this._stopped;
  21725. };
  21726. Animation.prototype.getKeys = function () {
  21727. return this._keys;
  21728. };
  21729. Animation.prototype.getEasingFunction = function () {
  21730. return this._easingFunction;
  21731. };
  21732. Animation.prototype.setEasingFunction = function (easingFunction) {
  21733. this._easingFunction = easingFunction;
  21734. };
  21735. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21736. return startValue + (endValue - startValue) * gradient;
  21737. };
  21738. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21739. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21740. };
  21741. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21742. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21743. };
  21744. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21745. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21746. };
  21747. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21748. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21749. };
  21750. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21751. var startScale = new BABYLON.Vector3(0, 0, 0);
  21752. var startRotation = new BABYLON.Quaternion();
  21753. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21754. startValue.decompose(startScale, startRotation, startTranslation);
  21755. var endScale = new BABYLON.Vector3(0, 0, 0);
  21756. var endRotation = new BABYLON.Quaternion();
  21757. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21758. endValue.decompose(endScale, endRotation, endTranslation);
  21759. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21760. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21761. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21762. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21763. return result;
  21764. };
  21765. Animation.prototype.clone = function () {
  21766. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21767. clone.setKeys(this._keys);
  21768. return clone;
  21769. };
  21770. Animation.prototype.setKeys = function (values) {
  21771. this._keys = values.slice(0);
  21772. this._offsetsCache = {};
  21773. this._highLimitsCache = {};
  21774. };
  21775. Animation.prototype._getKeyValue = function (value) {
  21776. if (typeof value === "function") {
  21777. return value();
  21778. }
  21779. return value;
  21780. };
  21781. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21782. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21783. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21784. }
  21785. this.currentFrame = currentFrame;
  21786. // Try to get a hash to find the right key
  21787. 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));
  21788. if (this._keys[startKey].frame >= currentFrame) {
  21789. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21790. startKey--;
  21791. }
  21792. }
  21793. for (var key = startKey; key < this._keys.length; key++) {
  21794. if (this._keys[key + 1].frame >= currentFrame) {
  21795. var startValue = this._getKeyValue(this._keys[key].value);
  21796. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21797. // gradient : percent of currentFrame between the frame inf and the frame sup
  21798. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21799. // check for easingFunction and correction of gradient
  21800. if (this._easingFunction != null) {
  21801. gradient = this._easingFunction.ease(gradient);
  21802. }
  21803. switch (this.dataType) {
  21804. // Float
  21805. case Animation.ANIMATIONTYPE_FLOAT:
  21806. switch (loopMode) {
  21807. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21808. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21809. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21810. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21811. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21812. }
  21813. break;
  21814. // Quaternion
  21815. case Animation.ANIMATIONTYPE_QUATERNION:
  21816. var quaternion = null;
  21817. switch (loopMode) {
  21818. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21819. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21820. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21821. break;
  21822. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21823. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21824. break;
  21825. }
  21826. return quaternion;
  21827. // Vector3
  21828. case Animation.ANIMATIONTYPE_VECTOR3:
  21829. switch (loopMode) {
  21830. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21831. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21832. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21833. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21834. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21835. }
  21836. // Vector2
  21837. case Animation.ANIMATIONTYPE_VECTOR2:
  21838. switch (loopMode) {
  21839. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21840. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21841. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21842. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21843. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21844. }
  21845. // Color3
  21846. case Animation.ANIMATIONTYPE_COLOR3:
  21847. switch (loopMode) {
  21848. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21849. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21850. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21851. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21852. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21853. }
  21854. // Matrix
  21855. case Animation.ANIMATIONTYPE_MATRIX:
  21856. switch (loopMode) {
  21857. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21858. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21859. if (this.allowMatricesInterpolation) {
  21860. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21861. }
  21862. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21863. return startValue;
  21864. }
  21865. default:
  21866. break;
  21867. }
  21868. break;
  21869. }
  21870. }
  21871. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21872. };
  21873. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21874. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21875. this._stopped = true;
  21876. return false;
  21877. }
  21878. var returnValue = true;
  21879. // Adding a start key at frame 0 if missing
  21880. if (this._keys[0].frame !== 0) {
  21881. var newKey = { frame: 0, value: this._keys[0].value };
  21882. this._keys.splice(0, 0, newKey);
  21883. }
  21884. // Check limits
  21885. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21886. from = this._keys[0].frame;
  21887. }
  21888. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21889. to = this._keys[this._keys.length - 1].frame;
  21890. }
  21891. // Compute ratio
  21892. var range = to - from;
  21893. var offsetValue;
  21894. // ratio represents the frame delta between from and to
  21895. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21896. var highLimitValue = 0;
  21897. if (ratio > range && !loop) {
  21898. returnValue = false;
  21899. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21900. }
  21901. else {
  21902. // Get max value if required
  21903. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21904. var keyOffset = to.toString() + from.toString();
  21905. if (!this._offsetsCache[keyOffset]) {
  21906. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21907. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21908. switch (this.dataType) {
  21909. // Float
  21910. case Animation.ANIMATIONTYPE_FLOAT:
  21911. this._offsetsCache[keyOffset] = toValue - fromValue;
  21912. break;
  21913. // Quaternion
  21914. case Animation.ANIMATIONTYPE_QUATERNION:
  21915. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21916. break;
  21917. // Vector3
  21918. case Animation.ANIMATIONTYPE_VECTOR3:
  21919. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21920. // Vector2
  21921. case Animation.ANIMATIONTYPE_VECTOR2:
  21922. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21923. // Color3
  21924. case Animation.ANIMATIONTYPE_COLOR3:
  21925. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21926. default:
  21927. break;
  21928. }
  21929. this._highLimitsCache[keyOffset] = toValue;
  21930. }
  21931. highLimitValue = this._highLimitsCache[keyOffset];
  21932. offsetValue = this._offsetsCache[keyOffset];
  21933. }
  21934. }
  21935. if (offsetValue === undefined) {
  21936. switch (this.dataType) {
  21937. // Float
  21938. case Animation.ANIMATIONTYPE_FLOAT:
  21939. offsetValue = 0;
  21940. break;
  21941. // Quaternion
  21942. case Animation.ANIMATIONTYPE_QUATERNION:
  21943. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21944. break;
  21945. // Vector3
  21946. case Animation.ANIMATIONTYPE_VECTOR3:
  21947. offsetValue = BABYLON.Vector3.Zero();
  21948. break;
  21949. // Vector2
  21950. case Animation.ANIMATIONTYPE_VECTOR2:
  21951. offsetValue = BABYLON.Vector2.Zero();
  21952. break;
  21953. // Color3
  21954. case Animation.ANIMATIONTYPE_COLOR3:
  21955. offsetValue = BABYLON.Color3.Black();
  21956. }
  21957. }
  21958. // Compute value
  21959. var repeatCount = (ratio / range) >> 0;
  21960. var currentFrame = returnValue ? from + ratio % range : to;
  21961. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21962. // Set value
  21963. if (this.targetPropertyPath.length > 1) {
  21964. var property = this._target[this.targetPropertyPath[0]];
  21965. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21966. property = property[this.targetPropertyPath[index]];
  21967. }
  21968. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21969. }
  21970. else {
  21971. this._target[this.targetPropertyPath[0]] = currentValue;
  21972. }
  21973. if (this._target.markAsDirty) {
  21974. this._target.markAsDirty(this.targetProperty);
  21975. }
  21976. if (!returnValue) {
  21977. this._stopped = true;
  21978. }
  21979. return returnValue;
  21980. };
  21981. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21982. get: function () {
  21983. return Animation._ANIMATIONTYPE_FLOAT;
  21984. },
  21985. enumerable: true,
  21986. configurable: true
  21987. });
  21988. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21989. get: function () {
  21990. return Animation._ANIMATIONTYPE_VECTOR3;
  21991. },
  21992. enumerable: true,
  21993. configurable: true
  21994. });
  21995. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21996. get: function () {
  21997. return Animation._ANIMATIONTYPE_VECTOR2;
  21998. },
  21999. enumerable: true,
  22000. configurable: true
  22001. });
  22002. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22003. get: function () {
  22004. return Animation._ANIMATIONTYPE_QUATERNION;
  22005. },
  22006. enumerable: true,
  22007. configurable: true
  22008. });
  22009. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22010. get: function () {
  22011. return Animation._ANIMATIONTYPE_MATRIX;
  22012. },
  22013. enumerable: true,
  22014. configurable: true
  22015. });
  22016. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22017. get: function () {
  22018. return Animation._ANIMATIONTYPE_COLOR3;
  22019. },
  22020. enumerable: true,
  22021. configurable: true
  22022. });
  22023. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22024. get: function () {
  22025. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22026. },
  22027. enumerable: true,
  22028. configurable: true
  22029. });
  22030. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22031. get: function () {
  22032. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22033. },
  22034. enumerable: true,
  22035. configurable: true
  22036. });
  22037. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22038. get: function () {
  22039. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22040. },
  22041. enumerable: true,
  22042. configurable: true
  22043. });
  22044. // Statics
  22045. Animation._ANIMATIONTYPE_FLOAT = 0;
  22046. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22047. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22048. Animation._ANIMATIONTYPE_MATRIX = 3;
  22049. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22050. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22051. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22052. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22053. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22054. return Animation;
  22055. })();
  22056. BABYLON.Animation = Animation;
  22057. })(BABYLON || (BABYLON = {}));
  22058. var BABYLON;
  22059. (function (BABYLON) {
  22060. var Animatable = (function () {
  22061. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22062. if (fromFrame === void 0) { fromFrame = 0; }
  22063. if (toFrame === void 0) { toFrame = 100; }
  22064. if (loopAnimation === void 0) { loopAnimation = false; }
  22065. if (speedRatio === void 0) { speedRatio = 1.0; }
  22066. this.target = target;
  22067. this.fromFrame = fromFrame;
  22068. this.toFrame = toFrame;
  22069. this.loopAnimation = loopAnimation;
  22070. this.speedRatio = speedRatio;
  22071. this.onAnimationEnd = onAnimationEnd;
  22072. this._animations = new Array();
  22073. this._paused = false;
  22074. this.animationStarted = false;
  22075. if (animations) {
  22076. this.appendAnimations(target, animations);
  22077. }
  22078. this._scene = scene;
  22079. scene._activeAnimatables.push(this);
  22080. }
  22081. // Methods
  22082. Animatable.prototype.appendAnimations = function (target, animations) {
  22083. for (var index = 0; index < animations.length; index++) {
  22084. var animation = animations[index];
  22085. animation._target = target;
  22086. this._animations.push(animation);
  22087. }
  22088. };
  22089. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22090. var animations = this._animations;
  22091. for (var index = 0; index < animations.length; index++) {
  22092. if (animations[index].targetProperty === property) {
  22093. return animations[index];
  22094. }
  22095. }
  22096. return null;
  22097. };
  22098. Animatable.prototype.reset = function () {
  22099. var animations = this._animations;
  22100. for (var index = 0; index < animations.length; index++) {
  22101. animations[index].reset();
  22102. }
  22103. this._localDelayOffset = null;
  22104. this._pausedDelay = null;
  22105. };
  22106. Animatable.prototype.pause = function () {
  22107. if (this._paused) {
  22108. return;
  22109. }
  22110. this._paused = true;
  22111. };
  22112. Animatable.prototype.restart = function () {
  22113. this._paused = false;
  22114. };
  22115. Animatable.prototype.stop = function () {
  22116. var index = this._scene._activeAnimatables.indexOf(this);
  22117. if (index > -1) {
  22118. this._scene._activeAnimatables.splice(index, 1);
  22119. }
  22120. if (this.onAnimationEnd) {
  22121. this.onAnimationEnd();
  22122. }
  22123. };
  22124. Animatable.prototype._animate = function (delay) {
  22125. if (this._paused) {
  22126. if (!this._pausedDelay) {
  22127. this._pausedDelay = delay;
  22128. }
  22129. return true;
  22130. }
  22131. if (!this._localDelayOffset) {
  22132. this._localDelayOffset = delay;
  22133. }
  22134. else if (this._pausedDelay) {
  22135. this._localDelayOffset += delay - this._pausedDelay;
  22136. this._pausedDelay = null;
  22137. }
  22138. // Animating
  22139. var running = false;
  22140. var animations = this._animations;
  22141. for (var index = 0; index < animations.length; index++) {
  22142. var animation = animations[index];
  22143. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22144. running = running || isRunning;
  22145. }
  22146. if (!running) {
  22147. // Remove from active animatables
  22148. index = this._scene._activeAnimatables.indexOf(this);
  22149. this._scene._activeAnimatables.splice(index, 1);
  22150. }
  22151. if (!running && this.onAnimationEnd) {
  22152. this.onAnimationEnd();
  22153. }
  22154. return running;
  22155. };
  22156. return Animatable;
  22157. })();
  22158. BABYLON.Animatable = Animatable;
  22159. })(BABYLON || (BABYLON = {}));
  22160. var BABYLON;
  22161. (function (BABYLON) {
  22162. var EasingFunction = (function () {
  22163. function EasingFunction() {
  22164. // Properties
  22165. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22166. }
  22167. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22168. get: function () {
  22169. return EasingFunction._EASINGMODE_EASEIN;
  22170. },
  22171. enumerable: true,
  22172. configurable: true
  22173. });
  22174. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22175. get: function () {
  22176. return EasingFunction._EASINGMODE_EASEOUT;
  22177. },
  22178. enumerable: true,
  22179. configurable: true
  22180. });
  22181. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22182. get: function () {
  22183. return EasingFunction._EASINGMODE_EASEINOUT;
  22184. },
  22185. enumerable: true,
  22186. configurable: true
  22187. });
  22188. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22189. var n = Math.min(Math.max(easingMode, 0), 2);
  22190. this._easingMode = n;
  22191. };
  22192. EasingFunction.prototype.getEasingMode = function () {
  22193. return this._easingMode;
  22194. };
  22195. EasingFunction.prototype.easeInCore = function (gradient) {
  22196. throw new Error('You must implement this method');
  22197. };
  22198. EasingFunction.prototype.ease = function (gradient) {
  22199. switch (this._easingMode) {
  22200. case EasingFunction.EASINGMODE_EASEIN:
  22201. return this.easeInCore(gradient);
  22202. case EasingFunction.EASINGMODE_EASEOUT:
  22203. return (1 - this.easeInCore(1 - gradient));
  22204. }
  22205. if (gradient >= 0.5) {
  22206. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22207. }
  22208. return (this.easeInCore(gradient * 2) * 0.5);
  22209. };
  22210. //Statics
  22211. EasingFunction._EASINGMODE_EASEIN = 0;
  22212. EasingFunction._EASINGMODE_EASEOUT = 1;
  22213. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22214. return EasingFunction;
  22215. })();
  22216. BABYLON.EasingFunction = EasingFunction;
  22217. var CircleEase = (function (_super) {
  22218. __extends(CircleEase, _super);
  22219. function CircleEase() {
  22220. _super.apply(this, arguments);
  22221. }
  22222. CircleEase.prototype.easeInCore = function (gradient) {
  22223. gradient = Math.max(0, Math.min(1, gradient));
  22224. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22225. };
  22226. return CircleEase;
  22227. })(EasingFunction);
  22228. BABYLON.CircleEase = CircleEase;
  22229. var BackEase = (function (_super) {
  22230. __extends(BackEase, _super);
  22231. function BackEase(amplitude) {
  22232. if (amplitude === void 0) { amplitude = 1; }
  22233. _super.call(this);
  22234. this.amplitude = amplitude;
  22235. }
  22236. BackEase.prototype.easeInCore = function (gradient) {
  22237. var num = Math.max(0, this.amplitude);
  22238. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22239. };
  22240. return BackEase;
  22241. })(EasingFunction);
  22242. BABYLON.BackEase = BackEase;
  22243. var BounceEase = (function (_super) {
  22244. __extends(BounceEase, _super);
  22245. function BounceEase(bounces, bounciness) {
  22246. if (bounces === void 0) { bounces = 3; }
  22247. if (bounciness === void 0) { bounciness = 2; }
  22248. _super.call(this);
  22249. this.bounces = bounces;
  22250. this.bounciness = bounciness;
  22251. }
  22252. BounceEase.prototype.easeInCore = function (gradient) {
  22253. var y = Math.max(0.0, this.bounces);
  22254. var bounciness = this.bounciness;
  22255. if (bounciness <= 1.0) {
  22256. bounciness = 1.001;
  22257. }
  22258. var num9 = Math.pow(bounciness, y);
  22259. var num5 = 1.0 - bounciness;
  22260. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22261. var num15 = gradient * num4;
  22262. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22263. var num3 = Math.floor(num65);
  22264. var num13 = num3 + 1.0;
  22265. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22266. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22267. var num7 = (num8 + num12) * 0.5;
  22268. var num6 = gradient - num7;
  22269. var num2 = num7 - num8;
  22270. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22271. };
  22272. return BounceEase;
  22273. })(EasingFunction);
  22274. BABYLON.BounceEase = BounceEase;
  22275. var CubicEase = (function (_super) {
  22276. __extends(CubicEase, _super);
  22277. function CubicEase() {
  22278. _super.apply(this, arguments);
  22279. }
  22280. CubicEase.prototype.easeInCore = function (gradient) {
  22281. return (gradient * gradient * gradient);
  22282. };
  22283. return CubicEase;
  22284. })(EasingFunction);
  22285. BABYLON.CubicEase = CubicEase;
  22286. var ElasticEase = (function (_super) {
  22287. __extends(ElasticEase, _super);
  22288. function ElasticEase(oscillations, springiness) {
  22289. if (oscillations === void 0) { oscillations = 3; }
  22290. if (springiness === void 0) { springiness = 3; }
  22291. _super.call(this);
  22292. this.oscillations = oscillations;
  22293. this.springiness = springiness;
  22294. }
  22295. ElasticEase.prototype.easeInCore = function (gradient) {
  22296. var num2;
  22297. var num3 = Math.max(0.0, this.oscillations);
  22298. var num = Math.max(0.0, this.springiness);
  22299. if (num == 0) {
  22300. num2 = gradient;
  22301. }
  22302. else {
  22303. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22304. }
  22305. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22306. };
  22307. return ElasticEase;
  22308. })(EasingFunction);
  22309. BABYLON.ElasticEase = ElasticEase;
  22310. var ExponentialEase = (function (_super) {
  22311. __extends(ExponentialEase, _super);
  22312. function ExponentialEase(exponent) {
  22313. if (exponent === void 0) { exponent = 2; }
  22314. _super.call(this);
  22315. this.exponent = exponent;
  22316. }
  22317. ExponentialEase.prototype.easeInCore = function (gradient) {
  22318. if (this.exponent <= 0) {
  22319. return gradient;
  22320. }
  22321. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22322. };
  22323. return ExponentialEase;
  22324. })(EasingFunction);
  22325. BABYLON.ExponentialEase = ExponentialEase;
  22326. var PowerEase = (function (_super) {
  22327. __extends(PowerEase, _super);
  22328. function PowerEase(power) {
  22329. if (power === void 0) { power = 2; }
  22330. _super.call(this);
  22331. this.power = power;
  22332. }
  22333. PowerEase.prototype.easeInCore = function (gradient) {
  22334. var y = Math.max(0.0, this.power);
  22335. return Math.pow(gradient, y);
  22336. };
  22337. return PowerEase;
  22338. })(EasingFunction);
  22339. BABYLON.PowerEase = PowerEase;
  22340. var QuadraticEase = (function (_super) {
  22341. __extends(QuadraticEase, _super);
  22342. function QuadraticEase() {
  22343. _super.apply(this, arguments);
  22344. }
  22345. QuadraticEase.prototype.easeInCore = function (gradient) {
  22346. return (gradient * gradient);
  22347. };
  22348. return QuadraticEase;
  22349. })(EasingFunction);
  22350. BABYLON.QuadraticEase = QuadraticEase;
  22351. var QuarticEase = (function (_super) {
  22352. __extends(QuarticEase, _super);
  22353. function QuarticEase() {
  22354. _super.apply(this, arguments);
  22355. }
  22356. QuarticEase.prototype.easeInCore = function (gradient) {
  22357. return (gradient * gradient * gradient * gradient);
  22358. };
  22359. return QuarticEase;
  22360. })(EasingFunction);
  22361. BABYLON.QuarticEase = QuarticEase;
  22362. var QuinticEase = (function (_super) {
  22363. __extends(QuinticEase, _super);
  22364. function QuinticEase() {
  22365. _super.apply(this, arguments);
  22366. }
  22367. QuinticEase.prototype.easeInCore = function (gradient) {
  22368. return (gradient * gradient * gradient * gradient * gradient);
  22369. };
  22370. return QuinticEase;
  22371. })(EasingFunction);
  22372. BABYLON.QuinticEase = QuinticEase;
  22373. var SineEase = (function (_super) {
  22374. __extends(SineEase, _super);
  22375. function SineEase() {
  22376. _super.apply(this, arguments);
  22377. }
  22378. SineEase.prototype.easeInCore = function (gradient) {
  22379. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22380. };
  22381. return SineEase;
  22382. })(EasingFunction);
  22383. BABYLON.SineEase = SineEase;
  22384. var BezierCurveEase = (function (_super) {
  22385. __extends(BezierCurveEase, _super);
  22386. function BezierCurveEase(x1, y1, x2, y2) {
  22387. if (x1 === void 0) { x1 = 0; }
  22388. if (y1 === void 0) { y1 = 0; }
  22389. if (x2 === void 0) { x2 = 1; }
  22390. if (y2 === void 0) { y2 = 1; }
  22391. _super.call(this);
  22392. this.x1 = x1;
  22393. this.y1 = y1;
  22394. this.x2 = x2;
  22395. this.y2 = y2;
  22396. }
  22397. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22398. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22399. };
  22400. return BezierCurveEase;
  22401. })(EasingFunction);
  22402. BABYLON.BezierCurveEase = BezierCurveEase;
  22403. })(BABYLON || (BABYLON = {}));
  22404. var BABYLON;
  22405. (function (BABYLON) {
  22406. var Octree = (function () {
  22407. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22408. if (maxDepth === void 0) { maxDepth = 2; }
  22409. this.maxDepth = maxDepth;
  22410. this.dynamicContent = new Array();
  22411. this._maxBlockCapacity = maxBlockCapacity || 64;
  22412. this._selectionContent = new BABYLON.SmartArray(1024);
  22413. this._creationFunc = creationFunc;
  22414. }
  22415. // Methods
  22416. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22417. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22418. };
  22419. Octree.prototype.addMesh = function (entry) {
  22420. for (var index = 0; index < this.blocks.length; index++) {
  22421. var block = this.blocks[index];
  22422. block.addEntry(entry);
  22423. }
  22424. };
  22425. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22426. this._selectionContent.reset();
  22427. for (var index = 0; index < this.blocks.length; index++) {
  22428. var block = this.blocks[index];
  22429. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22430. }
  22431. if (allowDuplicate) {
  22432. this._selectionContent.concat(this.dynamicContent);
  22433. }
  22434. else {
  22435. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22436. }
  22437. return this._selectionContent;
  22438. };
  22439. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22440. this._selectionContent.reset();
  22441. for (var index = 0; index < this.blocks.length; index++) {
  22442. var block = this.blocks[index];
  22443. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22444. }
  22445. if (allowDuplicate) {
  22446. this._selectionContent.concat(this.dynamicContent);
  22447. }
  22448. else {
  22449. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22450. }
  22451. return this._selectionContent;
  22452. };
  22453. Octree.prototype.intersectsRay = function (ray) {
  22454. this._selectionContent.reset();
  22455. for (var index = 0; index < this.blocks.length; index++) {
  22456. var block = this.blocks[index];
  22457. block.intersectsRay(ray, this._selectionContent);
  22458. }
  22459. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22460. return this._selectionContent;
  22461. };
  22462. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22463. target.blocks = new Array();
  22464. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22465. // Segmenting space
  22466. for (var x = 0; x < 2; x++) {
  22467. for (var y = 0; y < 2; y++) {
  22468. for (var z = 0; z < 2; z++) {
  22469. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22470. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22471. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22472. block.addEntries(entries);
  22473. target.blocks.push(block);
  22474. }
  22475. }
  22476. }
  22477. };
  22478. Octree.CreationFuncForMeshes = function (entry, block) {
  22479. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22480. block.entries.push(entry);
  22481. }
  22482. };
  22483. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22484. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22485. block.entries.push(entry);
  22486. }
  22487. };
  22488. return Octree;
  22489. })();
  22490. BABYLON.Octree = Octree;
  22491. })(BABYLON || (BABYLON = {}));
  22492. var BABYLON;
  22493. (function (BABYLON) {
  22494. var OctreeBlock = (function () {
  22495. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22496. this.entries = new Array();
  22497. this._boundingVectors = new Array();
  22498. this._capacity = capacity;
  22499. this._depth = depth;
  22500. this._maxDepth = maxDepth;
  22501. this._creationFunc = creationFunc;
  22502. this._minPoint = minPoint;
  22503. this._maxPoint = maxPoint;
  22504. this._boundingVectors.push(minPoint.clone());
  22505. this._boundingVectors.push(maxPoint.clone());
  22506. this._boundingVectors.push(minPoint.clone());
  22507. this._boundingVectors[2].x = maxPoint.x;
  22508. this._boundingVectors.push(minPoint.clone());
  22509. this._boundingVectors[3].y = maxPoint.y;
  22510. this._boundingVectors.push(minPoint.clone());
  22511. this._boundingVectors[4].z = maxPoint.z;
  22512. this._boundingVectors.push(maxPoint.clone());
  22513. this._boundingVectors[5].z = minPoint.z;
  22514. this._boundingVectors.push(maxPoint.clone());
  22515. this._boundingVectors[6].x = minPoint.x;
  22516. this._boundingVectors.push(maxPoint.clone());
  22517. this._boundingVectors[7].y = minPoint.y;
  22518. }
  22519. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22520. // Property
  22521. get: function () {
  22522. return this._capacity;
  22523. },
  22524. enumerable: true,
  22525. configurable: true
  22526. });
  22527. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22528. get: function () {
  22529. return this._minPoint;
  22530. },
  22531. enumerable: true,
  22532. configurable: true
  22533. });
  22534. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  22535. get: function () {
  22536. return this._maxPoint;
  22537. },
  22538. enumerable: true,
  22539. configurable: true
  22540. });
  22541. // Methods
  22542. OctreeBlock.prototype.addEntry = function (entry) {
  22543. if (this.blocks) {
  22544. for (var index = 0; index < this.blocks.length; index++) {
  22545. var block = this.blocks[index];
  22546. block.addEntry(entry);
  22547. }
  22548. return;
  22549. }
  22550. this._creationFunc(entry, this);
  22551. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  22552. this.createInnerBlocks();
  22553. }
  22554. };
  22555. OctreeBlock.prototype.addEntries = function (entries) {
  22556. for (var index = 0; index < entries.length; index++) {
  22557. var mesh = entries[index];
  22558. this.addEntry(mesh);
  22559. }
  22560. };
  22561. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  22562. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  22563. if (this.blocks) {
  22564. for (var index = 0; index < this.blocks.length; index++) {
  22565. var block = this.blocks[index];
  22566. block.select(frustumPlanes, selection, allowDuplicate);
  22567. }
  22568. return;
  22569. }
  22570. if (allowDuplicate) {
  22571. selection.concat(this.entries);
  22572. }
  22573. else {
  22574. selection.concatWithNoDuplicate(this.entries);
  22575. }
  22576. }
  22577. };
  22578. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  22579. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  22580. if (this.blocks) {
  22581. for (var index = 0; index < this.blocks.length; index++) {
  22582. var block = this.blocks[index];
  22583. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  22584. }
  22585. return;
  22586. }
  22587. if (allowDuplicate) {
  22588. selection.concat(this.entries);
  22589. }
  22590. else {
  22591. selection.concatWithNoDuplicate(this.entries);
  22592. }
  22593. }
  22594. };
  22595. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  22596. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  22597. if (this.blocks) {
  22598. for (var index = 0; index < this.blocks.length; index++) {
  22599. var block = this.blocks[index];
  22600. block.intersectsRay(ray, selection);
  22601. }
  22602. return;
  22603. }
  22604. selection.concatWithNoDuplicate(this.entries);
  22605. }
  22606. };
  22607. OctreeBlock.prototype.createInnerBlocks = function () {
  22608. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  22609. };
  22610. return OctreeBlock;
  22611. })();
  22612. BABYLON.OctreeBlock = OctreeBlock;
  22613. })(BABYLON || (BABYLON = {}));
  22614. var BABYLON;
  22615. (function (BABYLON) {
  22616. var Bone = (function (_super) {
  22617. __extends(Bone, _super);
  22618. function Bone(name, skeleton, parentBone, matrix) {
  22619. _super.call(this, name, skeleton.getScene());
  22620. this.name = name;
  22621. this.children = new Array();
  22622. this.animations = new Array();
  22623. this._worldTransform = new BABYLON.Matrix();
  22624. this._absoluteTransform = new BABYLON.Matrix();
  22625. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22626. this._skeleton = skeleton;
  22627. this._matrix = matrix;
  22628. this._baseMatrix = matrix;
  22629. skeleton.bones.push(this);
  22630. if (parentBone) {
  22631. this._parent = parentBone;
  22632. parentBone.children.push(this);
  22633. }
  22634. else {
  22635. this._parent = null;
  22636. }
  22637. this._updateDifferenceMatrix();
  22638. }
  22639. // Members
  22640. Bone.prototype.getParent = function () {
  22641. return this._parent;
  22642. };
  22643. Bone.prototype.getLocalMatrix = function () {
  22644. return this._matrix;
  22645. };
  22646. Bone.prototype.getBaseMatrix = function () {
  22647. return this._baseMatrix;
  22648. };
  22649. Bone.prototype.getWorldMatrix = function () {
  22650. return this._worldTransform;
  22651. };
  22652. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22653. return this._invertedAbsoluteTransform;
  22654. };
  22655. Bone.prototype.getAbsoluteMatrix = function () {
  22656. var matrix = this._matrix.clone();
  22657. var parent = this._parent;
  22658. while (parent) {
  22659. matrix = matrix.multiply(parent.getLocalMatrix());
  22660. parent = parent.getParent();
  22661. }
  22662. return matrix;
  22663. };
  22664. // Methods
  22665. Bone.prototype.updateMatrix = function (matrix) {
  22666. this._matrix = matrix;
  22667. this._skeleton._markAsDirty();
  22668. this._updateDifferenceMatrix();
  22669. };
  22670. Bone.prototype._updateDifferenceMatrix = function () {
  22671. if (this._parent) {
  22672. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22673. }
  22674. else {
  22675. this._absoluteTransform.copyFrom(this._matrix);
  22676. }
  22677. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22678. for (var index = 0; index < this.children.length; index++) {
  22679. this.children[index]._updateDifferenceMatrix();
  22680. }
  22681. };
  22682. Bone.prototype.markAsDirty = function () {
  22683. this._currentRenderId++;
  22684. this._skeleton._markAsDirty();
  22685. };
  22686. return Bone;
  22687. })(BABYLON.Node);
  22688. BABYLON.Bone = Bone;
  22689. })(BABYLON || (BABYLON = {}));
  22690. var BABYLON;
  22691. (function (BABYLON) {
  22692. var Skeleton = (function () {
  22693. function Skeleton(name, id, scene) {
  22694. this.name = name;
  22695. this.id = id;
  22696. this.bones = new Array();
  22697. this._isDirty = true;
  22698. this._identity = BABYLON.Matrix.Identity();
  22699. this.bones = [];
  22700. this._scene = scene;
  22701. scene.skeletons.push(this);
  22702. this.prepare();
  22703. //make sure it will recalculate the matrix next time prepare is called.
  22704. this._isDirty = true;
  22705. }
  22706. // Members
  22707. Skeleton.prototype.getTransformMatrices = function () {
  22708. return this._transformMatrices;
  22709. };
  22710. Skeleton.prototype.getScene = function () {
  22711. return this._scene;
  22712. };
  22713. // Methods
  22714. Skeleton.prototype._markAsDirty = function () {
  22715. this._isDirty = true;
  22716. };
  22717. Skeleton.prototype.prepare = function () {
  22718. if (!this._isDirty) {
  22719. return;
  22720. }
  22721. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22722. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22723. }
  22724. for (var index = 0; index < this.bones.length; index++) {
  22725. var bone = this.bones[index];
  22726. var parentBone = bone.getParent();
  22727. if (parentBone) {
  22728. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22729. }
  22730. else {
  22731. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22732. }
  22733. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22734. }
  22735. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22736. this._isDirty = false;
  22737. this._scene._activeBones += this.bones.length;
  22738. };
  22739. Skeleton.prototype.getAnimatables = function () {
  22740. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22741. this._animatables = [];
  22742. for (var index = 0; index < this.bones.length; index++) {
  22743. this._animatables.push(this.bones[index]);
  22744. }
  22745. }
  22746. return this._animatables;
  22747. };
  22748. Skeleton.prototype.clone = function (name, id) {
  22749. var result = new Skeleton(name, id || name, this._scene);
  22750. for (var index = 0; index < this.bones.length; index++) {
  22751. var source = this.bones[index];
  22752. var parentBone = null;
  22753. if (source.getParent()) {
  22754. var parentIndex = this.bones.indexOf(source.getParent());
  22755. parentBone = result.bones[parentIndex];
  22756. }
  22757. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22758. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22759. }
  22760. return result;
  22761. };
  22762. return Skeleton;
  22763. })();
  22764. BABYLON.Skeleton = Skeleton;
  22765. })(BABYLON || (BABYLON = {}));
  22766. var BABYLON;
  22767. (function (BABYLON) {
  22768. var PostProcess = (function () {
  22769. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22770. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22771. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22772. this.name = name;
  22773. this.width = -1;
  22774. this.height = -1;
  22775. this._reusable = false;
  22776. this._textures = new BABYLON.SmartArray(2);
  22777. this._currentRenderTextureInd = 0;
  22778. if (camera != null) {
  22779. this._camera = camera;
  22780. this._scene = camera.getScene();
  22781. camera.attachPostProcess(this);
  22782. this._engine = this._scene.getEngine();
  22783. }
  22784. else {
  22785. this._engine = engine;
  22786. }
  22787. this._renderRatio = ratio;
  22788. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22789. this._reusable = reusable || false;
  22790. this._textureType = textureType;
  22791. samplers = samplers || [];
  22792. samplers.push("textureSampler");
  22793. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22794. }
  22795. PostProcess.prototype.isReusable = function () {
  22796. return this._reusable;
  22797. };
  22798. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22799. camera = camera || this._camera;
  22800. var scene = camera.getScene();
  22801. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22802. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22803. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22804. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  22805. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  22806. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22807. if (this._textures.length > 0) {
  22808. for (var i = 0; i < this._textures.length; i++) {
  22809. this._engine._releaseTexture(this._textures.data[i]);
  22810. }
  22811. this._textures.reset();
  22812. }
  22813. this.width = desiredWidth;
  22814. this.height = desiredHeight;
  22815. 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 }));
  22816. if (this._reusable) {
  22817. 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 }));
  22818. }
  22819. if (this.onSizeChanged) {
  22820. this.onSizeChanged();
  22821. }
  22822. }
  22823. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22824. if (this.onActivate) {
  22825. this.onActivate(camera);
  22826. }
  22827. // Clear
  22828. if (this.clearColor) {
  22829. this._engine.clear(this.clearColor, true, true);
  22830. }
  22831. else {
  22832. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22833. }
  22834. if (this._reusable) {
  22835. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22836. }
  22837. };
  22838. PostProcess.prototype.apply = function () {
  22839. // Check
  22840. if (!this._effect.isReady())
  22841. return null;
  22842. // States
  22843. this._engine.enableEffect(this._effect);
  22844. this._engine.setState(false);
  22845. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22846. this._engine.setDepthBuffer(false);
  22847. this._engine.setDepthWrite(false);
  22848. // Texture
  22849. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22850. // Parameters
  22851. if (this.onApply) {
  22852. this.onApply(this._effect);
  22853. }
  22854. return this._effect;
  22855. };
  22856. PostProcess.prototype.dispose = function (camera) {
  22857. camera = camera || this._camera;
  22858. if (this._textures.length > 0) {
  22859. for (var i = 0; i < this._textures.length; i++) {
  22860. this._engine._releaseTexture(this._textures.data[i]);
  22861. }
  22862. this._textures.reset();
  22863. }
  22864. if (!camera) {
  22865. return;
  22866. }
  22867. camera.detachPostProcess(this);
  22868. var index = camera._postProcesses.indexOf(this);
  22869. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22870. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22871. }
  22872. };
  22873. return PostProcess;
  22874. })();
  22875. BABYLON.PostProcess = PostProcess;
  22876. })(BABYLON || (BABYLON = {}));
  22877. var BABYLON;
  22878. (function (BABYLON) {
  22879. var PostProcessManager = (function () {
  22880. function PostProcessManager(scene) {
  22881. this._vertexDeclaration = [2];
  22882. this._vertexStrideSize = 2 * 4;
  22883. this._scene = scene;
  22884. }
  22885. PostProcessManager.prototype._prepareBuffers = function () {
  22886. if (this._vertexBuffer) {
  22887. return;
  22888. }
  22889. // VBO
  22890. var vertices = [];
  22891. vertices.push(1, 1);
  22892. vertices.push(-1, 1);
  22893. vertices.push(-1, -1);
  22894. vertices.push(1, -1);
  22895. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22896. // Indices
  22897. var indices = [];
  22898. indices.push(0);
  22899. indices.push(1);
  22900. indices.push(2);
  22901. indices.push(0);
  22902. indices.push(2);
  22903. indices.push(3);
  22904. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22905. };
  22906. // Methods
  22907. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22908. var postProcesses = this._scene.activeCamera._postProcesses;
  22909. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22910. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22911. return false;
  22912. }
  22913. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22914. return true;
  22915. };
  22916. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22917. var engine = this._scene.getEngine();
  22918. for (var index = 0; index < postProcesses.length; index++) {
  22919. if (index < postProcesses.length - 1) {
  22920. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22921. }
  22922. else {
  22923. if (targetTexture) {
  22924. engine.bindFramebuffer(targetTexture);
  22925. }
  22926. else {
  22927. engine.restoreDefaultFramebuffer();
  22928. }
  22929. }
  22930. var pp = postProcesses[index];
  22931. var effect = pp.apply();
  22932. if (effect) {
  22933. if (pp.onBeforeRender) {
  22934. pp.onBeforeRender(effect);
  22935. }
  22936. // VBOs
  22937. this._prepareBuffers();
  22938. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22939. // Draw order
  22940. engine.draw(true, 0, 6);
  22941. if (pp.onAfterRender) {
  22942. pp.onAfterRender(effect);
  22943. }
  22944. }
  22945. }
  22946. // Restore depth buffer
  22947. engine.setDepthBuffer(true);
  22948. engine.setDepthWrite(true);
  22949. };
  22950. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  22951. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22952. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22953. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22954. return;
  22955. }
  22956. var engine = this._scene.getEngine();
  22957. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22958. if (index < postProcessesTakenIndices.length - 1) {
  22959. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22960. }
  22961. else {
  22962. if (targetTexture) {
  22963. engine.bindFramebuffer(targetTexture);
  22964. }
  22965. else {
  22966. engine.restoreDefaultFramebuffer();
  22967. }
  22968. }
  22969. if (doNotPresent) {
  22970. break;
  22971. }
  22972. var pp = postProcesses[postProcessesTakenIndices[index]];
  22973. var effect = pp.apply();
  22974. if (effect) {
  22975. if (pp.onBeforeRender) {
  22976. pp.onBeforeRender(effect);
  22977. }
  22978. // VBOs
  22979. this._prepareBuffers();
  22980. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22981. // Draw order
  22982. engine.draw(true, 0, 6);
  22983. if (pp.onAfterRender) {
  22984. pp.onAfterRender(effect);
  22985. }
  22986. }
  22987. }
  22988. // Restore depth buffer
  22989. engine.setDepthBuffer(true);
  22990. engine.setDepthWrite(true);
  22991. };
  22992. PostProcessManager.prototype.dispose = function () {
  22993. if (this._vertexBuffer) {
  22994. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22995. this._vertexBuffer = null;
  22996. }
  22997. if (this._indexBuffer) {
  22998. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22999. this._indexBuffer = null;
  23000. }
  23001. };
  23002. return PostProcessManager;
  23003. })();
  23004. BABYLON.PostProcessManager = PostProcessManager;
  23005. })(BABYLON || (BABYLON = {}));
  23006. var BABYLON;
  23007. (function (BABYLON) {
  23008. var PassPostProcess = (function (_super) {
  23009. __extends(PassPostProcess, _super);
  23010. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23011. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23012. }
  23013. return PassPostProcess;
  23014. })(BABYLON.PostProcess);
  23015. BABYLON.PassPostProcess = PassPostProcess;
  23016. })(BABYLON || (BABYLON = {}));
  23017. var BABYLON;
  23018. (function (BABYLON) {
  23019. var BlurPostProcess = (function (_super) {
  23020. __extends(BlurPostProcess, _super);
  23021. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  23022. var _this = this;
  23023. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  23024. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  23025. this.direction = direction;
  23026. this.blurWidth = blurWidth;
  23027. this.onApply = function (effect) {
  23028. effect.setFloat2("screenSize", _this.width, _this.height);
  23029. effect.setVector2("direction", _this.direction);
  23030. effect.setFloat("blurWidth", _this.blurWidth);
  23031. };
  23032. }
  23033. return BlurPostProcess;
  23034. })(BABYLON.PostProcess);
  23035. BABYLON.BlurPostProcess = BlurPostProcess;
  23036. })(BABYLON || (BABYLON = {}));
  23037. var BABYLON;
  23038. (function (BABYLON) {
  23039. var RefractionPostProcess = (function (_super) {
  23040. __extends(RefractionPostProcess, _super);
  23041. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  23042. var _this = this;
  23043. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  23044. this.color = color;
  23045. this.depth = depth;
  23046. this.colorLevel = colorLevel;
  23047. this.onActivate = function (cam) {
  23048. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  23049. };
  23050. this.onApply = function (effect) {
  23051. effect.setColor3("baseColor", _this.color);
  23052. effect.setFloat("depth", _this.depth);
  23053. effect.setFloat("colorLevel", _this.colorLevel);
  23054. effect.setTexture("refractionSampler", _this._refRexture);
  23055. };
  23056. }
  23057. // Methods
  23058. RefractionPostProcess.prototype.dispose = function (camera) {
  23059. if (this._refRexture) {
  23060. this._refRexture.dispose();
  23061. }
  23062. _super.prototype.dispose.call(this, camera);
  23063. };
  23064. return RefractionPostProcess;
  23065. })(BABYLON.PostProcess);
  23066. BABYLON.RefractionPostProcess = RefractionPostProcess;
  23067. })(BABYLON || (BABYLON = {}));
  23068. var BABYLON;
  23069. (function (BABYLON) {
  23070. var BlackAndWhitePostProcess = (function (_super) {
  23071. __extends(BlackAndWhitePostProcess, _super);
  23072. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23073. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  23074. }
  23075. return BlackAndWhitePostProcess;
  23076. })(BABYLON.PostProcess);
  23077. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  23078. })(BABYLON || (BABYLON = {}));
  23079. var BABYLON;
  23080. (function (BABYLON) {
  23081. var ConvolutionPostProcess = (function (_super) {
  23082. __extends(ConvolutionPostProcess, _super);
  23083. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  23084. var _this = this;
  23085. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  23086. this.kernel = kernel;
  23087. this.onApply = function (effect) {
  23088. effect.setFloat2("screenSize", _this.width, _this.height);
  23089. effect.setArray("kernel", _this.kernel);
  23090. };
  23091. }
  23092. // Statics
  23093. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  23094. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  23095. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  23096. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  23097. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  23098. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  23099. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  23100. return ConvolutionPostProcess;
  23101. })(BABYLON.PostProcess);
  23102. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  23103. })(BABYLON || (BABYLON = {}));
  23104. var BABYLON;
  23105. (function (BABYLON) {
  23106. var FilterPostProcess = (function (_super) {
  23107. __extends(FilterPostProcess, _super);
  23108. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  23109. var _this = this;
  23110. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23111. this.kernelMatrix = kernelMatrix;
  23112. this.onApply = function (effect) {
  23113. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23114. };
  23115. }
  23116. return FilterPostProcess;
  23117. })(BABYLON.PostProcess);
  23118. BABYLON.FilterPostProcess = FilterPostProcess;
  23119. })(BABYLON || (BABYLON = {}));
  23120. var BABYLON;
  23121. (function (BABYLON) {
  23122. var FxaaPostProcess = (function (_super) {
  23123. __extends(FxaaPostProcess, _super);
  23124. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23125. var _this = this;
  23126. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23127. this.onSizeChanged = function () {
  23128. _this.texelWidth = 1.0 / _this.width;
  23129. _this.texelHeight = 1.0 / _this.height;
  23130. };
  23131. this.onApply = function (effect) {
  23132. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23133. };
  23134. }
  23135. return FxaaPostProcess;
  23136. })(BABYLON.PostProcess);
  23137. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23138. })(BABYLON || (BABYLON = {}));
  23139. var BABYLON;
  23140. (function (BABYLON) {
  23141. var StereoscopicInterlacePostProcess = (function (_super) {
  23142. __extends(StereoscopicInterlacePostProcess, _super);
  23143. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23144. var _this = this;
  23145. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23146. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23147. this.onSizeChanged = function () {
  23148. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23149. };
  23150. this.onApply = function (effect) {
  23151. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23152. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23153. };
  23154. }
  23155. return StereoscopicInterlacePostProcess;
  23156. })(BABYLON.PostProcess);
  23157. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23158. })(BABYLON || (BABYLON = {}));
  23159. var BABYLON;
  23160. (function (BABYLON) {
  23161. var LensFlare = (function () {
  23162. function LensFlare(size, position, color, imgUrl, system) {
  23163. this.size = size;
  23164. this.position = position;
  23165. this.dispose = function () {
  23166. if (this.texture) {
  23167. this.texture.dispose();
  23168. }
  23169. // Remove from scene
  23170. var index = this._system.lensFlares.indexOf(this);
  23171. this._system.lensFlares.splice(index, 1);
  23172. };
  23173. this.color = color || new BABYLON.Color3(1, 1, 1);
  23174. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23175. this._system = system;
  23176. system.lensFlares.push(this);
  23177. }
  23178. return LensFlare;
  23179. })();
  23180. BABYLON.LensFlare = LensFlare;
  23181. })(BABYLON || (BABYLON = {}));
  23182. var BABYLON;
  23183. (function (BABYLON) {
  23184. var LensFlareSystem = (function () {
  23185. function LensFlareSystem(name, emitter, scene) {
  23186. this.name = name;
  23187. this.lensFlares = new Array();
  23188. this.borderLimit = 300;
  23189. this.layerMask = 0x0FFFFFFF;
  23190. this._vertexDeclaration = [2];
  23191. this._vertexStrideSize = 2 * 4;
  23192. this._isEnabled = true;
  23193. this._scene = scene;
  23194. this._emitter = emitter;
  23195. scene.lensFlareSystems.push(this);
  23196. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23197. // VBO
  23198. var vertices = [];
  23199. vertices.push(1, 1);
  23200. vertices.push(-1, 1);
  23201. vertices.push(-1, -1);
  23202. vertices.push(1, -1);
  23203. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23204. // Indices
  23205. var indices = [];
  23206. indices.push(0);
  23207. indices.push(1);
  23208. indices.push(2);
  23209. indices.push(0);
  23210. indices.push(2);
  23211. indices.push(3);
  23212. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23213. // Effects
  23214. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23215. }
  23216. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23217. get: function () {
  23218. return this._isEnabled;
  23219. },
  23220. set: function (value) {
  23221. this._isEnabled = value;
  23222. },
  23223. enumerable: true,
  23224. configurable: true
  23225. });
  23226. LensFlareSystem.prototype.getScene = function () {
  23227. return this._scene;
  23228. };
  23229. LensFlareSystem.prototype.getEmitter = function () {
  23230. return this._emitter;
  23231. };
  23232. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23233. this._emitter = newEmitter;
  23234. };
  23235. LensFlareSystem.prototype.getEmitterPosition = function () {
  23236. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23237. };
  23238. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23239. var position = this.getEmitterPosition();
  23240. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23241. this._positionX = position.x;
  23242. this._positionY = position.y;
  23243. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23244. if (position.z > 0) {
  23245. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23246. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23247. return true;
  23248. }
  23249. }
  23250. return false;
  23251. };
  23252. LensFlareSystem.prototype._isVisible = function () {
  23253. if (!this._isEnabled) {
  23254. return false;
  23255. }
  23256. var emitterPosition = this.getEmitterPosition();
  23257. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23258. var distance = direction.length();
  23259. direction.normalize();
  23260. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23261. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23262. return !pickInfo.hit || pickInfo.distance > distance;
  23263. };
  23264. LensFlareSystem.prototype.render = function () {
  23265. if (!this._effect.isReady())
  23266. return false;
  23267. var engine = this._scene.getEngine();
  23268. var viewport = this._scene.activeCamera.viewport;
  23269. var globalViewport = viewport.toGlobal(engine);
  23270. // Position
  23271. if (!this.computeEffectivePosition(globalViewport)) {
  23272. return false;
  23273. }
  23274. // Visibility
  23275. if (!this._isVisible()) {
  23276. return false;
  23277. }
  23278. // Intensity
  23279. var awayX;
  23280. var awayY;
  23281. if (this._positionX < this.borderLimit + globalViewport.x) {
  23282. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23283. }
  23284. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23285. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23286. }
  23287. else {
  23288. awayX = 0;
  23289. }
  23290. if (this._positionY < this.borderLimit + globalViewport.y) {
  23291. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23292. }
  23293. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23294. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23295. }
  23296. else {
  23297. awayY = 0;
  23298. }
  23299. var away = (awayX > awayY) ? awayX : awayY;
  23300. if (away > this.borderLimit) {
  23301. away = this.borderLimit;
  23302. }
  23303. var intensity = 1.0 - (away / this.borderLimit);
  23304. if (intensity < 0) {
  23305. return false;
  23306. }
  23307. if (intensity > 1.0) {
  23308. intensity = 1.0;
  23309. }
  23310. // Position
  23311. var centerX = globalViewport.x + globalViewport.width / 2;
  23312. var centerY = globalViewport.y + globalViewport.height / 2;
  23313. var distX = centerX - this._positionX;
  23314. var distY = centerY - this._positionY;
  23315. // Effects
  23316. engine.enableEffect(this._effect);
  23317. engine.setState(false);
  23318. engine.setDepthBuffer(false);
  23319. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23320. // VBOs
  23321. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23322. // Flares
  23323. for (var index = 0; index < this.lensFlares.length; index++) {
  23324. var flare = this.lensFlares[index];
  23325. var x = centerX - (distX * flare.position);
  23326. var y = centerY - (distY * flare.position);
  23327. var cw = flare.size;
  23328. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23329. var cx = 2 * (x / globalViewport.width) - 1.0;
  23330. var cy = 1.0 - 2 * (y / globalViewport.height);
  23331. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23332. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23333. // Texture
  23334. this._effect.setTexture("textureSampler", flare.texture);
  23335. // Color
  23336. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23337. // Draw order
  23338. engine.draw(true, 0, 6);
  23339. }
  23340. engine.setDepthBuffer(true);
  23341. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23342. return true;
  23343. };
  23344. LensFlareSystem.prototype.dispose = function () {
  23345. if (this._vertexBuffer) {
  23346. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23347. this._vertexBuffer = null;
  23348. }
  23349. if (this._indexBuffer) {
  23350. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23351. this._indexBuffer = null;
  23352. }
  23353. while (this.lensFlares.length) {
  23354. this.lensFlares[0].dispose();
  23355. }
  23356. // Remove from scene
  23357. var index = this._scene.lensFlareSystems.indexOf(this);
  23358. this._scene.lensFlareSystems.splice(index, 1);
  23359. };
  23360. return LensFlareSystem;
  23361. })();
  23362. BABYLON.LensFlareSystem = LensFlareSystem;
  23363. })(BABYLON || (BABYLON = {}));
  23364. var BABYLON;
  23365. (function (BABYLON) {
  23366. var CannonJSPlugin = (function () {
  23367. function CannonJSPlugin() {
  23368. this._registeredMeshes = [];
  23369. this._physicsMaterials = [];
  23370. this.updateBodyPosition = function (mesh) {
  23371. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23372. var registeredMesh = this._registeredMeshes[index];
  23373. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23374. var body = registeredMesh.body;
  23375. var center = mesh.getBoundingInfo().boundingBox.center;
  23376. body.position.set(center.x, center.z, center.y);
  23377. body.quaternion.x = mesh.rotationQuaternion.x;
  23378. body.quaternion.z = mesh.rotationQuaternion.y;
  23379. body.quaternion.y = mesh.rotationQuaternion.z;
  23380. body.quaternion.w = -mesh.rotationQuaternion.w;
  23381. return;
  23382. }
  23383. }
  23384. };
  23385. }
  23386. CannonJSPlugin.prototype.initialize = function (iterations) {
  23387. if (iterations === void 0) { iterations = 10; }
  23388. this._world = new CANNON.World();
  23389. this._world.broadphase = new CANNON.NaiveBroadphase();
  23390. this._world.solver.iterations = iterations;
  23391. };
  23392. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23393. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23394. };
  23395. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23396. this._world.step(delta);
  23397. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23398. var registeredMesh = this._registeredMeshes[index];
  23399. if (registeredMesh.isChild) {
  23400. continue;
  23401. }
  23402. // Body position
  23403. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23404. var deltaPos = registeredMesh.delta;
  23405. if (deltaPos) {
  23406. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23407. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23408. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23409. }
  23410. else {
  23411. registeredMesh.mesh.position.x = bodyX;
  23412. registeredMesh.mesh.position.y = bodyZ;
  23413. registeredMesh.mesh.position.z = bodyY;
  23414. }
  23415. if (!registeredMesh.mesh.rotationQuaternion) {
  23416. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23417. }
  23418. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23419. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23420. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23421. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23422. }
  23423. };
  23424. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23425. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23426. };
  23427. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23428. this.unregisterMesh(mesh);
  23429. mesh.computeWorldMatrix(true);
  23430. switch (impostor) {
  23431. case BABYLON.PhysicsEngine.SphereImpostor:
  23432. var bbox = mesh.getBoundingInfo().boundingBox;
  23433. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23434. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23435. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23436. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23437. case BABYLON.PhysicsEngine.BoxImpostor:
  23438. bbox = mesh.getBoundingInfo().boundingBox;
  23439. var min = bbox.minimumWorld;
  23440. var max = bbox.maximumWorld;
  23441. var box = max.subtract(min).scale(0.5);
  23442. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23443. case BABYLON.PhysicsEngine.PlaneImpostor:
  23444. return this._createPlane(mesh, options);
  23445. case BABYLON.PhysicsEngine.MeshImpostor:
  23446. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23447. var rawFaces = mesh.getIndices();
  23448. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23449. }
  23450. return null;
  23451. };
  23452. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23453. var shape = new CANNON.Sphere(radius);
  23454. if (!options) {
  23455. return shape;
  23456. }
  23457. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23458. };
  23459. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23460. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23461. if (!options) {
  23462. return shape;
  23463. }
  23464. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23465. };
  23466. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23467. var shape = new CANNON.Plane();
  23468. if (!options) {
  23469. return shape;
  23470. }
  23471. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23472. };
  23473. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23474. var verts = [], faces = [];
  23475. mesh.computeWorldMatrix(true);
  23476. // Get vertices
  23477. for (var i = 0; i < rawVerts.length; i += 3) {
  23478. var transformed = BABYLON.Vector3.Zero();
  23479. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23480. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23481. }
  23482. // Get faces
  23483. for (var j = 0; j < rawFaces.length; j += 3) {
  23484. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23485. }
  23486. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23487. if (!options) {
  23488. return shape;
  23489. }
  23490. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23491. };
  23492. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23493. var index;
  23494. var mat;
  23495. for (index = 0; index < this._physicsMaterials.length; index++) {
  23496. mat = this._physicsMaterials[index];
  23497. if (mat.friction === friction && mat.restitution === restitution) {
  23498. return mat;
  23499. }
  23500. }
  23501. var currentMat = new CANNON.Material();
  23502. currentMat.friction = friction;
  23503. currentMat.restitution = restitution;
  23504. this._physicsMaterials.push(currentMat);
  23505. for (index = 0; index < this._physicsMaterials.length; index++) {
  23506. mat = this._physicsMaterials[index];
  23507. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23508. contactMaterial.contactEquationStiffness = 1e10;
  23509. contactMaterial.contactEquationRegularizationTime = 10;
  23510. this._world.addContactMaterial(contactMaterial);
  23511. }
  23512. return currentMat;
  23513. };
  23514. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23515. var initialRotation = null;
  23516. if (mesh.rotationQuaternion) {
  23517. initialRotation = mesh.rotationQuaternion.clone();
  23518. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23519. }
  23520. // The delta between the mesh position and the mesh bounding box center
  23521. var bbox = mesh.getBoundingInfo().boundingBox;
  23522. var deltaPosition = mesh.position.subtract(bbox.center);
  23523. var material = this._addMaterial(friction, restitution);
  23524. var body = new CANNON.RigidBody(mass, shape, material);
  23525. if (initialRotation) {
  23526. body.quaternion.x = initialRotation.x;
  23527. body.quaternion.z = initialRotation.y;
  23528. body.quaternion.y = initialRotation.z;
  23529. body.quaternion.w = -initialRotation.w;
  23530. }
  23531. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23532. this._world.add(body);
  23533. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23534. return body;
  23535. };
  23536. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23537. var compoundShape = new CANNON.Compound();
  23538. for (var index = 0; index < parts.length; index++) {
  23539. var mesh = parts[index].mesh;
  23540. var shape = this.registerMesh(mesh, parts[index].impostor);
  23541. if (index == 0) {
  23542. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23543. }
  23544. else {
  23545. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23546. }
  23547. }
  23548. var initialMesh = parts[0].mesh;
  23549. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23550. body.parts = parts;
  23551. return body;
  23552. };
  23553. CannonJSPlugin.prototype._unbindBody = function (body) {
  23554. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23555. var registeredMesh = this._registeredMeshes[index];
  23556. if (registeredMesh.body === body) {
  23557. registeredMesh.body = null;
  23558. registeredMesh.delta = 0;
  23559. }
  23560. }
  23561. };
  23562. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23563. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23564. var registeredMesh = this._registeredMeshes[index];
  23565. if (registeredMesh.mesh === mesh) {
  23566. // Remove body
  23567. if (registeredMesh.body) {
  23568. this._world.remove(registeredMesh.body);
  23569. this._unbindBody(registeredMesh.body);
  23570. }
  23571. this._registeredMeshes.splice(index, 1);
  23572. return;
  23573. }
  23574. }
  23575. };
  23576. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23577. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23578. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23579. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23580. var registeredMesh = this._registeredMeshes[index];
  23581. if (registeredMesh.mesh === mesh) {
  23582. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23583. return;
  23584. }
  23585. }
  23586. };
  23587. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23588. var body1 = null, body2 = null;
  23589. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23590. var registeredMesh = this._registeredMeshes[index];
  23591. if (registeredMesh.mesh === mesh1) {
  23592. body1 = registeredMesh.body;
  23593. }
  23594. else if (registeredMesh.mesh === mesh2) {
  23595. body2 = registeredMesh.body;
  23596. }
  23597. }
  23598. if (!body1 || !body2) {
  23599. return false;
  23600. }
  23601. 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));
  23602. this._world.addConstraint(constraint);
  23603. return true;
  23604. };
  23605. CannonJSPlugin.prototype.dispose = function () {
  23606. while (this._registeredMeshes.length) {
  23607. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23608. }
  23609. };
  23610. CannonJSPlugin.prototype.isSupported = function () {
  23611. return window.CANNON !== undefined;
  23612. };
  23613. return CannonJSPlugin;
  23614. })();
  23615. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23616. })(BABYLON || (BABYLON = {}));
  23617. var BABYLON;
  23618. (function (BABYLON) {
  23619. var OimoJSPlugin = (function () {
  23620. function OimoJSPlugin() {
  23621. this._registeredMeshes = [];
  23622. /**
  23623. * Update the body position according to the mesh position
  23624. * @param mesh
  23625. */
  23626. this.updateBodyPosition = function (mesh) {
  23627. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23628. var registeredMesh = this._registeredMeshes[index];
  23629. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23630. var body = registeredMesh.body.body;
  23631. mesh.computeWorldMatrix(true);
  23632. var center = mesh.getBoundingInfo().boundingBox.center;
  23633. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  23634. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  23635. body.sleeping = false;
  23636. return;
  23637. }
  23638. // Case where the parent has been updated
  23639. if (registeredMesh.mesh.parent === mesh) {
  23640. mesh.computeWorldMatrix(true);
  23641. registeredMesh.mesh.computeWorldMatrix(true);
  23642. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  23643. var absoluteRotation = mesh.rotation;
  23644. body = registeredMesh.body.body;
  23645. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  23646. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  23647. body.sleeping = false;
  23648. return;
  23649. }
  23650. }
  23651. };
  23652. }
  23653. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  23654. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23655. };
  23656. OimoJSPlugin.prototype.initialize = function (iterations) {
  23657. this._world = new OIMO.World();
  23658. this._world.clear();
  23659. };
  23660. OimoJSPlugin.prototype.setGravity = function (gravity) {
  23661. this._world.gravity = gravity;
  23662. };
  23663. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23664. var body = null;
  23665. this.unregisterMesh(mesh);
  23666. mesh.computeWorldMatrix(true);
  23667. var initialRotation = null;
  23668. if (mesh.rotationQuaternion) {
  23669. initialRotation = mesh.rotationQuaternion.clone();
  23670. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23671. mesh.computeWorldMatrix(true);
  23672. }
  23673. var bbox = mesh.getBoundingInfo().boundingBox;
  23674. // The delta between the mesh position and the mesh bounding box center
  23675. var deltaPosition = mesh.position.subtract(bbox.center);
  23676. // Transform delta position with the rotation
  23677. if (initialRotation) {
  23678. var m = new BABYLON.Matrix();
  23679. initialRotation.toRotationMatrix(m);
  23680. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  23681. }
  23682. // register mesh
  23683. switch (impostor) {
  23684. case BABYLON.PhysicsEngine.SphereImpostor:
  23685. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23686. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23687. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23688. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23689. body = new OIMO.Body({
  23690. type: 'sphere',
  23691. size: [size],
  23692. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23693. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23694. move: options.mass != 0,
  23695. config: [options.mass, options.friction, options.restitution],
  23696. world: this._world
  23697. });
  23698. break;
  23699. case BABYLON.PhysicsEngine.PlaneImpostor:
  23700. //Oimo "fakes" a cylinder as a box, so why don't we!
  23701. case BABYLON.PhysicsEngine.CylinderImpostor:
  23702. case BABYLON.PhysicsEngine.BoxImpostor:
  23703. var min = bbox.minimumWorld;
  23704. var max = bbox.maximumWorld;
  23705. var box = max.subtract(min);
  23706. var sizeX = this._checkWithEpsilon(box.x);
  23707. var sizeY = this._checkWithEpsilon(box.y);
  23708. var sizeZ = this._checkWithEpsilon(box.z);
  23709. body = new OIMO.Body({
  23710. type: 'box',
  23711. size: [sizeX, sizeY, sizeZ],
  23712. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23713. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23714. move: options.mass != 0,
  23715. config: [options.mass, options.friction, options.restitution],
  23716. world: this._world
  23717. });
  23718. break;
  23719. }
  23720. //If quaternion was set as the rotation of the object
  23721. if (initialRotation) {
  23722. //We have to access the rigid body's properties to set the quaternion.
  23723. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  23724. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  23725. //update the internal rotation matrix
  23726. body.body.syncShapes();
  23727. }
  23728. this._registeredMeshes.push({
  23729. mesh: mesh,
  23730. body: body,
  23731. delta: deltaPosition
  23732. });
  23733. return body;
  23734. };
  23735. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23736. var types = [], sizes = [], positions = [], rotations = [];
  23737. var initialMesh = parts[0].mesh;
  23738. for (var index = 0; index < parts.length; index++) {
  23739. var part = parts[index];
  23740. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  23741. types.push(bodyParameters.type);
  23742. sizes.push.apply(sizes, bodyParameters.size);
  23743. positions.push.apply(positions, bodyParameters.pos);
  23744. rotations.push.apply(rotations, bodyParameters.rot);
  23745. }
  23746. var body = new OIMO.Body({
  23747. type: types,
  23748. size: sizes,
  23749. pos: positions,
  23750. rot: rotations,
  23751. move: options.mass != 0,
  23752. config: [options.mass, options.friction, options.restitution],
  23753. world: this._world
  23754. });
  23755. this._registeredMeshes.push({
  23756. mesh: initialMesh,
  23757. body: body
  23758. });
  23759. return body;
  23760. };
  23761. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  23762. var bodyParameters = null;
  23763. var mesh = part.mesh;
  23764. // We need the bounding box/sphere info to compute the physics body
  23765. mesh.computeWorldMatrix();
  23766. switch (part.impostor) {
  23767. case BABYLON.PhysicsEngine.SphereImpostor:
  23768. var bbox = mesh.getBoundingInfo().boundingBox;
  23769. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23770. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23771. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23772. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23773. bodyParameters = {
  23774. type: 'sphere',
  23775. /* bug with oimo : sphere needs 3 sizes in this case */
  23776. size: [size, -1, -1],
  23777. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  23778. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23779. };
  23780. break;
  23781. case BABYLON.PhysicsEngine.PlaneImpostor:
  23782. case BABYLON.PhysicsEngine.BoxImpostor:
  23783. bbox = mesh.getBoundingInfo().boundingBox;
  23784. var min = bbox.minimumWorld;
  23785. var max = bbox.maximumWorld;
  23786. var box = max.subtract(min);
  23787. var sizeX = this._checkWithEpsilon(box.x);
  23788. var sizeY = this._checkWithEpsilon(box.y);
  23789. var sizeZ = this._checkWithEpsilon(box.z);
  23790. var relativePosition = mesh.position;
  23791. bodyParameters = {
  23792. type: 'box',
  23793. size: [sizeX, sizeY, sizeZ],
  23794. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  23795. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23796. };
  23797. break;
  23798. }
  23799. return bodyParameters;
  23800. };
  23801. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  23802. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23803. var registeredMesh = this._registeredMeshes[index];
  23804. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23805. if (registeredMesh.body) {
  23806. this._world.removeRigidBody(registeredMesh.body.body);
  23807. this._unbindBody(registeredMesh.body);
  23808. }
  23809. this._registeredMeshes.splice(index, 1);
  23810. return;
  23811. }
  23812. }
  23813. };
  23814. OimoJSPlugin.prototype._unbindBody = function (body) {
  23815. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23816. var registeredMesh = this._registeredMeshes[index];
  23817. if (registeredMesh.body === body) {
  23818. registeredMesh.body = null;
  23819. }
  23820. }
  23821. };
  23822. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23823. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23824. var registeredMesh = this._registeredMeshes[index];
  23825. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23826. // Get object mass to have a behaviour similar to cannon.js
  23827. var mass = registeredMesh.body.body.massInfo.mass;
  23828. // The force is scaled with the mass of object
  23829. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  23830. return;
  23831. }
  23832. }
  23833. };
  23834. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23835. var body1 = null, body2 = null;
  23836. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23837. var registeredMesh = this._registeredMeshes[index];
  23838. if (registeredMesh.mesh === mesh1) {
  23839. body1 = registeredMesh.body.body;
  23840. }
  23841. else if (registeredMesh.mesh === mesh2) {
  23842. body2 = registeredMesh.body.body;
  23843. }
  23844. }
  23845. if (!body1 || !body2) {
  23846. return false;
  23847. }
  23848. if (!options) {
  23849. options = {};
  23850. }
  23851. new OIMO.Link({
  23852. type: options.type,
  23853. body1: body1,
  23854. body2: body2,
  23855. min: options.min,
  23856. max: options.max,
  23857. axe1: options.axe1,
  23858. axe2: options.axe2,
  23859. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23860. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23861. collision: options.collision,
  23862. spring: options.spring,
  23863. world: this._world
  23864. });
  23865. return true;
  23866. };
  23867. OimoJSPlugin.prototype.dispose = function () {
  23868. this._world.clear();
  23869. while (this._registeredMeshes.length) {
  23870. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23871. }
  23872. };
  23873. OimoJSPlugin.prototype.isSupported = function () {
  23874. return OIMO !== undefined;
  23875. };
  23876. OimoJSPlugin.prototype._getLastShape = function (body) {
  23877. var lastShape = body.shapes;
  23878. while (lastShape.next) {
  23879. lastShape = lastShape.next;
  23880. }
  23881. return lastShape;
  23882. };
  23883. OimoJSPlugin.prototype.runOneStep = function (time) {
  23884. this._world.step();
  23885. // Update the position of all registered meshes
  23886. var i = this._registeredMeshes.length;
  23887. var m;
  23888. while (i--) {
  23889. var body = this._registeredMeshes[i].body.body;
  23890. var mesh = this._registeredMeshes[i].mesh;
  23891. var delta = this._registeredMeshes[i].delta;
  23892. if (!body.sleeping) {
  23893. if (body.shapes.next) {
  23894. var parentShape = this._getLastShape(body);
  23895. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23896. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23897. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23898. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23899. if (!mesh.rotationQuaternion) {
  23900. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23901. }
  23902. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23903. mesh.computeWorldMatrix();
  23904. }
  23905. else {
  23906. m = body.getMatrix();
  23907. mtx = BABYLON.Matrix.FromArray(m);
  23908. // Body position
  23909. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23910. if (!delta) {
  23911. mesh.position.x = bodyX;
  23912. mesh.position.y = bodyY;
  23913. mesh.position.z = bodyZ;
  23914. }
  23915. else {
  23916. mesh.position.x = bodyX + delta.x;
  23917. mesh.position.y = bodyY + delta.y;
  23918. mesh.position.z = bodyZ + delta.z;
  23919. }
  23920. if (!mesh.rotationQuaternion) {
  23921. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23922. }
  23923. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23924. mesh.computeWorldMatrix();
  23925. }
  23926. }
  23927. }
  23928. };
  23929. return OimoJSPlugin;
  23930. })();
  23931. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23932. })(BABYLON || (BABYLON = {}));
  23933. var BABYLON;
  23934. (function (BABYLON) {
  23935. var PhysicsEngine = (function () {
  23936. function PhysicsEngine(plugin) {
  23937. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23938. }
  23939. PhysicsEngine.prototype._initialize = function (gravity) {
  23940. this._currentPlugin.initialize();
  23941. this._setGravity(gravity);
  23942. };
  23943. PhysicsEngine.prototype._runOneStep = function (delta) {
  23944. if (delta > 0.1) {
  23945. delta = 0.1;
  23946. }
  23947. else if (delta <= 0) {
  23948. delta = 1.0 / 60.0;
  23949. }
  23950. this._currentPlugin.runOneStep(delta);
  23951. };
  23952. PhysicsEngine.prototype._setGravity = function (gravity) {
  23953. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23954. this._currentPlugin.setGravity(this.gravity);
  23955. };
  23956. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23957. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23958. };
  23959. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23960. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23961. };
  23962. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23963. this._currentPlugin.unregisterMesh(mesh);
  23964. };
  23965. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23966. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23967. };
  23968. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23969. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23970. };
  23971. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23972. this._currentPlugin.updateBodyPosition(mesh);
  23973. };
  23974. PhysicsEngine.prototype.dispose = function () {
  23975. this._currentPlugin.dispose();
  23976. };
  23977. PhysicsEngine.prototype.isSupported = function () {
  23978. return this._currentPlugin.isSupported();
  23979. };
  23980. // Statics
  23981. PhysicsEngine.NoImpostor = 0;
  23982. PhysicsEngine.SphereImpostor = 1;
  23983. PhysicsEngine.BoxImpostor = 2;
  23984. PhysicsEngine.PlaneImpostor = 3;
  23985. PhysicsEngine.MeshImpostor = 4;
  23986. PhysicsEngine.CapsuleImpostor = 5;
  23987. PhysicsEngine.ConeImpostor = 6;
  23988. PhysicsEngine.CylinderImpostor = 7;
  23989. PhysicsEngine.ConvexHullImpostor = 8;
  23990. PhysicsEngine.Epsilon = 0.001;
  23991. return PhysicsEngine;
  23992. })();
  23993. BABYLON.PhysicsEngine = PhysicsEngine;
  23994. })(BABYLON || (BABYLON = {}));
  23995. var BABYLON;
  23996. (function (BABYLON) {
  23997. var serializeLight = function (light) {
  23998. var serializationObject = {};
  23999. serializationObject.name = light.name;
  24000. serializationObject.id = light.id;
  24001. serializationObject.tags = BABYLON.Tags.GetTags(light);
  24002. if (light instanceof BABYLON.PointLight) {
  24003. serializationObject.type = 0;
  24004. serializationObject.position = (light).position.asArray();
  24005. }
  24006. else if (light instanceof BABYLON.DirectionalLight) {
  24007. serializationObject.type = 1;
  24008. var directionalLight = light;
  24009. serializationObject.position = directionalLight.position.asArray();
  24010. serializationObject.direction = directionalLight.direction.asArray();
  24011. }
  24012. else if (light instanceof BABYLON.SpotLight) {
  24013. serializationObject.type = 2;
  24014. var spotLight = light;
  24015. serializationObject.position = spotLight.position.asArray();
  24016. serializationObject.direction = spotLight.position.asArray();
  24017. serializationObject.angle = spotLight.angle;
  24018. serializationObject.exponent = spotLight.exponent;
  24019. }
  24020. else if (light instanceof BABYLON.HemisphericLight) {
  24021. serializationObject.type = 3;
  24022. var hemisphericLight = light;
  24023. serializationObject.direction = hemisphericLight.direction.asArray();
  24024. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  24025. }
  24026. if (light.intensity) {
  24027. serializationObject.intensity = light.intensity;
  24028. }
  24029. serializationObject.range = light.range;
  24030. serializationObject.diffuse = light.diffuse.asArray();
  24031. serializationObject.specular = light.specular.asArray();
  24032. return serializationObject;
  24033. };
  24034. var serializeFresnelParameter = function (fresnelParameter) {
  24035. var serializationObject = {};
  24036. serializationObject.isEnabled = fresnelParameter.isEnabled;
  24037. serializationObject.leftColor = fresnelParameter.leftColor;
  24038. serializationObject.rightColor = fresnelParameter.rightColor;
  24039. serializationObject.bias = fresnelParameter.bias;
  24040. serializationObject.power = fresnelParameter.power;
  24041. return serializationObject;
  24042. };
  24043. var serializeAnimation;
  24044. var appendAnimations = function (source, destination) {
  24045. if (source.animations) {
  24046. destination.animations = [];
  24047. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24048. var animation = source.animations[animationIndex];
  24049. destination.animations.push(serializeAnimation(animation));
  24050. }
  24051. }
  24052. };
  24053. var serializeCamera = function (camera) {
  24054. var serializationObject = {};
  24055. serializationObject.name = camera.name;
  24056. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  24057. serializationObject.id = camera.id;
  24058. serializationObject.position = camera.position.asArray();
  24059. // Parent
  24060. if (camera.parent) {
  24061. serializationObject.parentId = camera.parent.id;
  24062. }
  24063. serializationObject.fov = camera.fov;
  24064. serializationObject.minZ = camera.minZ;
  24065. serializationObject.maxZ = camera.maxZ;
  24066. serializationObject.inertia = camera.inertia;
  24067. //setting the type
  24068. if (camera instanceof BABYLON.FreeCamera) {
  24069. serializationObject.type = "FreeCamera";
  24070. }
  24071. else if (camera instanceof BABYLON.ArcRotateCamera) {
  24072. serializationObject.type = "ArcRotateCamera";
  24073. }
  24074. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24075. serializationObject.type = "AnaglyphArcRotateCamera";
  24076. }
  24077. else if (camera instanceof BABYLON.GamepadCamera) {
  24078. serializationObject.type = "GamepadCamera";
  24079. }
  24080. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  24081. serializationObject.type = "AnaglyphFreeCamera";
  24082. }
  24083. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  24084. serializationObject.type = "DeviceOrientationCamera";
  24085. }
  24086. else if (camera instanceof BABYLON.FollowCamera) {
  24087. serializationObject.type = "FollowCamera";
  24088. }
  24089. else if (camera instanceof BABYLON.TouchCamera) {
  24090. serializationObject.type = "TouchCamera";
  24091. }
  24092. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  24093. serializationObject.type = "VirtualJoysticksCamera";
  24094. }
  24095. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  24096. serializationObject.type = "WebVRFreeCamera";
  24097. }
  24098. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  24099. serializationObject.type = "VRDeviceOrientationFreeCamera";
  24100. }
  24101. //special properties of specific cameras
  24102. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24103. var arcCamera = camera;
  24104. serializationObject.alpha = arcCamera.alpha;
  24105. serializationObject.beta = arcCamera.beta;
  24106. serializationObject.radius = arcCamera.radius;
  24107. if (arcCamera.target && arcCamera.target.id) {
  24108. serializationObject.lockedTargetId = arcCamera.target.id;
  24109. }
  24110. }
  24111. else if (camera instanceof BABYLON.FollowCamera) {
  24112. var followCam = camera;
  24113. serializationObject.radius = followCam.radius;
  24114. serializationObject.heightOffset = followCam.heightOffset;
  24115. serializationObject.rotationOffset = followCam.rotationOffset;
  24116. }
  24117. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24118. //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.
  24119. if (camera['_interaxialDistance'] !== undefined) {
  24120. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24121. }
  24122. }
  24123. //general properties that not all cameras have. The [] is due to typescript's type safety
  24124. if (camera['speed'] !== undefined) {
  24125. serializationObject.speed = camera['speed'];
  24126. }
  24127. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24128. serializationObject.target = camera['target'].asArray();
  24129. }
  24130. // Target
  24131. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24132. serializationObject.rotation = camera['rotation'].asArray();
  24133. }
  24134. // Locked target
  24135. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24136. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24137. }
  24138. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24139. serializationObject.applyGravity = camera['applyGravity'] || false;
  24140. if (camera['ellipsoid']) {
  24141. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24142. }
  24143. // Animations
  24144. appendAnimations(camera, serializationObject);
  24145. // Layer mask
  24146. serializationObject.layerMask = camera.layerMask;
  24147. return serializationObject;
  24148. };
  24149. serializeAnimation = function (animation) {
  24150. var serializationObject = {};
  24151. serializationObject.name = animation.name;
  24152. serializationObject.property = animation.targetProperty;
  24153. serializationObject.framePerSecond = animation.framePerSecond;
  24154. serializationObject.dataType = animation.dataType;
  24155. serializationObject.loopBehavior = animation.loopMode;
  24156. var dataType = animation.dataType;
  24157. serializationObject.keys = [];
  24158. var keys = animation.getKeys();
  24159. for (var index = 0; index < keys.length; index++) {
  24160. var animationKey = keys[index];
  24161. var key = {};
  24162. key.frame = animationKey.frame;
  24163. switch (dataType) {
  24164. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24165. key.values = [animationKey.value];
  24166. break;
  24167. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24168. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24169. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24170. key.values = animationKey.value.asArray();
  24171. break;
  24172. }
  24173. serializationObject.keys.push(key);
  24174. }
  24175. return serializationObject;
  24176. };
  24177. var serializeMultiMaterial = function (material) {
  24178. var serializationObject = {};
  24179. serializationObject.name = material.name;
  24180. serializationObject.id = material.id;
  24181. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24182. serializationObject.materials = [];
  24183. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24184. var subMat = material.subMaterials[matIndex];
  24185. if (subMat) {
  24186. serializationObject.materials.push(subMat.id);
  24187. }
  24188. else {
  24189. serializationObject.materials.push(null);
  24190. }
  24191. }
  24192. return serializationObject;
  24193. };
  24194. var serializeTexture;
  24195. var serializeMaterial = function (material) {
  24196. var serializationObject = {};
  24197. serializationObject.name = material.name;
  24198. serializationObject.ambient = material.ambientColor.asArray();
  24199. serializationObject.diffuse = material.diffuseColor.asArray();
  24200. serializationObject.specular = material.specularColor.asArray();
  24201. serializationObject.specularPower = material.specularPower;
  24202. serializationObject.emissive = material.emissiveColor.asArray();
  24203. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  24204. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  24205. serializationObject.alpha = material.alpha;
  24206. serializationObject.id = material.id;
  24207. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24208. serializationObject.backFaceCulling = material.backFaceCulling;
  24209. if (material.diffuseTexture) {
  24210. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24211. }
  24212. if (material.diffuseFresnelParameters) {
  24213. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24214. }
  24215. if (material.ambientTexture) {
  24216. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24217. }
  24218. if (material.opacityTexture) {
  24219. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24220. }
  24221. if (material.opacityFresnelParameters) {
  24222. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24223. }
  24224. if (material.reflectionTexture) {
  24225. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24226. }
  24227. if (material.reflectionFresnelParameters) {
  24228. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24229. }
  24230. if (material.emissiveTexture) {
  24231. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24232. }
  24233. if (material.emissiveFresnelParameters) {
  24234. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24235. }
  24236. if (material.specularTexture) {
  24237. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24238. }
  24239. if (material.bumpTexture) {
  24240. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24241. }
  24242. return serializationObject;
  24243. };
  24244. serializeTexture = function (texture) {
  24245. var serializationObject = {};
  24246. if (!texture.name) {
  24247. return null;
  24248. }
  24249. if (texture instanceof BABYLON.CubeTexture) {
  24250. serializationObject.name = texture.name;
  24251. serializationObject.hasAlpha = texture.hasAlpha;
  24252. serializationObject.isCube = true;
  24253. serializationObject.level = texture.level;
  24254. serializationObject.coordinatesMode = texture.coordinatesMode;
  24255. return serializationObject;
  24256. }
  24257. var index;
  24258. if (texture instanceof BABYLON.MirrorTexture) {
  24259. var mirrorTexture = texture;
  24260. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24261. serializationObject.renderList = [];
  24262. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  24263. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24264. }
  24265. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24266. }
  24267. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24268. var renderTargetTexture = texture;
  24269. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24270. serializationObject.renderList = [];
  24271. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24272. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24273. }
  24274. }
  24275. var regularTexture = texture;
  24276. serializationObject.name = texture.name;
  24277. serializationObject.hasAlpha = texture.hasAlpha;
  24278. serializationObject.level = texture.level;
  24279. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24280. serializationObject.coordinatesMode = texture.coordinatesMode;
  24281. serializationObject.uOffset = regularTexture.uOffset;
  24282. serializationObject.vOffset = regularTexture.vOffset;
  24283. serializationObject.uScale = regularTexture.uScale;
  24284. serializationObject.vScale = regularTexture.vScale;
  24285. serializationObject.uAng = regularTexture.uAng;
  24286. serializationObject.vAng = regularTexture.vAng;
  24287. serializationObject.wAng = regularTexture.wAng;
  24288. serializationObject.wrapU = texture.wrapU;
  24289. serializationObject.wrapV = texture.wrapV;
  24290. // Animations
  24291. appendAnimations(texture, serializationObject);
  24292. return serializationObject;
  24293. };
  24294. var serializeSkeleton = function (skeleton) {
  24295. var serializationObject = {};
  24296. serializationObject.name = skeleton.name;
  24297. serializationObject.id = skeleton.id;
  24298. serializationObject.bones = [];
  24299. for (var index = 0; index < skeleton.bones.length; index++) {
  24300. var bone = skeleton.bones[index];
  24301. var serializedBone = {
  24302. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24303. name: bone.name,
  24304. matrix: bone.getLocalMatrix().toArray()
  24305. };
  24306. serializationObject.bones.push(serializedBone);
  24307. if (bone.animations && bone.animations.length > 0) {
  24308. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24309. }
  24310. }
  24311. return serializationObject;
  24312. };
  24313. var serializeParticleSystem = function (particleSystem) {
  24314. var serializationObject = {};
  24315. serializationObject.emitterId = particleSystem.emitter.id;
  24316. serializationObject.capacity = particleSystem.getCapacity();
  24317. if (particleSystem.particleTexture) {
  24318. serializationObject.textureName = particleSystem.particleTexture.name;
  24319. }
  24320. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24321. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24322. serializationObject.minSize = particleSystem.minSize;
  24323. serializationObject.maxSize = particleSystem.maxSize;
  24324. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24325. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24326. serializationObject.emitRate = particleSystem.emitRate;
  24327. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24328. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24329. serializationObject.gravity = particleSystem.gravity.asArray();
  24330. serializationObject.direction1 = particleSystem.direction1.asArray();
  24331. serializationObject.direction2 = particleSystem.direction2.asArray();
  24332. serializationObject.color1 = particleSystem.color1.asArray();
  24333. serializationObject.color2 = particleSystem.color2.asArray();
  24334. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24335. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24336. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24337. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24338. serializationObject.blendMode = particleSystem.blendMode;
  24339. return serializationObject;
  24340. };
  24341. var serializeLensFlareSystem = function (lensFlareSystem) {
  24342. var serializationObject = {};
  24343. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24344. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24345. serializationObject.flares = [];
  24346. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24347. var flare = lensFlareSystem.lensFlares[index];
  24348. serializationObject.flares.push({
  24349. size: flare.size,
  24350. position: flare.position,
  24351. color: flare.color.asArray(),
  24352. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24353. });
  24354. }
  24355. return serializationObject;
  24356. };
  24357. var serializeShadowGenerator = function (light) {
  24358. var serializationObject = {};
  24359. var shadowGenerator = light.getShadowGenerator();
  24360. serializationObject.lightId = light.id;
  24361. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24362. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24363. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24364. serializationObject.renderList = [];
  24365. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24366. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24367. serializationObject.renderList.push(mesh.id);
  24368. }
  24369. return serializationObject;
  24370. };
  24371. var serializedGeometries = [];
  24372. var serializeVertexData;
  24373. var serializeTorusKnot;
  24374. var serializePlane;
  24375. var serializeGround;
  24376. var serializeTorus;
  24377. var serializeCylinder;
  24378. var serializeSphere;
  24379. var serializeBox;
  24380. var serializeGeometry = function (geometry, serializationGeometries) {
  24381. if (serializedGeometries[geometry.id]) {
  24382. return;
  24383. }
  24384. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24385. serializationGeometries.boxes.push(serializeBox(geometry));
  24386. }
  24387. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24388. serializationGeometries.spheres.push(serializeSphere(geometry));
  24389. }
  24390. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24391. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24392. }
  24393. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24394. serializationGeometries.toruses.push(serializeTorus(geometry));
  24395. }
  24396. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24397. serializationGeometries.grounds.push(serializeGround(geometry));
  24398. }
  24399. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24400. serializationGeometries.planes.push(serializePlane(geometry));
  24401. }
  24402. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24403. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24404. }
  24405. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24406. throw new Error("Unknown primitive type");
  24407. }
  24408. else {
  24409. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24410. }
  24411. serializedGeometries[geometry.id] = true;
  24412. };
  24413. var serializeGeometryBase = function (geometry) {
  24414. var serializationObject = {};
  24415. serializationObject.id = geometry.id;
  24416. if (BABYLON.Tags.HasTags(geometry)) {
  24417. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24418. }
  24419. return serializationObject;
  24420. };
  24421. serializeVertexData = function (vertexData) {
  24422. var serializationObject = serializeGeometryBase(vertexData);
  24423. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24424. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24425. }
  24426. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24427. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24428. }
  24429. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24430. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24431. }
  24432. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24433. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24434. }
  24435. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24436. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24437. }
  24438. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24439. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24440. }
  24441. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24442. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24443. }
  24444. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24445. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24446. }
  24447. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24448. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24449. }
  24450. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24451. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24452. serializationObject.matricesIndices._isExpanded = true;
  24453. }
  24454. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24455. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24456. }
  24457. serializationObject.indices = vertexData.getIndices();
  24458. return serializationObject;
  24459. };
  24460. var serializePrimitive = function (primitive) {
  24461. var serializationObject = serializeGeometryBase(primitive);
  24462. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24463. return serializationObject;
  24464. };
  24465. serializeBox = function (box) {
  24466. var serializationObject = serializePrimitive(box);
  24467. serializationObject.size = box.size;
  24468. return serializationObject;
  24469. };
  24470. serializeSphere = function (sphere) {
  24471. var serializationObject = serializePrimitive(sphere);
  24472. serializationObject.segments = sphere.segments;
  24473. serializationObject.diameter = sphere.diameter;
  24474. return serializationObject;
  24475. };
  24476. serializeCylinder = function (cylinder) {
  24477. var serializationObject = serializePrimitive(cylinder);
  24478. serializationObject.height = cylinder.height;
  24479. serializationObject.diameterTop = cylinder.diameterTop;
  24480. serializationObject.diameterBottom = cylinder.diameterBottom;
  24481. serializationObject.tessellation = cylinder.tessellation;
  24482. return serializationObject;
  24483. };
  24484. serializeTorus = function (torus) {
  24485. var serializationObject = serializePrimitive(torus);
  24486. serializationObject.diameter = torus.diameter;
  24487. serializationObject.thickness = torus.thickness;
  24488. serializationObject.tessellation = torus.tessellation;
  24489. return serializationObject;
  24490. };
  24491. serializeGround = function (ground) {
  24492. var serializationObject = serializePrimitive(ground);
  24493. serializationObject.width = ground.width;
  24494. serializationObject.height = ground.height;
  24495. serializationObject.subdivisions = ground.subdivisions;
  24496. return serializationObject;
  24497. };
  24498. serializePlane = function (plane) {
  24499. var serializationObject = serializePrimitive(plane);
  24500. serializationObject.size = plane.size;
  24501. return serializationObject;
  24502. };
  24503. serializeTorusKnot = function (torusKnot) {
  24504. var serializationObject = serializePrimitive(torusKnot);
  24505. serializationObject.radius = torusKnot.radius;
  24506. serializationObject.tube = torusKnot.tube;
  24507. serializationObject.radialSegments = torusKnot.radialSegments;
  24508. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24509. serializationObject.p = torusKnot.p;
  24510. serializationObject.q = torusKnot.q;
  24511. return serializationObject;
  24512. };
  24513. var serializeMesh = function (mesh, serializationScene) {
  24514. var serializationObject = {};
  24515. serializationObject.name = mesh.name;
  24516. serializationObject.id = mesh.id;
  24517. if (BABYLON.Tags.HasTags(mesh)) {
  24518. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24519. }
  24520. serializationObject.position = mesh.position.asArray();
  24521. if (mesh.rotationQuaternion) {
  24522. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24523. }
  24524. else if (mesh.rotation) {
  24525. serializationObject.rotation = mesh.rotation.asArray();
  24526. }
  24527. serializationObject.scaling = mesh.scaling.asArray();
  24528. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24529. serializationObject.isEnabled = mesh.isEnabled();
  24530. serializationObject.isVisible = mesh.isVisible;
  24531. serializationObject.infiniteDistance = mesh.infiniteDistance;
  24532. serializationObject.pickable = mesh.isPickable;
  24533. serializationObject.receiveShadows = mesh.receiveShadows;
  24534. serializationObject.billboardMode = mesh.billboardMode;
  24535. serializationObject.visibility = mesh.visibility;
  24536. serializationObject.checkCollisions = mesh.checkCollisions;
  24537. // Parent
  24538. if (mesh.parent) {
  24539. serializationObject.parentId = mesh.parent.id;
  24540. }
  24541. // Geometry
  24542. var geometry = mesh._geometry;
  24543. if (geometry) {
  24544. var geometryId = geometry.id;
  24545. serializationObject.geometryId = geometryId;
  24546. if (!mesh.getScene().getGeometryByID(geometryId)) {
  24547. // 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
  24548. serializeGeometry(geometry, serializationScene.geometries);
  24549. }
  24550. // SubMeshes
  24551. serializationObject.subMeshes = [];
  24552. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24553. var subMesh = mesh.subMeshes[subIndex];
  24554. serializationObject.subMeshes.push({
  24555. materialIndex: subMesh.materialIndex,
  24556. verticesStart: subMesh.verticesStart,
  24557. verticesCount: subMesh.verticesCount,
  24558. indexStart: subMesh.indexStart,
  24559. indexCount: subMesh.indexCount
  24560. });
  24561. }
  24562. }
  24563. // Material
  24564. if (mesh.material) {
  24565. serializationObject.materialId = mesh.material.id;
  24566. }
  24567. else {
  24568. mesh.material = null;
  24569. }
  24570. // Skeleton
  24571. if (mesh.skeleton) {
  24572. serializationObject.skeletonId = mesh.skeleton.id;
  24573. }
  24574. // Physics
  24575. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  24576. serializationObject.physicsMass = mesh.getPhysicsMass();
  24577. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  24578. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  24579. switch (mesh.getPhysicsImpostor()) {
  24580. case BABYLON.PhysicsEngine.BoxImpostor:
  24581. serializationObject.physicsImpostor = 1;
  24582. break;
  24583. case BABYLON.PhysicsEngine.SphereImpostor:
  24584. serializationObject.physicsImpostor = 2;
  24585. break;
  24586. }
  24587. }
  24588. // Instances
  24589. serializationObject.instances = [];
  24590. for (var index = 0; index < mesh.instances.length; index++) {
  24591. var instance = mesh.instances[index];
  24592. var serializationInstance = {
  24593. name: instance.name,
  24594. position: instance.position,
  24595. rotation: instance.rotation,
  24596. rotationQuaternion: instance.rotationQuaternion,
  24597. scaling: instance.scaling
  24598. };
  24599. serializationObject.instances.push(serializationInstance);
  24600. // Animations
  24601. appendAnimations(instance, serializationInstance);
  24602. }
  24603. // Animations
  24604. appendAnimations(mesh, serializationObject);
  24605. // Layer mask
  24606. serializationObject.layerMask = mesh.layerMask;
  24607. return serializationObject;
  24608. };
  24609. var finalizeSingleMesh = function (mesh, serializationObject) {
  24610. //only works if the mesh is already loaded
  24611. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24612. //serialize material
  24613. if (mesh.material) {
  24614. if (mesh.material instanceof BABYLON.StandardMaterial) {
  24615. serializationObject.materials = serializationObject.materials || [];
  24616. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24617. serializationObject.materials.push(serializeMaterial(mesh.material));
  24618. }
  24619. }
  24620. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  24621. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  24622. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24623. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  24624. }
  24625. }
  24626. }
  24627. //serialize geometry
  24628. var geometry = mesh._geometry;
  24629. if (geometry) {
  24630. if (!serializationObject.geometries) {
  24631. serializationObject.geometries = {};
  24632. serializationObject.geometries.boxes = [];
  24633. serializationObject.geometries.spheres = [];
  24634. serializationObject.geometries.cylinders = [];
  24635. serializationObject.geometries.toruses = [];
  24636. serializationObject.geometries.grounds = [];
  24637. serializationObject.geometries.planes = [];
  24638. serializationObject.geometries.torusKnots = [];
  24639. serializationObject.geometries.vertexData = [];
  24640. }
  24641. serializeGeometry(geometry, serializationObject.geometries);
  24642. }
  24643. // Skeletons
  24644. if (mesh.skeleton) {
  24645. serializationObject.skeletons = serializationObject.skeletons || [];
  24646. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  24647. }
  24648. //serialize the actual mesh
  24649. serializationObject.meshes = serializationObject.meshes || [];
  24650. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24651. }
  24652. };
  24653. var SceneSerializer = (function () {
  24654. function SceneSerializer() {
  24655. }
  24656. SceneSerializer.Serialize = function (scene) {
  24657. var serializationObject = {};
  24658. // Scene
  24659. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  24660. serializationObject.autoClear = scene.autoClear;
  24661. serializationObject.clearColor = scene.clearColor.asArray();
  24662. serializationObject.ambientColor = scene.ambientColor.asArray();
  24663. serializationObject.gravity = scene.gravity.asArray();
  24664. // Fog
  24665. if (scene.fogMode && scene.fogMode !== 0) {
  24666. serializationObject.fogMode = scene.fogMode;
  24667. serializationObject.fogColor = scene.fogColor.asArray();
  24668. serializationObject.fogStart = scene.fogStart;
  24669. serializationObject.fogEnd = scene.fogEnd;
  24670. serializationObject.fogDensity = scene.fogDensity;
  24671. }
  24672. // Lights
  24673. serializationObject.lights = [];
  24674. var index;
  24675. var light;
  24676. for (index = 0; index < scene.lights.length; index++) {
  24677. light = scene.lights[index];
  24678. serializationObject.lights.push(serializeLight(light));
  24679. }
  24680. // Cameras
  24681. serializationObject.cameras = [];
  24682. for (index = 0; index < scene.cameras.length; index++) {
  24683. var camera = scene.cameras[index];
  24684. serializationObject.cameras.push(serializeCamera(camera));
  24685. }
  24686. if (scene.activeCamera) {
  24687. serializationObject.activeCameraID = scene.activeCamera.id;
  24688. }
  24689. // Materials
  24690. serializationObject.materials = [];
  24691. serializationObject.multiMaterials = [];
  24692. var material;
  24693. for (index = 0; index < scene.materials.length; index++) {
  24694. material = scene.materials[index];
  24695. serializationObject.materials.push(serializeMaterial(material));
  24696. }
  24697. // MultiMaterials
  24698. serializationObject.multiMaterials = [];
  24699. for (index = 0; index < scene.multiMaterials.length; index++) {
  24700. var multiMaterial = scene.multiMaterials[index];
  24701. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  24702. }
  24703. for (index = 0; index < scene.materials.length; index++) {
  24704. material = scene.materials[index];
  24705. if (material instanceof BABYLON.StandardMaterial) {
  24706. serializationObject.materials.push(serializeMaterial(material));
  24707. }
  24708. else if (material instanceof BABYLON.MultiMaterial) {
  24709. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  24710. }
  24711. }
  24712. // Skeletons
  24713. serializationObject.skeletons = [];
  24714. for (index = 0; index < scene.skeletons.length; index++) {
  24715. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  24716. }
  24717. // Geometries
  24718. serializationObject.geometries = {};
  24719. serializationObject.geometries.boxes = [];
  24720. serializationObject.geometries.spheres = [];
  24721. serializationObject.geometries.cylinders = [];
  24722. serializationObject.geometries.toruses = [];
  24723. serializationObject.geometries.grounds = [];
  24724. serializationObject.geometries.planes = [];
  24725. serializationObject.geometries.torusKnots = [];
  24726. serializationObject.geometries.vertexData = [];
  24727. serializedGeometries = [];
  24728. var geometries = scene.getGeometries();
  24729. for (index = 0; index < geometries.length; index++) {
  24730. var geometry = geometries[index];
  24731. if (geometry.isReady()) {
  24732. serializeGeometry(geometry, serializationObject.geometries);
  24733. }
  24734. }
  24735. // Meshes
  24736. serializationObject.meshes = [];
  24737. for (index = 0; index < scene.meshes.length; index++) {
  24738. var abstractMesh = scene.meshes[index];
  24739. if (abstractMesh instanceof BABYLON.Mesh) {
  24740. var mesh = abstractMesh;
  24741. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24742. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24743. }
  24744. }
  24745. }
  24746. // Particles Systems
  24747. serializationObject.particleSystems = [];
  24748. for (index = 0; index < scene.particleSystems.length; index++) {
  24749. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  24750. }
  24751. // Lens flares
  24752. serializationObject.lensFlareSystems = [];
  24753. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  24754. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  24755. }
  24756. // Shadows
  24757. serializationObject.shadowGenerators = [];
  24758. for (index = 0; index < scene.lights.length; index++) {
  24759. light = scene.lights[index];
  24760. if (light.getShadowGenerator()) {
  24761. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  24762. }
  24763. }
  24764. return serializationObject;
  24765. };
  24766. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  24767. if (withParents === void 0) { withParents = false; }
  24768. if (withChildren === void 0) { withChildren = false; }
  24769. var serializationObject = {};
  24770. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  24771. if (withParents || withChildren) {
  24772. //deliberate for loop! not for each, appended should be processed as well.
  24773. for (var i = 0; i < toSerialize.length; ++i) {
  24774. if (withChildren) {
  24775. toSerialize[i].getDescendants().forEach(function (node) {
  24776. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  24777. toSerialize.push(node);
  24778. }
  24779. });
  24780. }
  24781. //make sure the array doesn't contain the object already
  24782. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  24783. toSerialize.push(toSerialize[i].parent);
  24784. }
  24785. }
  24786. }
  24787. toSerialize.forEach(function (mesh) {
  24788. finalizeSingleMesh(mesh, serializationObject);
  24789. });
  24790. return serializationObject;
  24791. };
  24792. return SceneSerializer;
  24793. })();
  24794. BABYLON.SceneSerializer = SceneSerializer;
  24795. })(BABYLON || (BABYLON = {}));
  24796. var BABYLON;
  24797. (function (BABYLON) {
  24798. // Unique ID when we import meshes from Babylon to CSG
  24799. var currentCSGMeshId = 0;
  24800. // # class Vertex
  24801. // Represents a vertex of a polygon. Use your own vertex class instead of this
  24802. // one to provide additional features like texture coordinates and vertex
  24803. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  24804. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  24805. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  24806. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  24807. // is not used anywhere else.
  24808. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  24809. var Vertex = (function () {
  24810. function Vertex(pos, normal, uv) {
  24811. this.pos = pos;
  24812. this.normal = normal;
  24813. this.uv = uv;
  24814. }
  24815. Vertex.prototype.clone = function () {
  24816. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  24817. };
  24818. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  24819. // orientation of a polygon is flipped.
  24820. Vertex.prototype.flip = function () {
  24821. this.normal = this.normal.scale(-1);
  24822. };
  24823. // Create a new vertex between this vertex and `other` by linearly
  24824. // interpolating all properties using a parameter of `t`. Subclasses should
  24825. // override this to interpolate additional properties.
  24826. Vertex.prototype.interpolate = function (other, t) {
  24827. 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));
  24828. };
  24829. return Vertex;
  24830. })();
  24831. // # class Plane
  24832. // Represents a plane in 3D space.
  24833. var Plane = (function () {
  24834. function Plane(normal, w) {
  24835. this.normal = normal;
  24836. this.w = w;
  24837. }
  24838. Plane.FromPoints = function (a, b, c) {
  24839. var v0 = c.subtract(a);
  24840. var v1 = b.subtract(a);
  24841. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  24842. return null;
  24843. }
  24844. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  24845. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  24846. };
  24847. Plane.prototype.clone = function () {
  24848. return new Plane(this.normal.clone(), this.w);
  24849. };
  24850. Plane.prototype.flip = function () {
  24851. this.normal.scaleInPlace(-1);
  24852. this.w = -this.w;
  24853. };
  24854. // Split `polygon` by this plane if needed, then put the polygon or polygon
  24855. // fragments in the appropriate lists. Coplanar polygons go into either
  24856. // `coplanarFront` or `coplanarBack` depending on their orientation with
  24857. // respect to this plane. Polygons in front or in back of this plane go into
  24858. // either `front` or `back`.
  24859. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  24860. var COPLANAR = 0;
  24861. var FRONT = 1;
  24862. var BACK = 2;
  24863. var SPANNING = 3;
  24864. // Classify each point as well as the entire polygon into one of the above
  24865. // four classes.
  24866. var polygonType = 0;
  24867. var types = [];
  24868. for (var i = 0; i < polygon.vertices.length; i++) {
  24869. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  24870. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  24871. polygonType |= type;
  24872. types.push(type);
  24873. }
  24874. // Put the polygon in the correct list, splitting it when necessary.
  24875. switch (polygonType) {
  24876. case COPLANAR:
  24877. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  24878. break;
  24879. case FRONT:
  24880. front.push(polygon);
  24881. break;
  24882. case BACK:
  24883. back.push(polygon);
  24884. break;
  24885. case SPANNING:
  24886. var f = [], b = [];
  24887. for (i = 0; i < polygon.vertices.length; i++) {
  24888. var j = (i + 1) % polygon.vertices.length;
  24889. var ti = types[i], tj = types[j];
  24890. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  24891. if (ti != BACK)
  24892. f.push(vi);
  24893. if (ti != FRONT)
  24894. b.push(ti != BACK ? vi.clone() : vi);
  24895. if ((ti | tj) == SPANNING) {
  24896. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  24897. var v = vi.interpolate(vj, t);
  24898. f.push(v);
  24899. b.push(v.clone());
  24900. }
  24901. }
  24902. if (f.length >= 3) {
  24903. var poly = new Polygon(f, polygon.shared);
  24904. if (poly.plane)
  24905. front.push(poly);
  24906. }
  24907. if (b.length >= 3) {
  24908. poly = new Polygon(b, polygon.shared);
  24909. if (poly.plane)
  24910. back.push(poly);
  24911. }
  24912. break;
  24913. }
  24914. };
  24915. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  24916. // point is on the plane.
  24917. Plane.EPSILON = 1e-5;
  24918. return Plane;
  24919. })();
  24920. // # class Polygon
  24921. // Represents a convex polygon. The vertices used to initialize a polygon must
  24922. // be coplanar and form a convex loop.
  24923. //
  24924. // Each convex polygon has a `shared` property, which is shared between all
  24925. // polygons that are clones of each other or were split from the same polygon.
  24926. // This can be used to define per-polygon properties (such as surface color).
  24927. var Polygon = (function () {
  24928. function Polygon(vertices, shared) {
  24929. this.vertices = vertices;
  24930. this.shared = shared;
  24931. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  24932. }
  24933. Polygon.prototype.clone = function () {
  24934. var vertices = this.vertices.map(function (v) { return v.clone(); });
  24935. return new Polygon(vertices, this.shared);
  24936. };
  24937. Polygon.prototype.flip = function () {
  24938. this.vertices.reverse().map(function (v) { v.flip(); });
  24939. this.plane.flip();
  24940. };
  24941. return Polygon;
  24942. })();
  24943. // # class Node
  24944. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  24945. // by picking a polygon to split along. That polygon (and all other coplanar
  24946. // polygons) are added directly to that node and the other polygons are added to
  24947. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  24948. // no distinction between internal and leaf nodes.
  24949. var Node = (function () {
  24950. function Node(polygons) {
  24951. this.plane = null;
  24952. this.front = null;
  24953. this.back = null;
  24954. this.polygons = [];
  24955. if (polygons) {
  24956. this.build(polygons);
  24957. }
  24958. }
  24959. Node.prototype.clone = function () {
  24960. var node = new Node();
  24961. node.plane = this.plane && this.plane.clone();
  24962. node.front = this.front && this.front.clone();
  24963. node.back = this.back && this.back.clone();
  24964. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  24965. return node;
  24966. };
  24967. // Convert solid space to empty space and empty space to solid space.
  24968. Node.prototype.invert = function () {
  24969. for (var i = 0; i < this.polygons.length; i++) {
  24970. this.polygons[i].flip();
  24971. }
  24972. if (this.plane) {
  24973. this.plane.flip();
  24974. }
  24975. if (this.front) {
  24976. this.front.invert();
  24977. }
  24978. if (this.back) {
  24979. this.back.invert();
  24980. }
  24981. var temp = this.front;
  24982. this.front = this.back;
  24983. this.back = temp;
  24984. };
  24985. // Recursively remove all polygons in `polygons` that are inside this BSP
  24986. // tree.
  24987. Node.prototype.clipPolygons = function (polygons) {
  24988. if (!this.plane)
  24989. return polygons.slice();
  24990. var front = [], back = [];
  24991. for (var i = 0; i < polygons.length; i++) {
  24992. this.plane.splitPolygon(polygons[i], front, back, front, back);
  24993. }
  24994. if (this.front) {
  24995. front = this.front.clipPolygons(front);
  24996. }
  24997. if (this.back) {
  24998. back = this.back.clipPolygons(back);
  24999. }
  25000. else {
  25001. back = [];
  25002. }
  25003. return front.concat(back);
  25004. };
  25005. // Remove all polygons in this BSP tree that are inside the other BSP tree
  25006. // `bsp`.
  25007. Node.prototype.clipTo = function (bsp) {
  25008. this.polygons = bsp.clipPolygons(this.polygons);
  25009. if (this.front)
  25010. this.front.clipTo(bsp);
  25011. if (this.back)
  25012. this.back.clipTo(bsp);
  25013. };
  25014. // Return a list of all polygons in this BSP tree.
  25015. Node.prototype.allPolygons = function () {
  25016. var polygons = this.polygons.slice();
  25017. if (this.front)
  25018. polygons = polygons.concat(this.front.allPolygons());
  25019. if (this.back)
  25020. polygons = polygons.concat(this.back.allPolygons());
  25021. return polygons;
  25022. };
  25023. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  25024. // new polygons are filtered down to the bottom of the tree and become new
  25025. // nodes there. Each set of polygons is partitioned using the first polygon
  25026. // (no heuristic is used to pick a good split).
  25027. Node.prototype.build = function (polygons) {
  25028. if (!polygons.length)
  25029. return;
  25030. if (!this.plane)
  25031. this.plane = polygons[0].plane.clone();
  25032. var front = [], back = [];
  25033. for (var i = 0; i < polygons.length; i++) {
  25034. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  25035. }
  25036. if (front.length) {
  25037. if (!this.front)
  25038. this.front = new Node();
  25039. this.front.build(front);
  25040. }
  25041. if (back.length) {
  25042. if (!this.back)
  25043. this.back = new Node();
  25044. this.back.build(back);
  25045. }
  25046. };
  25047. return Node;
  25048. })();
  25049. var CSG = (function () {
  25050. function CSG() {
  25051. this.polygons = new Array();
  25052. }
  25053. // Convert BABYLON.Mesh to BABYLON.CSG
  25054. CSG.FromMesh = function (mesh) {
  25055. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  25056. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  25057. if (mesh instanceof BABYLON.Mesh) {
  25058. mesh.computeWorldMatrix(true);
  25059. matrix = mesh.getWorldMatrix();
  25060. meshPosition = mesh.position.clone();
  25061. meshRotation = mesh.rotation.clone();
  25062. if (mesh.rotationQuaternion) {
  25063. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  25064. }
  25065. meshScaling = mesh.scaling.clone();
  25066. }
  25067. else {
  25068. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  25069. }
  25070. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25071. var subMeshes = mesh.subMeshes;
  25072. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  25073. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  25074. vertices = [];
  25075. for (var j = 0; j < 3; j++) {
  25076. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  25077. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  25078. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  25079. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  25080. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  25081. vertex = new Vertex(position, normal, uv);
  25082. vertices.push(vertex);
  25083. }
  25084. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  25085. // To handle the case of degenerated triangle
  25086. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  25087. if (polygon.plane)
  25088. polygons.push(polygon);
  25089. }
  25090. }
  25091. var csg = CSG.FromPolygons(polygons);
  25092. csg.matrix = matrix;
  25093. csg.position = meshPosition;
  25094. csg.rotation = meshRotation;
  25095. csg.scaling = meshScaling;
  25096. csg.rotationQuaternion = meshRotationQuaternion;
  25097. currentCSGMeshId++;
  25098. return csg;
  25099. };
  25100. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  25101. CSG.FromPolygons = function (polygons) {
  25102. var csg = new CSG();
  25103. csg.polygons = polygons;
  25104. return csg;
  25105. };
  25106. CSG.prototype.clone = function () {
  25107. var csg = new CSG();
  25108. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  25109. csg.copyTransformAttributes(this);
  25110. return csg;
  25111. };
  25112. CSG.prototype.toPolygons = function () {
  25113. return this.polygons;
  25114. };
  25115. CSG.prototype.union = function (csg) {
  25116. var a = new Node(this.clone().polygons);
  25117. var b = new Node(csg.clone().polygons);
  25118. a.clipTo(b);
  25119. b.clipTo(a);
  25120. b.invert();
  25121. b.clipTo(a);
  25122. b.invert();
  25123. a.build(b.allPolygons());
  25124. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25125. };
  25126. CSG.prototype.unionInPlace = function (csg) {
  25127. var a = new Node(this.polygons);
  25128. var b = new Node(csg.polygons);
  25129. a.clipTo(b);
  25130. b.clipTo(a);
  25131. b.invert();
  25132. b.clipTo(a);
  25133. b.invert();
  25134. a.build(b.allPolygons());
  25135. this.polygons = a.allPolygons();
  25136. };
  25137. CSG.prototype.subtract = function (csg) {
  25138. var a = new Node(this.clone().polygons);
  25139. var b = new Node(csg.clone().polygons);
  25140. a.invert();
  25141. a.clipTo(b);
  25142. b.clipTo(a);
  25143. b.invert();
  25144. b.clipTo(a);
  25145. b.invert();
  25146. a.build(b.allPolygons());
  25147. a.invert();
  25148. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25149. };
  25150. CSG.prototype.subtractInPlace = function (csg) {
  25151. var a = new Node(this.polygons);
  25152. var b = new Node(csg.polygons);
  25153. a.invert();
  25154. a.clipTo(b);
  25155. b.clipTo(a);
  25156. b.invert();
  25157. b.clipTo(a);
  25158. b.invert();
  25159. a.build(b.allPolygons());
  25160. a.invert();
  25161. this.polygons = a.allPolygons();
  25162. };
  25163. CSG.prototype.intersect = function (csg) {
  25164. var a = new Node(this.clone().polygons);
  25165. var b = new Node(csg.clone().polygons);
  25166. a.invert();
  25167. b.clipTo(a);
  25168. b.invert();
  25169. a.clipTo(b);
  25170. b.clipTo(a);
  25171. a.build(b.allPolygons());
  25172. a.invert();
  25173. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25174. };
  25175. CSG.prototype.intersectInPlace = function (csg) {
  25176. var a = new Node(this.polygons);
  25177. var b = new Node(csg.polygons);
  25178. a.invert();
  25179. b.clipTo(a);
  25180. b.invert();
  25181. a.clipTo(b);
  25182. b.clipTo(a);
  25183. a.build(b.allPolygons());
  25184. a.invert();
  25185. this.polygons = a.allPolygons();
  25186. };
  25187. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25188. // not modified.
  25189. CSG.prototype.inverse = function () {
  25190. var csg = this.clone();
  25191. csg.inverseInPlace();
  25192. return csg;
  25193. };
  25194. CSG.prototype.inverseInPlace = function () {
  25195. this.polygons.map(function (p) { p.flip(); });
  25196. };
  25197. // This is used to keep meshes transformations so they can be restored
  25198. // when we build back a Babylon Mesh
  25199. // NB : All CSG operations are performed in world coordinates
  25200. CSG.prototype.copyTransformAttributes = function (csg) {
  25201. this.matrix = csg.matrix;
  25202. this.position = csg.position;
  25203. this.rotation = csg.rotation;
  25204. this.scaling = csg.scaling;
  25205. this.rotationQuaternion = csg.rotationQuaternion;
  25206. return this;
  25207. };
  25208. // Build Raw mesh from CSG
  25209. // Coordinates here are in world space
  25210. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25211. var matrix = this.matrix.clone();
  25212. matrix.invert();
  25213. 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;
  25214. if (keepSubMeshes) {
  25215. // Sort Polygons, since subMeshes are indices range
  25216. polygons.sort(function (a, b) {
  25217. if (a.shared.meshId === b.shared.meshId) {
  25218. return a.shared.subMeshId - b.shared.subMeshId;
  25219. }
  25220. else {
  25221. return a.shared.meshId - b.shared.meshId;
  25222. }
  25223. });
  25224. }
  25225. for (var i = 0, il = polygons.length; i < il; i++) {
  25226. polygon = polygons[i];
  25227. // Building SubMeshes
  25228. if (!subMesh_dict[polygon.shared.meshId]) {
  25229. subMesh_dict[polygon.shared.meshId] = {};
  25230. }
  25231. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25232. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25233. indexStart: +Infinity,
  25234. indexEnd: -Infinity,
  25235. materialIndex: polygon.shared.materialIndex
  25236. };
  25237. }
  25238. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25239. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25240. polygonIndices[0] = 0;
  25241. polygonIndices[1] = j - 1;
  25242. polygonIndices[2] = j;
  25243. for (var k = 0; k < 3; k++) {
  25244. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25245. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25246. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25247. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25248. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25249. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25250. // Check if 2 points can be merged
  25251. if (!(typeof vertex_idx !== 'undefined' &&
  25252. normals[vertex_idx * 3] === localNormal.x &&
  25253. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25254. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25255. uvs[vertex_idx * 2] === uv.x &&
  25256. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25257. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25258. uvs.push(uv.x, uv.y);
  25259. normals.push(normal.x, normal.y, normal.z);
  25260. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25261. }
  25262. indices.push(vertex_idx);
  25263. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25264. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25265. currentIndex++;
  25266. }
  25267. }
  25268. }
  25269. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25270. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25271. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25272. mesh.setIndices(indices);
  25273. if (keepSubMeshes) {
  25274. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25275. var materialIndexOffset = 0, materialMaxIndex;
  25276. mesh.subMeshes.length = 0;
  25277. for (var m in subMesh_dict) {
  25278. materialMaxIndex = -1;
  25279. for (var sm in subMesh_dict[m]) {
  25280. subMesh_obj = subMesh_dict[m][sm];
  25281. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25282. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25283. }
  25284. materialIndexOffset += ++materialMaxIndex;
  25285. }
  25286. }
  25287. return mesh;
  25288. };
  25289. // Build Mesh from CSG taking material and transforms into account
  25290. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25291. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25292. mesh.material = material;
  25293. mesh.position.copyFrom(this.position);
  25294. mesh.rotation.copyFrom(this.rotation);
  25295. if (this.rotationQuaternion) {
  25296. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25297. }
  25298. mesh.scaling.copyFrom(this.scaling);
  25299. mesh.computeWorldMatrix(true);
  25300. return mesh;
  25301. };
  25302. return CSG;
  25303. })();
  25304. BABYLON.CSG = CSG;
  25305. })(BABYLON || (BABYLON = {}));
  25306. var BABYLON;
  25307. (function (BABYLON) {
  25308. var VRDistortionCorrectionPostProcess = (function (_super) {
  25309. __extends(VRDistortionCorrectionPostProcess, _super);
  25310. //ANY
  25311. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25312. var _this = this;
  25313. _super.call(this, name, "vrDistortionCorrection", [
  25314. 'LensCenter',
  25315. 'Scale',
  25316. 'ScaleIn',
  25317. 'HmdWarpParam'
  25318. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25319. this._isRightEye = isRightEye;
  25320. this._distortionFactors = vrMetrics.distortionK;
  25321. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25322. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25323. this.onSizeChanged = function () {
  25324. _this.aspectRatio = _this.width * .5 / _this.height;
  25325. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25326. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25327. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25328. };
  25329. this.onApply = function (effect) {
  25330. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25331. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25332. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25333. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25334. };
  25335. }
  25336. return VRDistortionCorrectionPostProcess;
  25337. })(BABYLON.PostProcess);
  25338. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25339. })(BABYLON || (BABYLON = {}));
  25340. // Mainly based on these 2 articles :
  25341. // 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
  25342. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25343. var BABYLON;
  25344. (function (BABYLON) {
  25345. (function (JoystickAxis) {
  25346. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25347. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25348. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25349. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25350. var JoystickAxis = BABYLON.JoystickAxis;
  25351. var VirtualJoystick = (function () {
  25352. function VirtualJoystick(leftJoystick) {
  25353. var _this = this;
  25354. if (leftJoystick) {
  25355. this._leftJoystick = true;
  25356. }
  25357. else {
  25358. this._leftJoystick = false;
  25359. }
  25360. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25361. VirtualJoystick._globalJoystickIndex++;
  25362. // By default left & right arrow keys are moving the X
  25363. // and up & down keys are moving the Y
  25364. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25365. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25366. this.reverseLeftRight = false;
  25367. this.reverseUpDown = false;
  25368. // collections of pointers
  25369. this._touches = new BABYLON.SmartCollection();
  25370. this.deltaPosition = BABYLON.Vector3.Zero();
  25371. this._joystickSensibility = 25;
  25372. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25373. this._rotationSpeed = 25;
  25374. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25375. this._rotateOnAxisRelativeToMesh = false;
  25376. this._onResize = function (evt) {
  25377. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25378. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25379. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25380. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25381. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25382. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25383. };
  25384. // injecting a canvas element on top of the canvas 3D game
  25385. if (!VirtualJoystick.vjCanvas) {
  25386. window.addEventListener("resize", this._onResize, false);
  25387. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25388. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25389. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25390. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25391. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25392. VirtualJoystick.vjCanvas.style.width = "100%";
  25393. VirtualJoystick.vjCanvas.style.height = "100%";
  25394. VirtualJoystick.vjCanvas.style.position = "absolute";
  25395. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25396. VirtualJoystick.vjCanvas.style.top = "0px";
  25397. VirtualJoystick.vjCanvas.style.left = "0px";
  25398. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25399. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25400. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25401. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25402. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25403. document.body.appendChild(VirtualJoystick.vjCanvas);
  25404. }
  25405. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25406. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25407. this.pressed = false;
  25408. // default joystick color
  25409. this._joystickColor = "cyan";
  25410. this._joystickPointerID = -1;
  25411. // current joystick position
  25412. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25413. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25414. // origin joystick position
  25415. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25416. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25417. this._onPointerDownHandlerRef = function (evt) {
  25418. _this._onPointerDown(evt);
  25419. };
  25420. this._onPointerMoveHandlerRef = function (evt) {
  25421. _this._onPointerMove(evt);
  25422. };
  25423. this._onPointerOutHandlerRef = function (evt) {
  25424. _this._onPointerUp(evt);
  25425. };
  25426. this._onPointerUpHandlerRef = function (evt) {
  25427. _this._onPointerUp(evt);
  25428. };
  25429. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25430. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25431. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25432. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25433. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25434. evt.preventDefault(); // Disables system menu
  25435. }, false);
  25436. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25437. }
  25438. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25439. this._joystickSensibility = newJoystickSensibility;
  25440. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25441. };
  25442. VirtualJoystick.prototype._onPointerDown = function (e) {
  25443. var positionOnScreenCondition;
  25444. e.preventDefault();
  25445. if (this._leftJoystick === true) {
  25446. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25447. }
  25448. else {
  25449. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25450. }
  25451. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25452. // First contact will be dedicated to the virtual joystick
  25453. this._joystickPointerID = e.pointerId;
  25454. this._joystickPointerStartPos.x = e.clientX;
  25455. this._joystickPointerStartPos.y = e.clientY;
  25456. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25457. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25458. this._deltaJoystickVector.x = 0;
  25459. this._deltaJoystickVector.y = 0;
  25460. this.pressed = true;
  25461. this._touches.add(e.pointerId.toString(), e);
  25462. }
  25463. else {
  25464. // You can only trigger the action buttons with a joystick declared
  25465. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25466. this._action();
  25467. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25468. }
  25469. }
  25470. };
  25471. VirtualJoystick.prototype._onPointerMove = function (e) {
  25472. // If the current pointer is the one associated to the joystick (first touch contact)
  25473. if (this._joystickPointerID == e.pointerId) {
  25474. this._joystickPointerPos.x = e.clientX;
  25475. this._joystickPointerPos.y = e.clientY;
  25476. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25477. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25478. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25479. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25480. switch (this._axisTargetedByLeftAndRight) {
  25481. case JoystickAxis.X:
  25482. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25483. break;
  25484. case JoystickAxis.Y:
  25485. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25486. break;
  25487. case JoystickAxis.Z:
  25488. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25489. break;
  25490. }
  25491. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25492. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25493. switch (this._axisTargetedByUpAndDown) {
  25494. case JoystickAxis.X:
  25495. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25496. break;
  25497. case JoystickAxis.Y:
  25498. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25499. break;
  25500. case JoystickAxis.Z:
  25501. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25502. break;
  25503. }
  25504. }
  25505. else {
  25506. if (this._touches.item(e.pointerId.toString())) {
  25507. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25508. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25509. }
  25510. }
  25511. };
  25512. VirtualJoystick.prototype._onPointerUp = function (e) {
  25513. if (this._joystickPointerID == e.pointerId) {
  25514. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25515. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25516. this._joystickPointerID = -1;
  25517. this.pressed = false;
  25518. }
  25519. else {
  25520. var touch = this._touches.item(e.pointerId.toString());
  25521. if (touch) {
  25522. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25523. }
  25524. }
  25525. this._deltaJoystickVector.x = 0;
  25526. this._deltaJoystickVector.y = 0;
  25527. this._touches.remove(e.pointerId.toString());
  25528. };
  25529. /**
  25530. * Change the color of the virtual joystick
  25531. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  25532. */
  25533. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  25534. this._joystickColor = newColor;
  25535. };
  25536. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  25537. this._action = action;
  25538. };
  25539. // Define which axis you'd like to control for left & right
  25540. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  25541. switch (axis) {
  25542. case JoystickAxis.X:
  25543. case JoystickAxis.Y:
  25544. case JoystickAxis.Z:
  25545. this._axisTargetedByLeftAndRight = axis;
  25546. break;
  25547. default:
  25548. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25549. break;
  25550. }
  25551. };
  25552. // Define which axis you'd like to control for up & down
  25553. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  25554. switch (axis) {
  25555. case JoystickAxis.X:
  25556. case JoystickAxis.Y:
  25557. case JoystickAxis.Z:
  25558. this._axisTargetedByUpAndDown = axis;
  25559. break;
  25560. default:
  25561. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25562. break;
  25563. }
  25564. };
  25565. VirtualJoystick.prototype._clearCanvas = function () {
  25566. if (this._leftJoystick) {
  25567. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  25568. }
  25569. else {
  25570. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  25571. }
  25572. };
  25573. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  25574. var _this = this;
  25575. if (this.pressed) {
  25576. this._touches.forEach(function (touch) {
  25577. if (touch.pointerId === _this._joystickPointerID) {
  25578. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  25579. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  25580. VirtualJoystick.vjCanvasContext.beginPath();
  25581. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25582. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25583. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  25584. VirtualJoystick.vjCanvasContext.stroke();
  25585. VirtualJoystick.vjCanvasContext.closePath();
  25586. VirtualJoystick.vjCanvasContext.beginPath();
  25587. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25588. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25589. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  25590. VirtualJoystick.vjCanvasContext.stroke();
  25591. VirtualJoystick.vjCanvasContext.closePath();
  25592. VirtualJoystick.vjCanvasContext.beginPath();
  25593. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25594. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  25595. VirtualJoystick.vjCanvasContext.stroke();
  25596. VirtualJoystick.vjCanvasContext.closePath();
  25597. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  25598. }
  25599. else {
  25600. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25601. VirtualJoystick.vjCanvasContext.beginPath();
  25602. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  25603. VirtualJoystick.vjCanvasContext.beginPath();
  25604. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  25605. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25606. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  25607. VirtualJoystick.vjCanvasContext.stroke();
  25608. VirtualJoystick.vjCanvasContext.closePath();
  25609. touch.prevX = touch.x;
  25610. touch.prevY = touch.y;
  25611. }
  25612. ;
  25613. });
  25614. }
  25615. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25616. };
  25617. VirtualJoystick.prototype.releaseCanvas = function () {
  25618. if (VirtualJoystick.vjCanvas) {
  25619. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  25620. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  25621. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  25622. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  25623. window.removeEventListener("resize", this._onResize);
  25624. document.body.removeChild(VirtualJoystick.vjCanvas);
  25625. VirtualJoystick.vjCanvas = null;
  25626. }
  25627. };
  25628. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  25629. VirtualJoystick._globalJoystickIndex = 0;
  25630. return VirtualJoystick;
  25631. })();
  25632. BABYLON.VirtualJoystick = VirtualJoystick;
  25633. })(BABYLON || (BABYLON = {}));
  25634. var BABYLON;
  25635. (function (BABYLON) {
  25636. // We're mainly based on the logic defined into the FreeCamera code
  25637. var VirtualJoysticksCamera = (function (_super) {
  25638. __extends(VirtualJoysticksCamera, _super);
  25639. function VirtualJoysticksCamera(name, position, scene) {
  25640. _super.call(this, name, position, scene);
  25641. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  25642. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  25643. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  25644. this._leftjoystick.setJoystickSensibility(0.15);
  25645. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  25646. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  25647. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  25648. this._rightjoystick.reverseUpDown = true;
  25649. this._rightjoystick.setJoystickSensibility(0.05);
  25650. this._rightjoystick.setJoystickColor("yellow");
  25651. }
  25652. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  25653. return this._leftjoystick;
  25654. };
  25655. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  25656. return this._rightjoystick;
  25657. };
  25658. VirtualJoysticksCamera.prototype._checkInputs = function () {
  25659. var speed = this._computeLocalCameraSpeed() * 50;
  25660. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25661. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  25662. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25663. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  25664. if (!this._leftjoystick.pressed) {
  25665. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  25666. }
  25667. if (!this._rightjoystick.pressed) {
  25668. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  25669. }
  25670. _super.prototype._checkInputs.call(this);
  25671. };
  25672. VirtualJoysticksCamera.prototype.dispose = function () {
  25673. this._leftjoystick.releaseCanvas();
  25674. _super.prototype.dispose.call(this);
  25675. };
  25676. return VirtualJoysticksCamera;
  25677. })(BABYLON.FreeCamera);
  25678. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  25679. })(BABYLON || (BABYLON = {}));
  25680. var BABYLON;
  25681. (function (BABYLON) {
  25682. var ShaderMaterial = (function (_super) {
  25683. __extends(ShaderMaterial, _super);
  25684. function ShaderMaterial(name, scene, shaderPath, options) {
  25685. _super.call(this, name, scene);
  25686. this._textures = new Array();
  25687. this._floats = new Array();
  25688. this._floatsArrays = {};
  25689. this._colors3 = new Array();
  25690. this._colors4 = new Array();
  25691. this._vectors2 = new Array();
  25692. this._vectors3 = new Array();
  25693. this._vectors4 = new Array();
  25694. this._matrices = new Array();
  25695. this._matrices3x3 = new Array();
  25696. this._matrices2x2 = new Array();
  25697. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  25698. this._shaderPath = shaderPath;
  25699. options.needAlphaBlending = options.needAlphaBlending || false;
  25700. options.needAlphaTesting = options.needAlphaTesting || false;
  25701. options.attributes = options.attributes || ["position", "normal", "uv"];
  25702. options.uniforms = options.uniforms || ["worldViewProjection"];
  25703. options.samplers = options.samplers || [];
  25704. options.defines = options.defines || [];
  25705. this._options = options;
  25706. }
  25707. ShaderMaterial.prototype.needAlphaBlending = function () {
  25708. return this._options.needAlphaBlending;
  25709. };
  25710. ShaderMaterial.prototype.needAlphaTesting = function () {
  25711. return this._options.needAlphaTesting;
  25712. };
  25713. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  25714. if (this._options.uniforms.indexOf(uniformName) === -1) {
  25715. this._options.uniforms.push(uniformName);
  25716. }
  25717. };
  25718. ShaderMaterial.prototype.setTexture = function (name, texture) {
  25719. if (this._options.samplers.indexOf(name) === -1) {
  25720. this._options.samplers.push(name);
  25721. }
  25722. this._textures[name] = texture;
  25723. return this;
  25724. };
  25725. ShaderMaterial.prototype.setFloat = function (name, value) {
  25726. this._checkUniform(name);
  25727. this._floats[name] = value;
  25728. return this;
  25729. };
  25730. ShaderMaterial.prototype.setFloats = function (name, value) {
  25731. this._checkUniform(name);
  25732. this._floatsArrays[name] = value;
  25733. return this;
  25734. };
  25735. ShaderMaterial.prototype.setColor3 = function (name, value) {
  25736. this._checkUniform(name);
  25737. this._colors3[name] = value;
  25738. return this;
  25739. };
  25740. ShaderMaterial.prototype.setColor4 = function (name, value) {
  25741. this._checkUniform(name);
  25742. this._colors4[name] = value;
  25743. return this;
  25744. };
  25745. ShaderMaterial.prototype.setVector2 = function (name, value) {
  25746. this._checkUniform(name);
  25747. this._vectors2[name] = value;
  25748. return this;
  25749. };
  25750. ShaderMaterial.prototype.setVector3 = function (name, value) {
  25751. this._checkUniform(name);
  25752. this._vectors3[name] = value;
  25753. return this;
  25754. };
  25755. ShaderMaterial.prototype.setVector4 = function (name, value) {
  25756. this._checkUniform(name);
  25757. this._vectors4[name] = value;
  25758. return this;
  25759. };
  25760. ShaderMaterial.prototype.setMatrix = function (name, value) {
  25761. this._checkUniform(name);
  25762. this._matrices[name] = value;
  25763. return this;
  25764. };
  25765. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  25766. this._checkUniform(name);
  25767. this._matrices3x3[name] = value;
  25768. return this;
  25769. };
  25770. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  25771. this._checkUniform(name);
  25772. this._matrices2x2[name] = value;
  25773. return this;
  25774. };
  25775. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  25776. var scene = this.getScene();
  25777. var engine = scene.getEngine();
  25778. if (!this.checkReadyOnEveryCall) {
  25779. if (this._renderId === scene.getRenderId()) {
  25780. return true;
  25781. }
  25782. }
  25783. // Instances
  25784. var defines = [];
  25785. var fallbacks = new BABYLON.EffectFallbacks();
  25786. if (useInstances) {
  25787. defines.push("#define INSTANCES");
  25788. }
  25789. for (var index = 0; index < this._options.defines.length; index++) {
  25790. defines.push(this._options.defines[index]);
  25791. }
  25792. // Bones
  25793. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25794. defines.push("#define BONES");
  25795. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25796. defines.push("#define BONES4");
  25797. fallbacks.addFallback(0, "BONES4");
  25798. }
  25799. // Alpha test
  25800. if (engine.getAlphaTesting()) {
  25801. defines.push("#define ALPHATEST");
  25802. }
  25803. var previousEffect = this._effect;
  25804. var join = defines.join("\n");
  25805. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  25806. if (!this._effect.isReady()) {
  25807. return false;
  25808. }
  25809. if (previousEffect !== this._effect) {
  25810. scene.resetCachedMaterial();
  25811. }
  25812. this._renderId = scene.getRenderId();
  25813. return true;
  25814. };
  25815. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25816. var scene = this.getScene();
  25817. if (this._options.uniforms.indexOf("world") !== -1) {
  25818. this._effect.setMatrix("world", world);
  25819. }
  25820. if (this._options.uniforms.indexOf("worldView") !== -1) {
  25821. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  25822. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  25823. }
  25824. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  25825. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  25826. }
  25827. };
  25828. ShaderMaterial.prototype.bind = function (world, mesh) {
  25829. // Std values
  25830. this.bindOnlyWorldMatrix(world);
  25831. if (this.getScene().getCachedMaterial() !== this) {
  25832. if (this._options.uniforms.indexOf("view") !== -1) {
  25833. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  25834. }
  25835. if (this._options.uniforms.indexOf("projection") !== -1) {
  25836. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  25837. }
  25838. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  25839. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25840. }
  25841. // Bones
  25842. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25843. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25844. }
  25845. // Texture
  25846. for (var name in this._textures) {
  25847. this._effect.setTexture(name, this._textures[name]);
  25848. }
  25849. // Float
  25850. for (name in this._floats) {
  25851. this._effect.setFloat(name, this._floats[name]);
  25852. }
  25853. // Float s
  25854. for (name in this._floatsArrays) {
  25855. this._effect.setArray(name, this._floatsArrays[name]);
  25856. }
  25857. // Color3
  25858. for (name in this._colors3) {
  25859. this._effect.setColor3(name, this._colors3[name]);
  25860. }
  25861. // Color4
  25862. for (name in this._colors4) {
  25863. var color = this._colors4[name];
  25864. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25865. }
  25866. // Vector2
  25867. for (name in this._vectors2) {
  25868. this._effect.setVector2(name, this._vectors2[name]);
  25869. }
  25870. // Vector3
  25871. for (name in this._vectors3) {
  25872. this._effect.setVector3(name, this._vectors3[name]);
  25873. }
  25874. // Vector4
  25875. for (name in this._vectors4) {
  25876. this._effect.setVector4(name, this._vectors4[name]);
  25877. }
  25878. // Matrix
  25879. for (name in this._matrices) {
  25880. this._effect.setMatrix(name, this._matrices[name]);
  25881. }
  25882. // Matrix 3x3
  25883. for (name in this._matrices3x3) {
  25884. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  25885. }
  25886. // Matrix 2x2
  25887. for (name in this._matrices2x2) {
  25888. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  25889. }
  25890. }
  25891. _super.prototype.bind.call(this, world, mesh);
  25892. };
  25893. ShaderMaterial.prototype.clone = function (name) {
  25894. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  25895. return newShaderMaterial;
  25896. };
  25897. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  25898. for (var name in this._textures) {
  25899. this._textures[name].dispose();
  25900. }
  25901. this._textures = [];
  25902. _super.prototype.dispose.call(this, forceDisposeEffect);
  25903. };
  25904. return ShaderMaterial;
  25905. })(BABYLON.Material);
  25906. BABYLON.ShaderMaterial = ShaderMaterial;
  25907. })(BABYLON || (BABYLON = {}));
  25908. var BABYLON;
  25909. (function (BABYLON) {
  25910. var VertexData = (function () {
  25911. function VertexData() {
  25912. }
  25913. VertexData.prototype.set = function (data, kind) {
  25914. switch (kind) {
  25915. case BABYLON.VertexBuffer.PositionKind:
  25916. this.positions = data;
  25917. break;
  25918. case BABYLON.VertexBuffer.NormalKind:
  25919. this.normals = data;
  25920. break;
  25921. case BABYLON.VertexBuffer.UVKind:
  25922. this.uvs = data;
  25923. break;
  25924. case BABYLON.VertexBuffer.UV2Kind:
  25925. this.uvs2 = data;
  25926. break;
  25927. case BABYLON.VertexBuffer.UV3Kind:
  25928. this.uvs3 = data;
  25929. break;
  25930. case BABYLON.VertexBuffer.UV4Kind:
  25931. this.uvs4 = data;
  25932. break;
  25933. case BABYLON.VertexBuffer.UV5Kind:
  25934. this.uvs5 = data;
  25935. break;
  25936. case BABYLON.VertexBuffer.UV6Kind:
  25937. this.uvs6 = data;
  25938. break;
  25939. case BABYLON.VertexBuffer.ColorKind:
  25940. this.colors = data;
  25941. break;
  25942. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25943. this.matricesIndices = data;
  25944. break;
  25945. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25946. this.matricesWeights = data;
  25947. break;
  25948. }
  25949. };
  25950. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25951. this._applyTo(mesh, updatable);
  25952. };
  25953. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25954. this._applyTo(geometry, updatable);
  25955. };
  25956. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25957. this._update(mesh);
  25958. };
  25959. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25960. this._update(geometry);
  25961. };
  25962. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25963. if (this.positions) {
  25964. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25965. }
  25966. if (this.normals) {
  25967. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25968. }
  25969. if (this.uvs) {
  25970. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25971. }
  25972. if (this.uvs2) {
  25973. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25974. }
  25975. if (this.uvs3) {
  25976. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25977. }
  25978. if (this.uvs4) {
  25979. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25980. }
  25981. if (this.uvs5) {
  25982. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25983. }
  25984. if (this.uvs6) {
  25985. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25986. }
  25987. if (this.colors) {
  25988. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25989. }
  25990. if (this.matricesIndices) {
  25991. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25992. }
  25993. if (this.matricesWeights) {
  25994. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25995. }
  25996. if (this.indices) {
  25997. meshOrGeometry.setIndices(this.indices);
  25998. }
  25999. };
  26000. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26001. if (this.positions) {
  26002. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26003. }
  26004. if (this.normals) {
  26005. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26006. }
  26007. if (this.uvs) {
  26008. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26009. }
  26010. if (this.uvs2) {
  26011. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26012. }
  26013. if (this.uvs3) {
  26014. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26015. }
  26016. if (this.uvs4) {
  26017. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26018. }
  26019. if (this.uvs5) {
  26020. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26021. }
  26022. if (this.uvs6) {
  26023. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26024. }
  26025. if (this.colors) {
  26026. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26027. }
  26028. if (this.matricesIndices) {
  26029. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26030. }
  26031. if (this.matricesWeights) {
  26032. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26033. }
  26034. if (this.indices) {
  26035. meshOrGeometry.setIndices(this.indices);
  26036. }
  26037. };
  26038. VertexData.prototype.transform = function (matrix) {
  26039. var transformed = BABYLON.Vector3.Zero();
  26040. var index;
  26041. if (this.positions) {
  26042. var position = BABYLON.Vector3.Zero();
  26043. for (index = 0; index < this.positions.length; index += 3) {
  26044. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26045. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26046. this.positions[index] = transformed.x;
  26047. this.positions[index + 1] = transformed.y;
  26048. this.positions[index + 2] = transformed.z;
  26049. }
  26050. }
  26051. if (this.normals) {
  26052. var normal = BABYLON.Vector3.Zero();
  26053. for (index = 0; index < this.normals.length; index += 3) {
  26054. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26055. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26056. this.normals[index] = transformed.x;
  26057. this.normals[index + 1] = transformed.y;
  26058. this.normals[index + 2] = transformed.z;
  26059. }
  26060. }
  26061. };
  26062. VertexData.prototype.merge = function (other) {
  26063. var index;
  26064. if (other.indices) {
  26065. if (!this.indices) {
  26066. this.indices = [];
  26067. }
  26068. var offset = this.positions ? this.positions.length / 3 : 0;
  26069. for (index = 0; index < other.indices.length; index++) {
  26070. this.indices.push(other.indices[index] + offset);
  26071. }
  26072. }
  26073. if (other.positions) {
  26074. if (!this.positions) {
  26075. this.positions = [];
  26076. }
  26077. for (index = 0; index < other.positions.length; index++) {
  26078. this.positions.push(other.positions[index]);
  26079. }
  26080. }
  26081. if (other.normals) {
  26082. if (!this.normals) {
  26083. this.normals = [];
  26084. }
  26085. for (index = 0; index < other.normals.length; index++) {
  26086. this.normals.push(other.normals[index]);
  26087. }
  26088. }
  26089. if (other.uvs) {
  26090. if (!this.uvs) {
  26091. this.uvs = [];
  26092. }
  26093. for (index = 0; index < other.uvs.length; index++) {
  26094. this.uvs.push(other.uvs[index]);
  26095. }
  26096. }
  26097. if (other.uvs2) {
  26098. if (!this.uvs2) {
  26099. this.uvs2 = [];
  26100. }
  26101. for (index = 0; index < other.uvs2.length; index++) {
  26102. this.uvs2.push(other.uvs2[index]);
  26103. }
  26104. }
  26105. if (other.uvs3) {
  26106. if (!this.uvs3) {
  26107. this.uvs3 = [];
  26108. }
  26109. for (index = 0; index < other.uvs3.length; index++) {
  26110. this.uvs3.push(other.uvs3[index]);
  26111. }
  26112. }
  26113. if (other.uvs4) {
  26114. if (!this.uvs4) {
  26115. this.uvs4 = [];
  26116. }
  26117. for (index = 0; index < other.uvs4.length; index++) {
  26118. this.uvs4.push(other.uvs4[index]);
  26119. }
  26120. }
  26121. if (other.uvs5) {
  26122. if (!this.uvs5) {
  26123. this.uvs5 = [];
  26124. }
  26125. for (index = 0; index < other.uvs5.length; index++) {
  26126. this.uvs5.push(other.uvs5[index]);
  26127. }
  26128. }
  26129. if (other.uvs6) {
  26130. if (!this.uvs6) {
  26131. this.uvs6 = [];
  26132. }
  26133. for (index = 0; index < other.uvs6.length; index++) {
  26134. this.uvs6.push(other.uvs6[index]);
  26135. }
  26136. }
  26137. if (other.matricesIndices) {
  26138. if (!this.matricesIndices) {
  26139. this.matricesIndices = [];
  26140. }
  26141. for (index = 0; index < other.matricesIndices.length; index++) {
  26142. this.matricesIndices.push(other.matricesIndices[index]);
  26143. }
  26144. }
  26145. if (other.matricesWeights) {
  26146. if (!this.matricesWeights) {
  26147. this.matricesWeights = [];
  26148. }
  26149. for (index = 0; index < other.matricesWeights.length; index++) {
  26150. this.matricesWeights.push(other.matricesWeights[index]);
  26151. }
  26152. }
  26153. if (other.colors) {
  26154. if (!this.colors) {
  26155. this.colors = [];
  26156. }
  26157. for (index = 0; index < other.colors.length; index++) {
  26158. this.colors.push(other.colors[index]);
  26159. }
  26160. }
  26161. };
  26162. // Statics
  26163. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26164. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26165. };
  26166. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26167. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26168. };
  26169. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26170. var result = new VertexData();
  26171. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26172. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26173. }
  26174. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26175. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26176. }
  26177. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26178. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26179. }
  26180. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26181. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26182. }
  26183. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26184. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26185. }
  26186. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26187. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26188. }
  26189. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26190. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26191. }
  26192. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26193. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26194. }
  26195. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26196. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26197. }
  26198. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26199. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26200. }
  26201. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26202. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26203. }
  26204. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26205. return result;
  26206. };
  26207. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  26208. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26209. closeArray = closeArray || false;
  26210. closePath = closePath || false;
  26211. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26212. offset = offset || defaultOffset;
  26213. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26214. var positions = [];
  26215. var indices = [];
  26216. var normals = [];
  26217. var uvs = [];
  26218. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26219. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26220. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26221. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26222. var minlg; // minimal length among all paths from pathArray
  26223. var lg = []; // array of path lengths : nb of vertex per path
  26224. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26225. var p; // path iterator
  26226. var i; // point iterator
  26227. var j; // point iterator
  26228. // if single path in pathArray
  26229. if (pathArray.length < 2) {
  26230. var ar1 = [];
  26231. var ar2 = [];
  26232. for (i = 0; i < pathArray[0].length - offset; i++) {
  26233. ar1.push(pathArray[0][i]);
  26234. ar2.push(pathArray[0][i + offset]);
  26235. }
  26236. pathArray = [ar1, ar2];
  26237. }
  26238. // positions and horizontal distances (u)
  26239. var idc = 0;
  26240. var closePathCorr = (closePath) ? 1 : 0;
  26241. var path;
  26242. var l;
  26243. minlg = pathArray[0].length;
  26244. var vectlg;
  26245. var dist;
  26246. for (p = 0; p < pathArray.length; p++) {
  26247. uTotalDistance[p] = 0;
  26248. us[p] = [0];
  26249. path = pathArray[p];
  26250. l = path.length;
  26251. minlg = (minlg < l) ? minlg : l;
  26252. j = 0;
  26253. while (j < l) {
  26254. positions.push(path[j].x, path[j].y, path[j].z);
  26255. if (j > 0) {
  26256. vectlg = path[j].subtract(path[j - 1]).length();
  26257. dist = vectlg + uTotalDistance[p];
  26258. us[p].push(dist);
  26259. uTotalDistance[p] = dist;
  26260. }
  26261. j++;
  26262. }
  26263. if (closePath) {
  26264. j--;
  26265. positions.push(path[0].x, path[0].y, path[0].z);
  26266. vectlg = path[j].subtract(path[0]).length();
  26267. dist = vectlg + uTotalDistance[p];
  26268. us[p].push(dist);
  26269. uTotalDistance[p] = dist;
  26270. }
  26271. lg[p] = l + closePathCorr;
  26272. idx[p] = idc;
  26273. idc += (l + closePathCorr);
  26274. }
  26275. // vertical distances (v)
  26276. var path1;
  26277. var path2;
  26278. var vertex1;
  26279. var vertex2;
  26280. for (i = 0; i < minlg + closePathCorr; i++) {
  26281. vTotalDistance[i] = 0;
  26282. vs[i] = [0];
  26283. for (p = 0; p < pathArray.length - 1; p++) {
  26284. path1 = pathArray[p];
  26285. path2 = pathArray[p + 1];
  26286. if (i === minlg) {
  26287. vertex1 = path1[0];
  26288. vertex2 = path2[0];
  26289. }
  26290. else {
  26291. vertex1 = path1[i];
  26292. vertex2 = path2[i];
  26293. }
  26294. vectlg = vertex2.subtract(vertex1).length();
  26295. dist = vectlg + vTotalDistance[i];
  26296. vs[i].push(dist);
  26297. vTotalDistance[i] = dist;
  26298. }
  26299. if (closeArray) {
  26300. path1 = pathArray[p];
  26301. path2 = pathArray[0];
  26302. vectlg = path2[i].subtract(path1[i]).length();
  26303. dist = vectlg + vTotalDistance[i];
  26304. vTotalDistance[i] = dist;
  26305. }
  26306. }
  26307. // uvs
  26308. var u;
  26309. var v;
  26310. for (p = 0; p < pathArray.length; p++) {
  26311. for (i = 0; i < minlg + closePathCorr; i++) {
  26312. u = us[p][i] / uTotalDistance[p];
  26313. v = vs[i][p] / vTotalDistance[i];
  26314. uvs.push(u, v);
  26315. }
  26316. }
  26317. // indices
  26318. p = 0; // path index
  26319. var pi = 0; // positions array index
  26320. var l1 = lg[p] - 1; // path1 length
  26321. var l2 = lg[p + 1] - 1; // path2 length
  26322. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26323. var shft = idx[1] - idx[0]; // shift
  26324. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26325. while (pi <= min && p < path1nb) {
  26326. // 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
  26327. indices.push(pi, pi + shft, pi + 1);
  26328. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26329. pi += 1;
  26330. if (pi === min) {
  26331. p++;
  26332. if (p === lg.length - 1) {
  26333. shft = idx[0] - idx[p];
  26334. l1 = lg[p] - 1;
  26335. l2 = lg[0] - 1;
  26336. }
  26337. else {
  26338. shft = idx[p + 1] - idx[p];
  26339. l1 = lg[p] - 1;
  26340. l2 = lg[p + 1] - 1;
  26341. }
  26342. pi = idx[p];
  26343. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26344. }
  26345. }
  26346. // normals
  26347. VertexData.ComputeNormals(positions, indices, normals);
  26348. if (closePath) {
  26349. var indexFirst = 0;
  26350. var indexLast = 0;
  26351. for (p = 0; p < pathArray.length; p++) {
  26352. indexFirst = idx[p] * 3;
  26353. if (p + 1 < pathArray.length) {
  26354. indexLast = (idx[p + 1] - 1) * 3;
  26355. }
  26356. else {
  26357. indexLast = normals.length - 3;
  26358. }
  26359. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26360. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26361. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26362. normals[indexLast] = normals[indexFirst];
  26363. normals[indexLast + 1] = normals[indexFirst + 1];
  26364. normals[indexLast + 2] = normals[indexFirst + 2];
  26365. }
  26366. }
  26367. // sides
  26368. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26369. // Result
  26370. var vertexData = new VertexData();
  26371. vertexData.indices = indices;
  26372. vertexData.positions = positions;
  26373. vertexData.normals = normals;
  26374. vertexData.uvs = uvs;
  26375. if (closePath) {
  26376. vertexData._idx = idx;
  26377. }
  26378. return vertexData;
  26379. };
  26380. VertexData.CreateBox = function (options, sideOrientation) {
  26381. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26382. var normalsSource = [
  26383. new BABYLON.Vector3(0, 0, 1),
  26384. new BABYLON.Vector3(0, 0, -1),
  26385. new BABYLON.Vector3(1, 0, 0),
  26386. new BABYLON.Vector3(-1, 0, 0),
  26387. new BABYLON.Vector3(0, 1, 0),
  26388. new BABYLON.Vector3(0, -1, 0)
  26389. ];
  26390. var indices = [];
  26391. var positions = [];
  26392. var normals = [];
  26393. var uvs = [];
  26394. var width = 1;
  26395. var height = 1;
  26396. var depth = 1;
  26397. var faceUV = options.faceUV || new Array(6);
  26398. var faceColors;
  26399. var colors = [];
  26400. if (options.faceColors) {
  26401. faceColors = options.faceColors;
  26402. }
  26403. if (options.width !== undefined) {
  26404. width = options.width || 1;
  26405. height = options.height || 1;
  26406. depth = options.depth || 1;
  26407. }
  26408. else {
  26409. width = options || 1;
  26410. height = options || 1;
  26411. depth = options || 1;
  26412. }
  26413. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26414. for (var f = 0; f < 6; f++) {
  26415. if (faceUV[f] === undefined) {
  26416. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26417. }
  26418. if (faceColors && faceColors[f] === undefined) {
  26419. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26420. }
  26421. }
  26422. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26423. // Create each face in turn.
  26424. for (var index = 0; index < normalsSource.length; index++) {
  26425. var normal = normalsSource[index];
  26426. // Get two vectors perpendicular to the face normal and to each other.
  26427. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26428. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26429. // Six indices (two triangles) per face.
  26430. var verticesLength = positions.length / 3;
  26431. indices.push(verticesLength);
  26432. indices.push(verticesLength + 1);
  26433. indices.push(verticesLength + 2);
  26434. indices.push(verticesLength);
  26435. indices.push(verticesLength + 2);
  26436. indices.push(verticesLength + 3);
  26437. // Four vertices per face.
  26438. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26439. positions.push(vertex.x, vertex.y, vertex.z);
  26440. normals.push(normal.x, normal.y, normal.z);
  26441. uvs.push(faceUV[index].z, faceUV[index].w);
  26442. if (faceColors) {
  26443. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26444. }
  26445. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26446. positions.push(vertex.x, vertex.y, vertex.z);
  26447. normals.push(normal.x, normal.y, normal.z);
  26448. uvs.push(faceUV[index].x, faceUV[index].w);
  26449. if (faceColors) {
  26450. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26451. }
  26452. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26453. positions.push(vertex.x, vertex.y, vertex.z);
  26454. normals.push(normal.x, normal.y, normal.z);
  26455. uvs.push(faceUV[index].x, faceUV[index].y);
  26456. if (faceColors) {
  26457. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26458. }
  26459. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26460. positions.push(vertex.x, vertex.y, vertex.z);
  26461. normals.push(normal.x, normal.y, normal.z);
  26462. uvs.push(faceUV[index].z, faceUV[index].y);
  26463. if (faceColors) {
  26464. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26465. }
  26466. }
  26467. // sides
  26468. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26469. // Result
  26470. var vertexData = new VertexData();
  26471. vertexData.indices = indices;
  26472. vertexData.positions = positions;
  26473. vertexData.normals = normals;
  26474. vertexData.uvs = uvs;
  26475. if (faceColors) {
  26476. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26477. vertexData.colors = totalColors;
  26478. }
  26479. return vertexData;
  26480. };
  26481. VertexData.CreateSphere = function (options, diameter, sideOrientation) {
  26482. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26483. var segments;
  26484. var diameterX;
  26485. var diameterY;
  26486. var diameterZ;
  26487. if (options.segments) {
  26488. segments = options.segments || 32;
  26489. diameterX = options.diameterX || 1;
  26490. diameterY = options.diameterY || 1;
  26491. diameterZ = options.diameterZ || 1;
  26492. }
  26493. else {
  26494. segments = options || 32;
  26495. diameterX = diameter || 1;
  26496. diameterY = diameterX;
  26497. diameterZ = diameterX;
  26498. }
  26499. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26500. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26501. var totalZRotationSteps = 2 + segments;
  26502. var totalYRotationSteps = 2 * totalZRotationSteps;
  26503. var indices = [];
  26504. var positions = [];
  26505. var normals = [];
  26506. var uvs = [];
  26507. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26508. var normalizedZ = zRotationStep / totalZRotationSteps;
  26509. var angleZ = (normalizedZ * Math.PI);
  26510. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26511. var normalizedY = yRotationStep / totalYRotationSteps;
  26512. var angleY = normalizedY * Math.PI * 2;
  26513. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26514. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26515. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26516. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26517. var vertex = complete.multiply(radius);
  26518. var normal = BABYLON.Vector3.Normalize(vertex);
  26519. positions.push(vertex.x, vertex.y, vertex.z);
  26520. normals.push(normal.x, normal.y, normal.z);
  26521. uvs.push(normalizedZ, normalizedY);
  26522. }
  26523. if (zRotationStep > 0) {
  26524. var verticesCount = positions.length / 3;
  26525. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26526. indices.push((firstIndex));
  26527. indices.push((firstIndex + 1));
  26528. indices.push(firstIndex + totalYRotationSteps + 1);
  26529. indices.push((firstIndex + totalYRotationSteps + 1));
  26530. indices.push((firstIndex + 1));
  26531. indices.push((firstIndex + totalYRotationSteps + 2));
  26532. }
  26533. }
  26534. }
  26535. // Sides
  26536. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26537. // Result
  26538. var vertexData = new VertexData();
  26539. vertexData.indices = indices;
  26540. vertexData.positions = positions;
  26541. vertexData.normals = normals;
  26542. vertexData.uvs = uvs;
  26543. return vertexData;
  26544. };
  26545. // Cylinder and cone (made using ribbons)
  26546. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  26547. if (subdivisions === void 0) { subdivisions = 1; }
  26548. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26549. var indices = [];
  26550. var positions = [];
  26551. var normals = [];
  26552. var uvs = [];
  26553. var angle_step = Math.PI * 2 / tessellation;
  26554. var angle;
  26555. var h;
  26556. var radius;
  26557. var tan = (diameterBottom - diameterTop) / 2 / height;
  26558. var ringVertex = BABYLON.Vector3.Zero();
  26559. var ringNormal = BABYLON.Vector3.Zero();
  26560. // positions, normals, uvs
  26561. var i;
  26562. var j;
  26563. for (i = 0; i <= subdivisions; i++) {
  26564. h = i / subdivisions;
  26565. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26566. for (j = 0; j <= tessellation; j++) {
  26567. angle = j * angle_step;
  26568. ringVertex.x = Math.cos(-angle) * radius;
  26569. ringVertex.y = -height / 2 + h * height;
  26570. ringVertex.z = Math.sin(-angle) * radius;
  26571. if (diameterTop === 0 && i === subdivisions) {
  26572. // if no top cap, reuse former normals
  26573. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26574. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26575. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26576. }
  26577. else {
  26578. ringNormal.x = ringVertex.x;
  26579. ringNormal.z = ringVertex.z;
  26580. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26581. ringNormal.normalize();
  26582. }
  26583. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26584. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26585. uvs.push(j / tessellation, 1 - h);
  26586. }
  26587. }
  26588. // indices
  26589. for (i = 0; i < subdivisions; i++) {
  26590. for (j = 0; j < tessellation; j++) {
  26591. var i0 = i * (tessellation + 1) + j;
  26592. var i1 = (i + 1) * (tessellation + 1) + j;
  26593. var i2 = i * (tessellation + 1) + (j + 1);
  26594. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  26595. indices.push(i0, i1, i2);
  26596. indices.push(i3, i2, i1);
  26597. }
  26598. }
  26599. // Caps
  26600. var createCylinderCap = function (isTop) {
  26601. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26602. if (radius === 0) {
  26603. return;
  26604. }
  26605. var vbase = positions.length / 3;
  26606. var offset = new BABYLON.Vector3(0, isTop ? height / 2 : -height / 2, 0);
  26607. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26608. // Cap positions, normals & uvs
  26609. var angle;
  26610. var circleVector;
  26611. var i;
  26612. for (i = 0; i < tessellation; i++) {
  26613. angle = Math.PI * 2 * i / tessellation;
  26614. circleVector = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26615. var position = circleVector.scale(radius).add(offset);
  26616. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  26617. positions.push(position.x, position.y, position.z);
  26618. normals.push(0, isTop ? 1 : -1, 0);
  26619. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26620. }
  26621. // Cap indices
  26622. for (i = 0; i < tessellation - 2; i++) {
  26623. if (!isTop) {
  26624. indices.push(vbase);
  26625. indices.push(vbase + (i + 1) % tessellation);
  26626. indices.push(vbase + (i + 2) % tessellation);
  26627. }
  26628. else {
  26629. indices.push(vbase);
  26630. indices.push(vbase + (i + 2) % tessellation);
  26631. indices.push(vbase + (i + 1) % tessellation);
  26632. }
  26633. }
  26634. };
  26635. // add caps to geometry
  26636. createCylinderCap(true);
  26637. createCylinderCap(false);
  26638. // Sides
  26639. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26640. var vertexData = new VertexData();
  26641. vertexData.indices = indices;
  26642. vertexData.positions = positions;
  26643. vertexData.normals = normals;
  26644. vertexData.uvs = uvs;
  26645. return vertexData;
  26646. };
  26647. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  26648. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26649. var indices = [];
  26650. var positions = [];
  26651. var normals = [];
  26652. var uvs = [];
  26653. diameter = diameter || 1;
  26654. thickness = thickness || 0.5;
  26655. tessellation = tessellation || 16;
  26656. var stride = tessellation + 1;
  26657. for (var i = 0; i <= tessellation; i++) {
  26658. var u = i / tessellation;
  26659. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26660. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26661. for (var j = 0; j <= tessellation; j++) {
  26662. var v = 1 - j / tessellation;
  26663. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26664. var dx = Math.cos(innerAngle);
  26665. var dy = Math.sin(innerAngle);
  26666. // Create a vertex.
  26667. var normal = new BABYLON.Vector3(dx, dy, 0);
  26668. var position = normal.scale(thickness / 2);
  26669. var textureCoordinate = new BABYLON.Vector2(u, v);
  26670. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26671. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26672. positions.push(position.x, position.y, position.z);
  26673. normals.push(normal.x, normal.y, normal.z);
  26674. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26675. // And create indices for two triangles.
  26676. var nextI = (i + 1) % stride;
  26677. var nextJ = (j + 1) % stride;
  26678. indices.push(i * stride + j);
  26679. indices.push(i * stride + nextJ);
  26680. indices.push(nextI * stride + j);
  26681. indices.push(i * stride + nextJ);
  26682. indices.push(nextI * stride + nextJ);
  26683. indices.push(nextI * stride + j);
  26684. }
  26685. }
  26686. // Sides
  26687. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26688. // Result
  26689. var vertexData = new VertexData();
  26690. vertexData.indices = indices;
  26691. vertexData.positions = positions;
  26692. vertexData.normals = normals;
  26693. vertexData.uvs = uvs;
  26694. return vertexData;
  26695. };
  26696. VertexData.CreateLines = function (points) {
  26697. var indices = [];
  26698. var positions = [];
  26699. for (var index = 0; index < points.length; index++) {
  26700. positions.push(points[index].x, points[index].y, points[index].z);
  26701. if (index > 0) {
  26702. indices.push(index - 1);
  26703. indices.push(index);
  26704. }
  26705. }
  26706. // Result
  26707. var vertexData = new VertexData();
  26708. vertexData.indices = indices;
  26709. vertexData.positions = positions;
  26710. return vertexData;
  26711. };
  26712. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  26713. dashSize = dashSize || 3;
  26714. gapSize = gapSize || 1;
  26715. dashNb = dashNb || 200;
  26716. var positions = new Array();
  26717. var indices = new Array();
  26718. var curvect = BABYLON.Vector3.Zero();
  26719. var lg = 0;
  26720. var nb = 0;
  26721. var shft = 0;
  26722. var dashshft = 0;
  26723. var curshft = 0;
  26724. var idx = 0;
  26725. var i = 0;
  26726. for (i = 0; i < points.length - 1; i++) {
  26727. points[i + 1].subtractToRef(points[i], curvect);
  26728. lg += curvect.length();
  26729. }
  26730. shft = lg / dashNb;
  26731. dashshft = dashSize * shft / (dashSize + gapSize);
  26732. for (i = 0; i < points.length - 1; i++) {
  26733. points[i + 1].subtractToRef(points[i], curvect);
  26734. nb = Math.floor(curvect.length() / shft);
  26735. curvect.normalize();
  26736. for (var j = 0; j < nb; j++) {
  26737. curshft = shft * j;
  26738. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26739. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26740. indices.push(idx, idx + 1);
  26741. idx += 2;
  26742. }
  26743. }
  26744. // Result
  26745. var vertexData = new VertexData();
  26746. vertexData.positions = positions;
  26747. vertexData.indices = indices;
  26748. return vertexData;
  26749. };
  26750. VertexData.CreateGround = function (options, height, subdivisions) {
  26751. var indices = [];
  26752. var positions = [];
  26753. var normals = [];
  26754. var uvs = [];
  26755. var row, col;
  26756. var width;
  26757. if (options.width) {
  26758. width = options.width || 1;
  26759. height = options.height || 1;
  26760. subdivisions = options.subdivisions || 1;
  26761. }
  26762. else {
  26763. width = options || 1;
  26764. height = height || 1;
  26765. subdivisions = subdivisions || 1;
  26766. }
  26767. for (row = 0; row <= subdivisions; row++) {
  26768. for (col = 0; col <= subdivisions; col++) {
  26769. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26770. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26771. positions.push(position.x, position.y, position.z);
  26772. normals.push(normal.x, normal.y, normal.z);
  26773. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26774. }
  26775. }
  26776. for (row = 0; row < subdivisions; row++) {
  26777. for (col = 0; col < subdivisions; col++) {
  26778. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26779. indices.push(col + 1 + row * (subdivisions + 1));
  26780. indices.push(col + row * (subdivisions + 1));
  26781. indices.push(col + (row + 1) * (subdivisions + 1));
  26782. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26783. indices.push(col + row * (subdivisions + 1));
  26784. }
  26785. }
  26786. // Result
  26787. var vertexData = new VertexData();
  26788. vertexData.indices = indices;
  26789. vertexData.positions = positions;
  26790. vertexData.normals = normals;
  26791. vertexData.uvs = uvs;
  26792. return vertexData;
  26793. };
  26794. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  26795. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  26796. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  26797. var indices = [];
  26798. var positions = [];
  26799. var normals = [];
  26800. var uvs = [];
  26801. var row, col, tileRow, tileCol;
  26802. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  26803. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26804. precision.w = (precision.w < 1) ? 1 : precision.w;
  26805. precision.h = (precision.h < 1) ? 1 : precision.h;
  26806. var tileSize = {
  26807. 'w': (xmax - xmin) / subdivisions.w,
  26808. 'h': (zmax - zmin) / subdivisions.h
  26809. };
  26810. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26811. // Indices
  26812. var base = positions.length / 3;
  26813. var rowLength = precision.w + 1;
  26814. for (row = 0; row < precision.h; row++) {
  26815. for (col = 0; col < precision.w; col++) {
  26816. var square = [
  26817. base + col + row * rowLength,
  26818. base + (col + 1) + row * rowLength,
  26819. base + (col + 1) + (row + 1) * rowLength,
  26820. base + col + (row + 1) * rowLength
  26821. ];
  26822. indices.push(square[1]);
  26823. indices.push(square[2]);
  26824. indices.push(square[3]);
  26825. indices.push(square[0]);
  26826. indices.push(square[1]);
  26827. indices.push(square[3]);
  26828. }
  26829. }
  26830. // Position, normals and uvs
  26831. var position = BABYLON.Vector3.Zero();
  26832. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26833. for (row = 0; row <= precision.h; row++) {
  26834. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26835. for (col = 0; col <= precision.w; col++) {
  26836. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26837. position.y = 0;
  26838. positions.push(position.x, position.y, position.z);
  26839. normals.push(normal.x, normal.y, normal.z);
  26840. uvs.push(col / precision.w, row / precision.h);
  26841. }
  26842. }
  26843. }
  26844. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26845. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26846. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26847. }
  26848. }
  26849. // Result
  26850. var vertexData = new VertexData();
  26851. vertexData.indices = indices;
  26852. vertexData.positions = positions;
  26853. vertexData.normals = normals;
  26854. vertexData.uvs = uvs;
  26855. return vertexData;
  26856. };
  26857. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  26858. var indices = [];
  26859. var positions = [];
  26860. var normals = [];
  26861. var uvs = [];
  26862. var row, col;
  26863. // Vertices
  26864. for (row = 0; row <= subdivisions; row++) {
  26865. for (col = 0; col <= subdivisions; col++) {
  26866. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26867. // Compute height
  26868. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  26869. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  26870. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  26871. var r = buffer[pos] / 255.0;
  26872. var g = buffer[pos + 1] / 255.0;
  26873. var b = buffer[pos + 2] / 255.0;
  26874. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26875. position.y = minHeight + (maxHeight - minHeight) * gradient;
  26876. // Add vertex
  26877. positions.push(position.x, position.y, position.z);
  26878. normals.push(0, 0, 0);
  26879. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26880. }
  26881. }
  26882. // Indices
  26883. for (row = 0; row < subdivisions; row++) {
  26884. for (col = 0; col < subdivisions; col++) {
  26885. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26886. indices.push(col + 1 + row * (subdivisions + 1));
  26887. indices.push(col + row * (subdivisions + 1));
  26888. indices.push(col + (row + 1) * (subdivisions + 1));
  26889. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26890. indices.push(col + row * (subdivisions + 1));
  26891. }
  26892. }
  26893. // Normals
  26894. VertexData.ComputeNormals(positions, indices, normals);
  26895. // Result
  26896. var vertexData = new VertexData();
  26897. vertexData.indices = indices;
  26898. vertexData.positions = positions;
  26899. vertexData.normals = normals;
  26900. vertexData.uvs = uvs;
  26901. return vertexData;
  26902. };
  26903. VertexData.CreatePlane = function (options, sideOrientation) {
  26904. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26905. var indices = [];
  26906. var positions = [];
  26907. var normals = [];
  26908. var uvs = [];
  26909. var width;
  26910. var height;
  26911. if (options.width) {
  26912. width = options.width || 1;
  26913. height = options.height || 1;
  26914. sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26915. }
  26916. else {
  26917. width = options || 1;
  26918. height = options || 1;
  26919. }
  26920. // Vertices
  26921. var halfWidth = width / 2.0;
  26922. var halfHeight = height / 2.0;
  26923. positions.push(-halfWidth, -halfHeight, 0);
  26924. normals.push(0, 0, -1.0);
  26925. uvs.push(0.0, 0.0);
  26926. positions.push(halfWidth, -halfHeight, 0);
  26927. normals.push(0, 0, -1.0);
  26928. uvs.push(1.0, 0.0);
  26929. positions.push(halfWidth, halfHeight, 0);
  26930. normals.push(0, 0, -1.0);
  26931. uvs.push(1.0, 1.0);
  26932. positions.push(-halfWidth, halfHeight, 0);
  26933. normals.push(0, 0, -1.0);
  26934. uvs.push(0.0, 1.0);
  26935. // Indices
  26936. indices.push(0);
  26937. indices.push(1);
  26938. indices.push(2);
  26939. indices.push(0);
  26940. indices.push(2);
  26941. indices.push(3);
  26942. // Sides
  26943. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26944. // Result
  26945. var vertexData = new VertexData();
  26946. vertexData.indices = indices;
  26947. vertexData.positions = positions;
  26948. vertexData.normals = normals;
  26949. vertexData.uvs = uvs;
  26950. return vertexData;
  26951. };
  26952. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  26953. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26954. var positions = [];
  26955. var indices = [];
  26956. var normals = [];
  26957. var uvs = [];
  26958. // positions and uvs
  26959. positions.push(0, 0, 0); // disc center first
  26960. uvs.push(0.5, 0.5);
  26961. var step = Math.PI * 2 / tessellation;
  26962. for (var a = 0; a < Math.PI * 2; a += step) {
  26963. var x = Math.cos(a);
  26964. var y = Math.sin(a);
  26965. var u = (x + 1) / 2;
  26966. var v = (1 - y) / 2;
  26967. positions.push(radius * x, radius * y, 0);
  26968. uvs.push(u, v);
  26969. }
  26970. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26971. uvs.push(uvs[2], uvs[3]);
  26972. //indices
  26973. var vertexNb = positions.length / 3;
  26974. for (var i = 1; i < vertexNb - 1; i++) {
  26975. indices.push(i + 1, 0, i);
  26976. }
  26977. // result
  26978. VertexData.ComputeNormals(positions, indices, normals);
  26979. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26980. var vertexData = new VertexData();
  26981. vertexData.indices = indices;
  26982. vertexData.positions = positions;
  26983. vertexData.normals = normals;
  26984. vertexData.uvs = uvs;
  26985. return vertexData;
  26986. };
  26987. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26988. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  26989. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26990. var indices = [];
  26991. var positions = [];
  26992. var normals = [];
  26993. var uvs = [];
  26994. radius = radius || 2;
  26995. tube = tube || 0.5;
  26996. radialSegments = radialSegments || 32;
  26997. tubularSegments = tubularSegments || 32;
  26998. p = p || 2;
  26999. q = q || 3;
  27000. // Helper
  27001. var getPos = function (angle) {
  27002. var cu = Math.cos(angle);
  27003. var su = Math.sin(angle);
  27004. var quOverP = q / p * angle;
  27005. var cs = Math.cos(quOverP);
  27006. var tx = radius * (2 + cs) * 0.5 * cu;
  27007. var ty = radius * (2 + cs) * su * 0.5;
  27008. var tz = radius * Math.sin(quOverP) * 0.5;
  27009. return new BABYLON.Vector3(tx, ty, tz);
  27010. };
  27011. // Vertices
  27012. var i;
  27013. var j;
  27014. for (i = 0; i <= radialSegments; i++) {
  27015. var modI = i % radialSegments;
  27016. var u = modI / radialSegments * 2 * p * Math.PI;
  27017. var p1 = getPos(u);
  27018. var p2 = getPos(u + 0.01);
  27019. var tang = p2.subtract(p1);
  27020. var n = p2.add(p1);
  27021. var bitan = BABYLON.Vector3.Cross(tang, n);
  27022. n = BABYLON.Vector3.Cross(bitan, tang);
  27023. bitan.normalize();
  27024. n.normalize();
  27025. for (j = 0; j < tubularSegments; j++) {
  27026. var modJ = j % tubularSegments;
  27027. var v = modJ / tubularSegments * 2 * Math.PI;
  27028. var cx = -tube * Math.cos(v);
  27029. var cy = tube * Math.sin(v);
  27030. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27031. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27032. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27033. uvs.push(i / radialSegments);
  27034. uvs.push(j / tubularSegments);
  27035. }
  27036. }
  27037. for (i = 0; i < radialSegments; i++) {
  27038. for (j = 0; j < tubularSegments; j++) {
  27039. var jNext = (j + 1) % tubularSegments;
  27040. var a = i * tubularSegments + j;
  27041. var b = (i + 1) * tubularSegments + j;
  27042. var c = (i + 1) * tubularSegments + jNext;
  27043. var d = i * tubularSegments + jNext;
  27044. indices.push(d);
  27045. indices.push(b);
  27046. indices.push(a);
  27047. indices.push(d);
  27048. indices.push(c);
  27049. indices.push(b);
  27050. }
  27051. }
  27052. // Normals
  27053. VertexData.ComputeNormals(positions, indices, normals);
  27054. // Sides
  27055. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27056. // Result
  27057. var vertexData = new VertexData();
  27058. vertexData.indices = indices;
  27059. vertexData.positions = positions;
  27060. vertexData.normals = normals;
  27061. vertexData.uvs = uvs;
  27062. return vertexData;
  27063. };
  27064. // Tools
  27065. /**
  27066. * @param {any} - positions (number[] or Float32Array)
  27067. * @param {any} - indices (number[] or Uint16Array)
  27068. * @param {any} - normals (number[] or Float32Array)
  27069. */
  27070. VertexData.ComputeNormals = function (positions, indices, normals) {
  27071. var index = 0;
  27072. // temp Vector3
  27073. var p1p2 = BABYLON.Vector3.Zero();
  27074. var p3p2 = BABYLON.Vector3.Zero();
  27075. var faceNormal = BABYLON.Vector3.Zero();
  27076. var vertexNormali1 = BABYLON.Vector3.Zero();
  27077. for (index = 0; index < positions.length; index++) {
  27078. normals[index] = 0.0;
  27079. }
  27080. // indice triplet = 1 face
  27081. var nbFaces = indices.length / 3;
  27082. for (index = 0; index < nbFaces; index++) {
  27083. var i1 = indices[index * 3];
  27084. var i2 = indices[index * 3 + 1];
  27085. var i3 = indices[index * 3 + 2];
  27086. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  27087. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27088. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27089. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  27090. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27091. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27092. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  27093. faceNormal.normalize();
  27094. normals[i1 * 3] += faceNormal.x;
  27095. normals[i1 * 3 + 1] += faceNormal.y;
  27096. normals[i1 * 3 + 2] += faceNormal.z;
  27097. normals[i2 * 3] += faceNormal.x;
  27098. normals[i2 * 3 + 1] += faceNormal.y;
  27099. normals[i2 * 3 + 2] += faceNormal.z;
  27100. normals[i3 * 3] += faceNormal.x;
  27101. normals[i3 * 3 + 1] += faceNormal.y;
  27102. normals[i3 * 3 + 2] += faceNormal.z;
  27103. }
  27104. // last normalization
  27105. for (index = 0; index < normals.length / 3; index++) {
  27106. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  27107. vertexNormali1.normalize();
  27108. normals[index * 3] = vertexNormali1.x;
  27109. normals[index * 3 + 1] = vertexNormali1.y;
  27110. normals[index * 3 + 2] = vertexNormali1.z;
  27111. }
  27112. };
  27113. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27114. var li = indices.length;
  27115. var ln = normals.length;
  27116. var i;
  27117. var n;
  27118. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27119. switch (sideOrientation) {
  27120. case BABYLON.Mesh.FRONTSIDE:
  27121. // nothing changed
  27122. break;
  27123. case BABYLON.Mesh.BACKSIDE:
  27124. var tmp;
  27125. // indices
  27126. for (i = 0; i < li; i += 3) {
  27127. tmp = indices[i];
  27128. indices[i] = indices[i + 2];
  27129. indices[i + 2] = tmp;
  27130. }
  27131. // normals
  27132. for (n = 0; n < ln; n++) {
  27133. normals[n] = -normals[n];
  27134. }
  27135. break;
  27136. case BABYLON.Mesh.DOUBLESIDE:
  27137. // positions
  27138. var lp = positions.length;
  27139. var l = lp / 3;
  27140. for (var p = 0; p < lp; p++) {
  27141. positions[lp + p] = positions[p];
  27142. }
  27143. // indices
  27144. for (i = 0; i < li; i += 3) {
  27145. indices[i + li] = indices[i + 2] + l;
  27146. indices[i + 1 + li] = indices[i + 1] + l;
  27147. indices[i + 2 + li] = indices[i] + l;
  27148. }
  27149. // normals
  27150. for (n = 0; n < ln; n++) {
  27151. normals[ln + n] = -normals[n];
  27152. }
  27153. // uvs
  27154. var lu = uvs.length;
  27155. for (var u = 0; u < lu; u++) {
  27156. uvs[u + lu] = uvs[u];
  27157. }
  27158. break;
  27159. }
  27160. };
  27161. return VertexData;
  27162. })();
  27163. BABYLON.VertexData = VertexData;
  27164. })(BABYLON || (BABYLON = {}));
  27165. var BABYLON;
  27166. (function (BABYLON) {
  27167. var AnaglyphPostProcess = (function (_super) {
  27168. __extends(AnaglyphPostProcess, _super);
  27169. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27170. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  27171. }
  27172. return AnaglyphPostProcess;
  27173. })(BABYLON.PostProcess);
  27174. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  27175. })(BABYLON || (BABYLON = {}));
  27176. var BABYLON;
  27177. (function (BABYLON) {
  27178. var Tags = (function () {
  27179. function Tags() {
  27180. }
  27181. Tags.EnableFor = function (obj) {
  27182. obj._tags = obj._tags || {};
  27183. obj.hasTags = function () {
  27184. return Tags.HasTags(obj);
  27185. };
  27186. obj.addTags = function (tagsString) {
  27187. return Tags.AddTagsTo(obj, tagsString);
  27188. };
  27189. obj.removeTags = function (tagsString) {
  27190. return Tags.RemoveTagsFrom(obj, tagsString);
  27191. };
  27192. obj.matchesTagsQuery = function (tagsQuery) {
  27193. return Tags.MatchesQuery(obj, tagsQuery);
  27194. };
  27195. };
  27196. Tags.DisableFor = function (obj) {
  27197. delete obj._tags;
  27198. delete obj.hasTags;
  27199. delete obj.addTags;
  27200. delete obj.removeTags;
  27201. delete obj.matchesTagsQuery;
  27202. };
  27203. Tags.HasTags = function (obj) {
  27204. if (!obj._tags) {
  27205. return false;
  27206. }
  27207. return !BABYLON.Tools.IsEmpty(obj._tags);
  27208. };
  27209. Tags.GetTags = function (obj) {
  27210. if (!obj._tags) {
  27211. return null;
  27212. }
  27213. return obj._tags;
  27214. };
  27215. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27216. // a tag cannot start with '||', '&&', and '!'
  27217. // it cannot contain whitespaces
  27218. Tags.AddTagsTo = function (obj, tagsString) {
  27219. if (!tagsString) {
  27220. return;
  27221. }
  27222. var tags = tagsString.split(" ");
  27223. for (var t in tags) {
  27224. Tags._AddTagTo(obj, tags[t]);
  27225. }
  27226. };
  27227. Tags._AddTagTo = function (obj, tag) {
  27228. tag = tag.trim();
  27229. if (tag === "" || tag === "true" || tag === "false") {
  27230. return;
  27231. }
  27232. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27233. return;
  27234. }
  27235. Tags.EnableFor(obj);
  27236. obj._tags[tag] = true;
  27237. };
  27238. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27239. if (!Tags.HasTags(obj)) {
  27240. return;
  27241. }
  27242. var tags = tagsString.split(" ");
  27243. for (var t in tags) {
  27244. Tags._RemoveTagFrom(obj, tags[t]);
  27245. }
  27246. };
  27247. Tags._RemoveTagFrom = function (obj, tag) {
  27248. delete obj._tags[tag];
  27249. };
  27250. Tags.MatchesQuery = function (obj, tagsQuery) {
  27251. if (tagsQuery === undefined) {
  27252. return true;
  27253. }
  27254. if (tagsQuery === "") {
  27255. return Tags.HasTags(obj);
  27256. }
  27257. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27258. };
  27259. return Tags;
  27260. })();
  27261. BABYLON.Tags = Tags;
  27262. })(BABYLON || (BABYLON = {}));
  27263. var BABYLON;
  27264. (function (BABYLON) {
  27265. var Internals;
  27266. (function (Internals) {
  27267. var AndOrNotEvaluator = (function () {
  27268. function AndOrNotEvaluator() {
  27269. }
  27270. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27271. if (!query.match(/\([^\(\)]*\)/g)) {
  27272. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27273. }
  27274. else {
  27275. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27276. // remove parenthesis
  27277. r = r.slice(1, r.length - 1);
  27278. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27279. });
  27280. }
  27281. if (query === "true") {
  27282. return true;
  27283. }
  27284. if (query === "false") {
  27285. return false;
  27286. }
  27287. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27288. };
  27289. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27290. evaluateCallback = evaluateCallback || (function (r) {
  27291. return r === "true" ? true : false;
  27292. });
  27293. var result;
  27294. var or = parenthesisContent.split("||");
  27295. for (var i in or) {
  27296. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27297. var and = ori.split("&&");
  27298. if (and.length > 1) {
  27299. for (var j = 0; j < and.length; ++j) {
  27300. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27301. if (andj !== "true" && andj !== "false") {
  27302. if (andj[0] === "!") {
  27303. result = !evaluateCallback(andj.substring(1));
  27304. }
  27305. else {
  27306. result = evaluateCallback(andj);
  27307. }
  27308. }
  27309. else {
  27310. result = andj === "true" ? true : false;
  27311. }
  27312. if (!result) {
  27313. ori = "false";
  27314. break;
  27315. }
  27316. }
  27317. }
  27318. if (result || ori === "true") {
  27319. result = true;
  27320. break;
  27321. }
  27322. // result equals false (or undefined)
  27323. if (ori !== "true" && ori !== "false") {
  27324. if (ori[0] === "!") {
  27325. result = !evaluateCallback(ori.substring(1));
  27326. }
  27327. else {
  27328. result = evaluateCallback(ori);
  27329. }
  27330. }
  27331. else {
  27332. result = ori === "true" ? true : false;
  27333. }
  27334. }
  27335. // the whole parenthesis scope is replaced by 'true' or 'false'
  27336. return result ? "true" : "false";
  27337. };
  27338. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27339. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27340. // remove whitespaces
  27341. r = r.replace(/[\s]/g, function () { return ""; });
  27342. return r.length % 2 ? "!" : "";
  27343. });
  27344. booleanString = booleanString.trim();
  27345. if (booleanString === "!true") {
  27346. booleanString = "false";
  27347. }
  27348. else if (booleanString === "!false") {
  27349. booleanString = "true";
  27350. }
  27351. return booleanString;
  27352. };
  27353. return AndOrNotEvaluator;
  27354. })();
  27355. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27356. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27357. })(BABYLON || (BABYLON = {}));
  27358. var BABYLON;
  27359. (function (BABYLON) {
  27360. var PostProcessRenderPass = (function () {
  27361. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27362. this._enabled = true;
  27363. this._refCount = 0;
  27364. this._name = name;
  27365. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27366. this.setRenderList(renderList);
  27367. this._renderTexture.onBeforeRender = beforeRender;
  27368. this._renderTexture.onAfterRender = afterRender;
  27369. this._scene = scene;
  27370. this._renderList = renderList;
  27371. }
  27372. // private
  27373. PostProcessRenderPass.prototype._incRefCount = function () {
  27374. if (this._refCount === 0) {
  27375. this._scene.customRenderTargets.push(this._renderTexture);
  27376. }
  27377. return ++this._refCount;
  27378. };
  27379. PostProcessRenderPass.prototype._decRefCount = function () {
  27380. this._refCount--;
  27381. if (this._refCount <= 0) {
  27382. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27383. }
  27384. return this._refCount;
  27385. };
  27386. PostProcessRenderPass.prototype._update = function () {
  27387. this.setRenderList(this._renderList);
  27388. };
  27389. // public
  27390. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27391. this._renderTexture.renderList = renderList;
  27392. };
  27393. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27394. return this._renderTexture;
  27395. };
  27396. return PostProcessRenderPass;
  27397. })();
  27398. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27399. })(BABYLON || (BABYLON = {}));
  27400. var BABYLON;
  27401. (function (BABYLON) {
  27402. var PostProcessRenderEffect = (function () {
  27403. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27404. this._engine = engine;
  27405. this._name = name;
  27406. this._singleInstance = singleInstance || true;
  27407. this._getPostProcess = getPostProcess;
  27408. this._cameras = [];
  27409. this._indicesForCamera = [];
  27410. this._postProcesses = {};
  27411. this._renderPasses = {};
  27412. this._renderEffectAsPasses = {};
  27413. }
  27414. PostProcessRenderEffect.prototype._update = function () {
  27415. for (var renderPassName in this._renderPasses) {
  27416. this._renderPasses[renderPassName]._update();
  27417. }
  27418. };
  27419. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27420. this._renderPasses[renderPass._name] = renderPass;
  27421. this._linkParameters();
  27422. };
  27423. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27424. delete this._renderPasses[renderPass._name];
  27425. this._linkParameters();
  27426. };
  27427. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27428. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27429. this._linkParameters();
  27430. };
  27431. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27432. for (var renderPassName in this._renderPasses) {
  27433. if (renderPassName === passName) {
  27434. return this._renderPasses[passName];
  27435. }
  27436. }
  27437. };
  27438. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27439. this._renderPasses = {};
  27440. this._linkParameters();
  27441. };
  27442. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27443. var cameraKey;
  27444. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27445. for (var i = 0; i < _cam.length; i++) {
  27446. var camera = _cam[i];
  27447. var cameraName = camera.name;
  27448. if (this._singleInstance) {
  27449. cameraKey = 0;
  27450. }
  27451. else {
  27452. cameraKey = cameraName;
  27453. }
  27454. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27455. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27456. if (!this._indicesForCamera[cameraName]) {
  27457. this._indicesForCamera[cameraName] = [];
  27458. }
  27459. this._indicesForCamera[cameraName].push(index);
  27460. if (this._cameras.indexOf(camera) === -1) {
  27461. this._cameras[cameraName] = camera;
  27462. }
  27463. for (var passName in this._renderPasses) {
  27464. this._renderPasses[passName]._incRefCount();
  27465. }
  27466. }
  27467. this._linkParameters();
  27468. };
  27469. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27470. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27471. for (var i = 0; i < _cam.length; i++) {
  27472. var camera = _cam[i];
  27473. var cameraName = camera.name;
  27474. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27475. var index = this._cameras.indexOf(cameraName);
  27476. this._indicesForCamera.splice(index, 1);
  27477. this._cameras.splice(index, 1);
  27478. for (var passName in this._renderPasses) {
  27479. this._renderPasses[passName]._decRefCount();
  27480. }
  27481. }
  27482. };
  27483. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27484. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27485. for (var i = 0; i < _cam.length; i++) {
  27486. var camera = _cam[i];
  27487. var cameraName = camera.name;
  27488. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27489. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27490. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27491. }
  27492. }
  27493. for (var passName in this._renderPasses) {
  27494. this._renderPasses[passName]._incRefCount();
  27495. }
  27496. }
  27497. };
  27498. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27499. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27500. for (var i = 0; i < _cam.length; i++) {
  27501. var camera = _cam[i];
  27502. var cameraName = camera.Name;
  27503. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27504. for (var passName in this._renderPasses) {
  27505. this._renderPasses[passName]._decRefCount();
  27506. }
  27507. }
  27508. };
  27509. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27510. if (this._singleInstance) {
  27511. return this._postProcesses[0];
  27512. }
  27513. else {
  27514. return this._postProcesses[camera.name];
  27515. }
  27516. };
  27517. PostProcessRenderEffect.prototype._linkParameters = function () {
  27518. var _this = this;
  27519. for (var index in this._postProcesses) {
  27520. if (this.applyParameters) {
  27521. this.applyParameters(this._postProcesses[index]);
  27522. }
  27523. this._postProcesses[index].onBeforeRender = function (effect) {
  27524. _this._linkTextures(effect);
  27525. };
  27526. }
  27527. };
  27528. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  27529. for (var renderPassName in this._renderPasses) {
  27530. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  27531. }
  27532. for (var renderEffectName in this._renderEffectAsPasses) {
  27533. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  27534. }
  27535. };
  27536. return PostProcessRenderEffect;
  27537. })();
  27538. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  27539. })(BABYLON || (BABYLON = {}));
  27540. var BABYLON;
  27541. (function (BABYLON) {
  27542. var PostProcessRenderPipeline = (function () {
  27543. function PostProcessRenderPipeline(engine, name) {
  27544. this._engine = engine;
  27545. this._name = name;
  27546. this._renderEffects = {};
  27547. this._renderEffectsForIsolatedPass = {};
  27548. this._cameras = [];
  27549. }
  27550. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  27551. this._renderEffects[renderEffect._name] = renderEffect;
  27552. };
  27553. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  27554. var renderEffects = this._renderEffects[renderEffectName];
  27555. if (!renderEffects) {
  27556. return;
  27557. }
  27558. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27559. };
  27560. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  27561. var renderEffects = this._renderEffects[renderEffectName];
  27562. if (!renderEffects) {
  27563. return;
  27564. }
  27565. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27566. };
  27567. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  27568. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27569. var indicesToDelete = [];
  27570. for (var i = 0; i < _cam.length; i++) {
  27571. var camera = _cam[i];
  27572. var cameraName = camera.name;
  27573. if (this._cameras.indexOf(camera) === -1) {
  27574. this._cameras[cameraName] = camera;
  27575. }
  27576. else if (unique) {
  27577. indicesToDelete.push(i);
  27578. }
  27579. }
  27580. for (var i = 0; i < indicesToDelete.length; i++) {
  27581. cameras.splice(indicesToDelete[i], 1);
  27582. }
  27583. for (var renderEffectName in this._renderEffects) {
  27584. this._renderEffects[renderEffectName]._attachCameras(_cam);
  27585. }
  27586. };
  27587. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  27588. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27589. for (var renderEffectName in this._renderEffects) {
  27590. this._renderEffects[renderEffectName]._detachCameras(_cam);
  27591. }
  27592. for (var i = 0; i < _cam.length; i++) {
  27593. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  27594. }
  27595. };
  27596. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  27597. var _this = this;
  27598. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27599. var pass = null;
  27600. for (var renderEffectName in this._renderEffects) {
  27601. pass = this._renderEffects[renderEffectName].getPass(passName);
  27602. if (pass != null) {
  27603. break;
  27604. }
  27605. }
  27606. if (pass === null) {
  27607. return;
  27608. }
  27609. for (var renderEffectName in this._renderEffects) {
  27610. this._renderEffects[renderEffectName]._disable(_cam);
  27611. }
  27612. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  27613. for (var i = 0; i < _cam.length; i++) {
  27614. var camera = _cam[i];
  27615. var cameraName = camera.name;
  27616. 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); });
  27617. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  27618. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  27619. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  27620. }
  27621. };
  27622. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  27623. var _this = this;
  27624. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27625. for (var i = 0; i < _cam.length; i++) {
  27626. var camera = _cam[i];
  27627. var cameraName = camera.name;
  27628. 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); });
  27629. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  27630. }
  27631. for (var renderEffectName in this._renderEffects) {
  27632. this._renderEffects[renderEffectName]._enable(_cam);
  27633. }
  27634. };
  27635. PostProcessRenderPipeline.prototype._update = function () {
  27636. for (var renderEffectName in this._renderEffects) {
  27637. this._renderEffects[renderEffectName]._update();
  27638. }
  27639. for (var i = 0; i < this._cameras.length; i++) {
  27640. var cameraName = this._cameras[i].name;
  27641. if (this._renderEffectsForIsolatedPass[cameraName]) {
  27642. this._renderEffectsForIsolatedPass[cameraName]._update();
  27643. }
  27644. }
  27645. };
  27646. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  27647. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  27648. return PostProcessRenderPipeline;
  27649. })();
  27650. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  27651. })(BABYLON || (BABYLON = {}));
  27652. var BABYLON;
  27653. (function (BABYLON) {
  27654. var PostProcessRenderPipelineManager = (function () {
  27655. function PostProcessRenderPipelineManager() {
  27656. this._renderPipelines = {};
  27657. }
  27658. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  27659. this._renderPipelines[renderPipeline._name] = renderPipeline;
  27660. };
  27661. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  27662. var renderPipeline = this._renderPipelines[renderPipelineName];
  27663. if (!renderPipeline) {
  27664. return;
  27665. }
  27666. renderPipeline._attachCameras(cameras, unique);
  27667. };
  27668. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  27669. var renderPipeline = this._renderPipelines[renderPipelineName];
  27670. if (!renderPipeline) {
  27671. return;
  27672. }
  27673. renderPipeline._detachCameras(cameras);
  27674. };
  27675. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27676. var renderPipeline = this._renderPipelines[renderPipelineName];
  27677. if (!renderPipeline) {
  27678. return;
  27679. }
  27680. renderPipeline._enableEffect(renderEffectName, cameras);
  27681. };
  27682. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27683. var renderPipeline = this._renderPipelines[renderPipelineName];
  27684. if (!renderPipeline) {
  27685. return;
  27686. }
  27687. renderPipeline._disableEffect(renderEffectName, cameras);
  27688. };
  27689. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  27690. var renderPipeline = this._renderPipelines[renderPipelineName];
  27691. if (!renderPipeline) {
  27692. return;
  27693. }
  27694. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  27695. };
  27696. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  27697. var renderPipeline = this._renderPipelines[renderPipelineName];
  27698. if (!renderPipeline) {
  27699. return;
  27700. }
  27701. renderPipeline._disableDisplayOnlyPass(cameras);
  27702. };
  27703. PostProcessRenderPipelineManager.prototype.update = function () {
  27704. for (var renderPipelineName in this._renderPipelines) {
  27705. this._renderPipelines[renderPipelineName]._update();
  27706. }
  27707. };
  27708. return PostProcessRenderPipelineManager;
  27709. })();
  27710. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  27711. })(BABYLON || (BABYLON = {}));
  27712. var BABYLON;
  27713. (function (BABYLON) {
  27714. var DisplayPassPostProcess = (function (_super) {
  27715. __extends(DisplayPassPostProcess, _super);
  27716. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27717. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  27718. }
  27719. return DisplayPassPostProcess;
  27720. })(BABYLON.PostProcess);
  27721. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  27722. })(BABYLON || (BABYLON = {}));
  27723. var BABYLON;
  27724. (function (BABYLON) {
  27725. var BoundingBoxRenderer = (function () {
  27726. function BoundingBoxRenderer(scene) {
  27727. this.frontColor = new BABYLON.Color3(1, 1, 1);
  27728. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  27729. this.showBackLines = true;
  27730. this.renderList = new BABYLON.SmartArray(32);
  27731. this._scene = scene;
  27732. }
  27733. BoundingBoxRenderer.prototype._prepareRessources = function () {
  27734. if (this._colorShader) {
  27735. return;
  27736. }
  27737. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  27738. attributes: ["position"],
  27739. uniforms: ["worldViewProjection", "color"]
  27740. });
  27741. var engine = this._scene.getEngine();
  27742. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  27743. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  27744. 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]);
  27745. };
  27746. BoundingBoxRenderer.prototype.reset = function () {
  27747. this.renderList.reset();
  27748. };
  27749. BoundingBoxRenderer.prototype.render = function () {
  27750. if (this.renderList.length === 0) {
  27751. return;
  27752. }
  27753. this._prepareRessources();
  27754. if (!this._colorShader.isReady()) {
  27755. return;
  27756. }
  27757. var engine = this._scene.getEngine();
  27758. engine.setDepthWrite(false);
  27759. this._colorShader._preBind();
  27760. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27761. var boundingBox = this.renderList.data[boundingBoxIndex];
  27762. var min = boundingBox.minimum;
  27763. var max = boundingBox.maximum;
  27764. var diff = max.subtract(min);
  27765. var median = min.add(diff.scale(0.5));
  27766. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27767. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27768. .multiply(boundingBox.getWorldMatrix());
  27769. // VBOs
  27770. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27771. if (this.showBackLines) {
  27772. // Back
  27773. engine.setDepthFunctionToGreaterOrEqual();
  27774. this._scene.resetCachedMaterial();
  27775. this._colorShader.setColor4("color", this.backColor.toColor4());
  27776. this._colorShader.bind(worldMatrix);
  27777. // Draw order
  27778. engine.draw(false, 0, 24);
  27779. }
  27780. // Front
  27781. engine.setDepthFunctionToLess();
  27782. this._scene.resetCachedMaterial();
  27783. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27784. this._colorShader.bind(worldMatrix);
  27785. // Draw order
  27786. engine.draw(false, 0, 24);
  27787. }
  27788. this._colorShader.unbind();
  27789. engine.setDepthFunctionToLessOrEqual();
  27790. engine.setDepthWrite(true);
  27791. };
  27792. BoundingBoxRenderer.prototype.dispose = function () {
  27793. if (!this._colorShader) {
  27794. return;
  27795. }
  27796. this._colorShader.dispose();
  27797. this._vb.dispose();
  27798. this._scene.getEngine()._releaseBuffer(this._ib);
  27799. };
  27800. return BoundingBoxRenderer;
  27801. })();
  27802. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27803. })(BABYLON || (BABYLON = {}));
  27804. var BABYLON;
  27805. (function (BABYLON) {
  27806. var Condition = (function () {
  27807. function Condition(actionManager) {
  27808. this._actionManager = actionManager;
  27809. }
  27810. Condition.prototype.isValid = function () {
  27811. return true;
  27812. };
  27813. Condition.prototype._getProperty = function (propertyPath) {
  27814. return this._actionManager._getProperty(propertyPath);
  27815. };
  27816. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27817. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27818. };
  27819. return Condition;
  27820. })();
  27821. BABYLON.Condition = Condition;
  27822. var ValueCondition = (function (_super) {
  27823. __extends(ValueCondition, _super);
  27824. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27825. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27826. _super.call(this, actionManager);
  27827. this.propertyPath = propertyPath;
  27828. this.value = value;
  27829. this.operator = operator;
  27830. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27831. this._property = this._getProperty(this.propertyPath);
  27832. }
  27833. Object.defineProperty(ValueCondition, "IsEqual", {
  27834. get: function () {
  27835. return ValueCondition._IsEqual;
  27836. },
  27837. enumerable: true,
  27838. configurable: true
  27839. });
  27840. Object.defineProperty(ValueCondition, "IsDifferent", {
  27841. get: function () {
  27842. return ValueCondition._IsDifferent;
  27843. },
  27844. enumerable: true,
  27845. configurable: true
  27846. });
  27847. Object.defineProperty(ValueCondition, "IsGreater", {
  27848. get: function () {
  27849. return ValueCondition._IsGreater;
  27850. },
  27851. enumerable: true,
  27852. configurable: true
  27853. });
  27854. Object.defineProperty(ValueCondition, "IsLesser", {
  27855. get: function () {
  27856. return ValueCondition._IsLesser;
  27857. },
  27858. enumerable: true,
  27859. configurable: true
  27860. });
  27861. // Methods
  27862. ValueCondition.prototype.isValid = function () {
  27863. switch (this.operator) {
  27864. case ValueCondition.IsGreater:
  27865. return this._target[this._property] > this.value;
  27866. case ValueCondition.IsLesser:
  27867. return this._target[this._property] < this.value;
  27868. case ValueCondition.IsEqual:
  27869. case ValueCondition.IsDifferent:
  27870. var check;
  27871. if (this.value.equals) {
  27872. check = this.value.equals(this._target[this._property]);
  27873. }
  27874. else {
  27875. check = this.value === this._target[this._property];
  27876. }
  27877. return this.operator === ValueCondition.IsEqual ? check : !check;
  27878. }
  27879. return false;
  27880. };
  27881. // Statics
  27882. ValueCondition._IsEqual = 0;
  27883. ValueCondition._IsDifferent = 1;
  27884. ValueCondition._IsGreater = 2;
  27885. ValueCondition._IsLesser = 3;
  27886. return ValueCondition;
  27887. })(Condition);
  27888. BABYLON.ValueCondition = ValueCondition;
  27889. var PredicateCondition = (function (_super) {
  27890. __extends(PredicateCondition, _super);
  27891. function PredicateCondition(actionManager, predicate) {
  27892. _super.call(this, actionManager);
  27893. this.predicate = predicate;
  27894. }
  27895. PredicateCondition.prototype.isValid = function () {
  27896. return this.predicate();
  27897. };
  27898. return PredicateCondition;
  27899. })(Condition);
  27900. BABYLON.PredicateCondition = PredicateCondition;
  27901. var StateCondition = (function (_super) {
  27902. __extends(StateCondition, _super);
  27903. function StateCondition(actionManager, target, value) {
  27904. _super.call(this, actionManager);
  27905. this.value = value;
  27906. this._target = target;
  27907. }
  27908. // Methods
  27909. StateCondition.prototype.isValid = function () {
  27910. return this._target.state === this.value;
  27911. };
  27912. return StateCondition;
  27913. })(Condition);
  27914. BABYLON.StateCondition = StateCondition;
  27915. })(BABYLON || (BABYLON = {}));
  27916. var BABYLON;
  27917. (function (BABYLON) {
  27918. var Action = (function () {
  27919. function Action(triggerOptions, condition) {
  27920. this.triggerOptions = triggerOptions;
  27921. if (triggerOptions.parameter) {
  27922. this.trigger = triggerOptions.trigger;
  27923. this._triggerParameter = triggerOptions.parameter;
  27924. }
  27925. else {
  27926. this.trigger = triggerOptions;
  27927. }
  27928. this._nextActiveAction = this;
  27929. this._condition = condition;
  27930. }
  27931. // Methods
  27932. Action.prototype._prepare = function () {
  27933. };
  27934. Action.prototype.getTriggerParameter = function () {
  27935. return this._triggerParameter;
  27936. };
  27937. Action.prototype._executeCurrent = function (evt) {
  27938. if (this._nextActiveAction._condition) {
  27939. var condition = this._nextActiveAction._condition;
  27940. var currentRenderId = this._actionManager.getScene().getRenderId();
  27941. // We cache the current evaluation for the current frame
  27942. if (condition._evaluationId === currentRenderId) {
  27943. if (!condition._currentResult) {
  27944. return;
  27945. }
  27946. }
  27947. else {
  27948. condition._evaluationId = currentRenderId;
  27949. if (!condition.isValid()) {
  27950. condition._currentResult = false;
  27951. return;
  27952. }
  27953. condition._currentResult = true;
  27954. }
  27955. }
  27956. this._nextActiveAction.execute(evt);
  27957. if (this._nextActiveAction._child) {
  27958. if (!this._nextActiveAction._child._actionManager) {
  27959. this._nextActiveAction._child._actionManager = this._actionManager;
  27960. }
  27961. this._nextActiveAction = this._nextActiveAction._child;
  27962. }
  27963. else {
  27964. this._nextActiveAction = this;
  27965. }
  27966. };
  27967. Action.prototype.execute = function (evt) {
  27968. };
  27969. Action.prototype.then = function (action) {
  27970. this._child = action;
  27971. action._actionManager = this._actionManager;
  27972. action._prepare();
  27973. return action;
  27974. };
  27975. Action.prototype._getProperty = function (propertyPath) {
  27976. return this._actionManager._getProperty(propertyPath);
  27977. };
  27978. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27979. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27980. };
  27981. return Action;
  27982. })();
  27983. BABYLON.Action = Action;
  27984. })(BABYLON || (BABYLON = {}));
  27985. var BABYLON;
  27986. (function (BABYLON) {
  27987. /**
  27988. * ActionEvent is the event beint sent when an action is triggered.
  27989. */
  27990. var ActionEvent = (function () {
  27991. /**
  27992. * @constructor
  27993. * @param source The mesh that triggered the action.
  27994. * @param pointerX the X mouse cursor position at the time of the event
  27995. * @param pointerY the Y mouse cursor position at the time of the event
  27996. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27997. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27998. */
  27999. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  28000. this.source = source;
  28001. this.pointerX = pointerX;
  28002. this.pointerY = pointerY;
  28003. this.meshUnderPointer = meshUnderPointer;
  28004. this.sourceEvent = sourceEvent;
  28005. this.additionalData = additionalData;
  28006. }
  28007. /**
  28008. * Helper function to auto-create an ActionEvent from a source mesh.
  28009. * @param source the source mesh that triggered the event
  28010. * @param evt {Event} The original (browser) event
  28011. */
  28012. ActionEvent.CreateNew = function (source, evt, additionalData) {
  28013. var scene = source.getScene();
  28014. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28015. };
  28016. /**
  28017. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28018. * @param scene the scene where the event occurred
  28019. * @param evt {Event} The original (browser) event
  28020. */
  28021. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28022. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28023. };
  28024. return ActionEvent;
  28025. })();
  28026. BABYLON.ActionEvent = ActionEvent;
  28027. /**
  28028. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28029. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28030. */
  28031. var ActionManager = (function () {
  28032. function ActionManager(scene) {
  28033. // Members
  28034. this.actions = new Array();
  28035. this._scene = scene;
  28036. scene._actionManagers.push(this);
  28037. }
  28038. Object.defineProperty(ActionManager, "NothingTrigger", {
  28039. get: function () {
  28040. return ActionManager._NothingTrigger;
  28041. },
  28042. enumerable: true,
  28043. configurable: true
  28044. });
  28045. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28046. get: function () {
  28047. return ActionManager._OnPickTrigger;
  28048. },
  28049. enumerable: true,
  28050. configurable: true
  28051. });
  28052. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28053. get: function () {
  28054. return ActionManager._OnLeftPickTrigger;
  28055. },
  28056. enumerable: true,
  28057. configurable: true
  28058. });
  28059. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28060. get: function () {
  28061. return ActionManager._OnRightPickTrigger;
  28062. },
  28063. enumerable: true,
  28064. configurable: true
  28065. });
  28066. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28067. get: function () {
  28068. return ActionManager._OnCenterPickTrigger;
  28069. },
  28070. enumerable: true,
  28071. configurable: true
  28072. });
  28073. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28074. get: function () {
  28075. return ActionManager._OnPointerOverTrigger;
  28076. },
  28077. enumerable: true,
  28078. configurable: true
  28079. });
  28080. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28081. get: function () {
  28082. return ActionManager._OnPointerOutTrigger;
  28083. },
  28084. enumerable: true,
  28085. configurable: true
  28086. });
  28087. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28088. get: function () {
  28089. return ActionManager._OnEveryFrameTrigger;
  28090. },
  28091. enumerable: true,
  28092. configurable: true
  28093. });
  28094. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28095. get: function () {
  28096. return ActionManager._OnIntersectionEnterTrigger;
  28097. },
  28098. enumerable: true,
  28099. configurable: true
  28100. });
  28101. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28102. get: function () {
  28103. return ActionManager._OnIntersectionExitTrigger;
  28104. },
  28105. enumerable: true,
  28106. configurable: true
  28107. });
  28108. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28109. get: function () {
  28110. return ActionManager._OnKeyDownTrigger;
  28111. },
  28112. enumerable: true,
  28113. configurable: true
  28114. });
  28115. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28116. get: function () {
  28117. return ActionManager._OnKeyUpTrigger;
  28118. },
  28119. enumerable: true,
  28120. configurable: true
  28121. });
  28122. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28123. get: function () {
  28124. return ActionManager._OnPickUpTrigger;
  28125. },
  28126. enumerable: true,
  28127. configurable: true
  28128. });
  28129. // Methods
  28130. ActionManager.prototype.dispose = function () {
  28131. var index = this._scene._actionManagers.indexOf(this);
  28132. if (index > -1) {
  28133. this._scene._actionManagers.splice(index, 1);
  28134. }
  28135. };
  28136. ActionManager.prototype.getScene = function () {
  28137. return this._scene;
  28138. };
  28139. /**
  28140. * Does this action manager handles actions of any of the given triggers
  28141. * @param {number[]} triggers - the triggers to be tested
  28142. * @return {boolean} whether one (or more) of the triggers is handeled
  28143. */
  28144. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28145. for (var index = 0; index < this.actions.length; index++) {
  28146. var action = this.actions[index];
  28147. if (triggers.indexOf(action.trigger) > -1) {
  28148. return true;
  28149. }
  28150. }
  28151. return false;
  28152. };
  28153. /**
  28154. * Does this action manager handles actions of a given trigger
  28155. * @param {number} trigger - the trigger to be tested
  28156. * @return {boolean} whether the trigger is handeled
  28157. */
  28158. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28159. for (var index = 0; index < this.actions.length; index++) {
  28160. var action = this.actions[index];
  28161. if (action.trigger === trigger) {
  28162. return true;
  28163. }
  28164. }
  28165. return false;
  28166. };
  28167. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28168. /**
  28169. * Does this action manager has pointer triggers
  28170. * @return {boolean} whether or not it has pointer triggers
  28171. */
  28172. get: function () {
  28173. for (var index = 0; index < this.actions.length; index++) {
  28174. var action = this.actions[index];
  28175. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28176. return true;
  28177. }
  28178. if (action.trigger == ActionManager._OnPickUpTrigger) {
  28179. return true;
  28180. }
  28181. }
  28182. return false;
  28183. },
  28184. enumerable: true,
  28185. configurable: true
  28186. });
  28187. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28188. /**
  28189. * Does this action manager has pick triggers
  28190. * @return {boolean} whether or not it has pick triggers
  28191. */
  28192. get: function () {
  28193. for (var index = 0; index < this.actions.length; index++) {
  28194. var action = this.actions[index];
  28195. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  28196. return true;
  28197. }
  28198. }
  28199. return false;
  28200. },
  28201. enumerable: true,
  28202. configurable: true
  28203. });
  28204. /**
  28205. * Registers an action to this action manager
  28206. * @param {BABYLON.Action} action - the action to be registered
  28207. * @return {BABYLON.Action} the action amended (prepared) after registration
  28208. */
  28209. ActionManager.prototype.registerAction = function (action) {
  28210. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28211. if (this.getScene().actionManager !== this) {
  28212. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28213. return null;
  28214. }
  28215. }
  28216. this.actions.push(action);
  28217. action._actionManager = this;
  28218. action._prepare();
  28219. return action;
  28220. };
  28221. /**
  28222. * Process a specific trigger
  28223. * @param {number} trigger - the trigger to process
  28224. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28225. */
  28226. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28227. for (var index = 0; index < this.actions.length; index++) {
  28228. var action = this.actions[index];
  28229. if (action.trigger === trigger) {
  28230. if (trigger === ActionManager.OnKeyUpTrigger
  28231. || trigger === ActionManager.OnKeyDownTrigger) {
  28232. var parameter = action.getTriggerParameter();
  28233. if (parameter) {
  28234. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28235. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28236. if (actualkey !== parameter.toLowerCase()) {
  28237. continue;
  28238. }
  28239. }
  28240. }
  28241. action._executeCurrent(evt);
  28242. }
  28243. }
  28244. };
  28245. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28246. var properties = propertyPath.split(".");
  28247. for (var index = 0; index < properties.length - 1; index++) {
  28248. target = target[properties[index]];
  28249. }
  28250. return target;
  28251. };
  28252. ActionManager.prototype._getProperty = function (propertyPath) {
  28253. var properties = propertyPath.split(".");
  28254. return properties[properties.length - 1];
  28255. };
  28256. // Statics
  28257. ActionManager._NothingTrigger = 0;
  28258. ActionManager._OnPickTrigger = 1;
  28259. ActionManager._OnLeftPickTrigger = 2;
  28260. ActionManager._OnRightPickTrigger = 3;
  28261. ActionManager._OnCenterPickTrigger = 4;
  28262. ActionManager._OnPointerOverTrigger = 5;
  28263. ActionManager._OnPointerOutTrigger = 6;
  28264. ActionManager._OnEveryFrameTrigger = 7;
  28265. ActionManager._OnIntersectionEnterTrigger = 8;
  28266. ActionManager._OnIntersectionExitTrigger = 9;
  28267. ActionManager._OnKeyDownTrigger = 10;
  28268. ActionManager._OnKeyUpTrigger = 11;
  28269. ActionManager._OnPickUpTrigger = 12;
  28270. return ActionManager;
  28271. })();
  28272. BABYLON.ActionManager = ActionManager;
  28273. })(BABYLON || (BABYLON = {}));
  28274. var BABYLON;
  28275. (function (BABYLON) {
  28276. var InterpolateValueAction = (function (_super) {
  28277. __extends(InterpolateValueAction, _super);
  28278. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  28279. if (duration === void 0) { duration = 1000; }
  28280. _super.call(this, triggerOptions, condition);
  28281. this.propertyPath = propertyPath;
  28282. this.value = value;
  28283. this.duration = duration;
  28284. this.stopOtherAnimations = stopOtherAnimations;
  28285. this._target = target;
  28286. }
  28287. InterpolateValueAction.prototype._prepare = function () {
  28288. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28289. this._property = this._getProperty(this.propertyPath);
  28290. };
  28291. InterpolateValueAction.prototype.execute = function () {
  28292. var scene = this._actionManager.getScene();
  28293. var keys = [
  28294. {
  28295. frame: 0,
  28296. value: this._target[this._property]
  28297. }, {
  28298. frame: 100,
  28299. value: this.value
  28300. }
  28301. ];
  28302. var dataType;
  28303. if (typeof this.value === "number") {
  28304. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28305. }
  28306. else if (this.value instanceof BABYLON.Color3) {
  28307. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28308. }
  28309. else if (this.value instanceof BABYLON.Vector3) {
  28310. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28311. }
  28312. else if (this.value instanceof BABYLON.Matrix) {
  28313. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28314. }
  28315. else if (this.value instanceof BABYLON.Quaternion) {
  28316. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28317. }
  28318. else {
  28319. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28320. return;
  28321. }
  28322. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28323. animation.setKeys(keys);
  28324. if (this.stopOtherAnimations) {
  28325. scene.stopAnimation(this._target);
  28326. }
  28327. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  28328. };
  28329. return InterpolateValueAction;
  28330. })(BABYLON.Action);
  28331. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28332. })(BABYLON || (BABYLON = {}));
  28333. var BABYLON;
  28334. (function (BABYLON) {
  28335. var SwitchBooleanAction = (function (_super) {
  28336. __extends(SwitchBooleanAction, _super);
  28337. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28338. _super.call(this, triggerOptions, condition);
  28339. this.propertyPath = propertyPath;
  28340. this._target = target;
  28341. }
  28342. SwitchBooleanAction.prototype._prepare = function () {
  28343. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28344. this._property = this._getProperty(this.propertyPath);
  28345. };
  28346. SwitchBooleanAction.prototype.execute = function () {
  28347. this._target[this._property] = !this._target[this._property];
  28348. };
  28349. return SwitchBooleanAction;
  28350. })(BABYLON.Action);
  28351. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28352. var SetStateAction = (function (_super) {
  28353. __extends(SetStateAction, _super);
  28354. function SetStateAction(triggerOptions, target, value, condition) {
  28355. _super.call(this, triggerOptions, condition);
  28356. this.value = value;
  28357. this._target = target;
  28358. }
  28359. SetStateAction.prototype.execute = function () {
  28360. this._target.state = this.value;
  28361. };
  28362. return SetStateAction;
  28363. })(BABYLON.Action);
  28364. BABYLON.SetStateAction = SetStateAction;
  28365. var SetValueAction = (function (_super) {
  28366. __extends(SetValueAction, _super);
  28367. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28368. _super.call(this, triggerOptions, condition);
  28369. this.propertyPath = propertyPath;
  28370. this.value = value;
  28371. this._target = target;
  28372. }
  28373. SetValueAction.prototype._prepare = function () {
  28374. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28375. this._property = this._getProperty(this.propertyPath);
  28376. };
  28377. SetValueAction.prototype.execute = function () {
  28378. this._target[this._property] = this.value;
  28379. };
  28380. return SetValueAction;
  28381. })(BABYLON.Action);
  28382. BABYLON.SetValueAction = SetValueAction;
  28383. var IncrementValueAction = (function (_super) {
  28384. __extends(IncrementValueAction, _super);
  28385. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28386. _super.call(this, triggerOptions, condition);
  28387. this.propertyPath = propertyPath;
  28388. this.value = value;
  28389. this._target = target;
  28390. }
  28391. IncrementValueAction.prototype._prepare = function () {
  28392. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28393. this._property = this._getProperty(this.propertyPath);
  28394. if (typeof this._target[this._property] !== "number") {
  28395. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28396. }
  28397. };
  28398. IncrementValueAction.prototype.execute = function () {
  28399. this._target[this._property] += this.value;
  28400. };
  28401. return IncrementValueAction;
  28402. })(BABYLON.Action);
  28403. BABYLON.IncrementValueAction = IncrementValueAction;
  28404. var PlayAnimationAction = (function (_super) {
  28405. __extends(PlayAnimationAction, _super);
  28406. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28407. _super.call(this, triggerOptions, condition);
  28408. this.from = from;
  28409. this.to = to;
  28410. this.loop = loop;
  28411. this._target = target;
  28412. }
  28413. PlayAnimationAction.prototype._prepare = function () {
  28414. };
  28415. PlayAnimationAction.prototype.execute = function () {
  28416. var scene = this._actionManager.getScene();
  28417. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28418. };
  28419. return PlayAnimationAction;
  28420. })(BABYLON.Action);
  28421. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28422. var StopAnimationAction = (function (_super) {
  28423. __extends(StopAnimationAction, _super);
  28424. function StopAnimationAction(triggerOptions, target, condition) {
  28425. _super.call(this, triggerOptions, condition);
  28426. this._target = target;
  28427. }
  28428. StopAnimationAction.prototype._prepare = function () {
  28429. };
  28430. StopAnimationAction.prototype.execute = function () {
  28431. var scene = this._actionManager.getScene();
  28432. scene.stopAnimation(this._target);
  28433. };
  28434. return StopAnimationAction;
  28435. })(BABYLON.Action);
  28436. BABYLON.StopAnimationAction = StopAnimationAction;
  28437. var DoNothingAction = (function (_super) {
  28438. __extends(DoNothingAction, _super);
  28439. function DoNothingAction(triggerOptions, condition) {
  28440. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28441. _super.call(this, triggerOptions, condition);
  28442. }
  28443. DoNothingAction.prototype.execute = function () {
  28444. };
  28445. return DoNothingAction;
  28446. })(BABYLON.Action);
  28447. BABYLON.DoNothingAction = DoNothingAction;
  28448. var CombineAction = (function (_super) {
  28449. __extends(CombineAction, _super);
  28450. function CombineAction(triggerOptions, children, condition) {
  28451. _super.call(this, triggerOptions, condition);
  28452. this.children = children;
  28453. }
  28454. CombineAction.prototype._prepare = function () {
  28455. for (var index = 0; index < this.children.length; index++) {
  28456. this.children[index]._actionManager = this._actionManager;
  28457. this.children[index]._prepare();
  28458. }
  28459. };
  28460. CombineAction.prototype.execute = function (evt) {
  28461. for (var index = 0; index < this.children.length; index++) {
  28462. this.children[index].execute(evt);
  28463. }
  28464. };
  28465. return CombineAction;
  28466. })(BABYLON.Action);
  28467. BABYLON.CombineAction = CombineAction;
  28468. var ExecuteCodeAction = (function (_super) {
  28469. __extends(ExecuteCodeAction, _super);
  28470. function ExecuteCodeAction(triggerOptions, func, condition) {
  28471. _super.call(this, triggerOptions, condition);
  28472. this.func = func;
  28473. }
  28474. ExecuteCodeAction.prototype.execute = function (evt) {
  28475. this.func(evt);
  28476. };
  28477. return ExecuteCodeAction;
  28478. })(BABYLON.Action);
  28479. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28480. var SetParentAction = (function (_super) {
  28481. __extends(SetParentAction, _super);
  28482. function SetParentAction(triggerOptions, target, parent, condition) {
  28483. _super.call(this, triggerOptions, condition);
  28484. this._target = target;
  28485. this._parent = parent;
  28486. }
  28487. SetParentAction.prototype._prepare = function () {
  28488. };
  28489. SetParentAction.prototype.execute = function () {
  28490. if (this._target.parent === this._parent) {
  28491. return;
  28492. }
  28493. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28494. invertParentWorldMatrix.invert();
  28495. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28496. this._target.parent = this._parent;
  28497. };
  28498. return SetParentAction;
  28499. })(BABYLON.Action);
  28500. BABYLON.SetParentAction = SetParentAction;
  28501. var PlaySoundAction = (function (_super) {
  28502. __extends(PlaySoundAction, _super);
  28503. function PlaySoundAction(triggerOptions, sound, condition) {
  28504. _super.call(this, triggerOptions, condition);
  28505. this._sound = sound;
  28506. }
  28507. PlaySoundAction.prototype._prepare = function () {
  28508. };
  28509. PlaySoundAction.prototype.execute = function () {
  28510. if (this._sound !== undefined)
  28511. this._sound.play();
  28512. };
  28513. return PlaySoundAction;
  28514. })(BABYLON.Action);
  28515. BABYLON.PlaySoundAction = PlaySoundAction;
  28516. var StopSoundAction = (function (_super) {
  28517. __extends(StopSoundAction, _super);
  28518. function StopSoundAction(triggerOptions, sound, condition) {
  28519. _super.call(this, triggerOptions, condition);
  28520. this._sound = sound;
  28521. }
  28522. StopSoundAction.prototype._prepare = function () {
  28523. };
  28524. StopSoundAction.prototype.execute = function () {
  28525. if (this._sound !== undefined)
  28526. this._sound.stop();
  28527. };
  28528. return StopSoundAction;
  28529. })(BABYLON.Action);
  28530. BABYLON.StopSoundAction = StopSoundAction;
  28531. })(BABYLON || (BABYLON = {}));
  28532. var BABYLON;
  28533. (function (BABYLON) {
  28534. var Geometry = (function () {
  28535. function Geometry(id, scene, vertexData, updatable, mesh) {
  28536. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28537. this._totalVertices = 0;
  28538. this._indices = [];
  28539. this._isDisposed = false;
  28540. this.id = id;
  28541. this._engine = scene.getEngine();
  28542. this._meshes = [];
  28543. this._scene = scene;
  28544. // vertexData
  28545. if (vertexData) {
  28546. this.setAllVerticesData(vertexData, updatable);
  28547. }
  28548. else {
  28549. this._totalVertices = 0;
  28550. this._indices = [];
  28551. }
  28552. // applyToMesh
  28553. if (mesh) {
  28554. this.applyToMesh(mesh);
  28555. mesh.computeWorldMatrix(true);
  28556. }
  28557. }
  28558. Geometry.prototype.getScene = function () {
  28559. return this._scene;
  28560. };
  28561. Geometry.prototype.getEngine = function () {
  28562. return this._engine;
  28563. };
  28564. Geometry.prototype.isReady = function () {
  28565. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28566. };
  28567. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28568. vertexData.applyToGeometry(this, updatable);
  28569. this.notifyUpdate();
  28570. };
  28571. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28572. this._vertexBuffers = this._vertexBuffers || {};
  28573. if (this._vertexBuffers[kind]) {
  28574. this._vertexBuffers[kind].dispose();
  28575. }
  28576. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28577. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28578. stride = this._vertexBuffers[kind].getStrideSize();
  28579. this._totalVertices = data.length / stride;
  28580. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28581. var meshes = this._meshes;
  28582. var numOfMeshes = meshes.length;
  28583. for (var index = 0; index < numOfMeshes; index++) {
  28584. var mesh = meshes[index];
  28585. mesh._resetPointsArrayCache();
  28586. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28587. mesh._createGlobalSubMesh();
  28588. mesh.computeWorldMatrix(true);
  28589. }
  28590. }
  28591. this.notifyUpdate(kind);
  28592. };
  28593. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28594. var vertexBuffer = this.getVertexBuffer(kind);
  28595. if (!vertexBuffer) {
  28596. return;
  28597. }
  28598. vertexBuffer.updateDirectly(data, offset);
  28599. this.notifyUpdate(kind);
  28600. };
  28601. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28602. var vertexBuffer = this.getVertexBuffer(kind);
  28603. if (!vertexBuffer) {
  28604. return;
  28605. }
  28606. vertexBuffer.update(data);
  28607. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28608. var extend;
  28609. var stride = vertexBuffer.getStrideSize();
  28610. this._totalVertices = data.length / stride;
  28611. if (updateExtends) {
  28612. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28613. }
  28614. var meshes = this._meshes;
  28615. var numOfMeshes = meshes.length;
  28616. for (var index = 0; index < numOfMeshes; index++) {
  28617. var mesh = meshes[index];
  28618. mesh._resetPointsArrayCache();
  28619. if (updateExtends) {
  28620. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28621. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28622. var subMesh = mesh.subMeshes[subIndex];
  28623. subMesh.refreshBoundingInfo();
  28624. }
  28625. }
  28626. }
  28627. }
  28628. this.notifyUpdate(kind);
  28629. };
  28630. Geometry.prototype.getTotalVertices = function () {
  28631. if (!this.isReady()) {
  28632. return 0;
  28633. }
  28634. return this._totalVertices;
  28635. };
  28636. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28637. var vertexBuffer = this.getVertexBuffer(kind);
  28638. if (!vertexBuffer) {
  28639. return null;
  28640. }
  28641. var orig = vertexBuffer.getData();
  28642. if (!copyWhenShared || this._meshes.length === 1) {
  28643. return orig;
  28644. }
  28645. else {
  28646. var len = orig.length;
  28647. var copy = [];
  28648. for (var i = 0; i < len; i++) {
  28649. copy.push(orig[i]);
  28650. }
  28651. return copy;
  28652. }
  28653. };
  28654. Geometry.prototype.getVertexBuffer = function (kind) {
  28655. if (!this.isReady()) {
  28656. return null;
  28657. }
  28658. return this._vertexBuffers[kind];
  28659. };
  28660. Geometry.prototype.getVertexBuffers = function () {
  28661. if (!this.isReady()) {
  28662. return null;
  28663. }
  28664. return this._vertexBuffers;
  28665. };
  28666. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28667. if (!this._vertexBuffers) {
  28668. if (this._delayInfo) {
  28669. return this._delayInfo.indexOf(kind) !== -1;
  28670. }
  28671. return false;
  28672. }
  28673. return this._vertexBuffers[kind] !== undefined;
  28674. };
  28675. Geometry.prototype.getVerticesDataKinds = function () {
  28676. var result = [];
  28677. if (!this._vertexBuffers && this._delayInfo) {
  28678. for (var kind in this._delayInfo) {
  28679. result.push(kind);
  28680. }
  28681. }
  28682. else {
  28683. for (kind in this._vertexBuffers) {
  28684. result.push(kind);
  28685. }
  28686. }
  28687. return result;
  28688. };
  28689. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28690. if (this._indexBuffer) {
  28691. this._engine._releaseBuffer(this._indexBuffer);
  28692. }
  28693. this._indices = indices;
  28694. if (this._meshes.length !== 0 && this._indices) {
  28695. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28696. }
  28697. if (totalVertices !== undefined) {
  28698. this._totalVertices = totalVertices;
  28699. }
  28700. var meshes = this._meshes;
  28701. var numOfMeshes = meshes.length;
  28702. for (var index = 0; index < numOfMeshes; index++) {
  28703. meshes[index]._createGlobalSubMesh();
  28704. }
  28705. this.notifyUpdate();
  28706. };
  28707. Geometry.prototype.getTotalIndices = function () {
  28708. if (!this.isReady()) {
  28709. return 0;
  28710. }
  28711. return this._indices.length;
  28712. };
  28713. Geometry.prototype.getIndices = function (copyWhenShared) {
  28714. if (!this.isReady()) {
  28715. return null;
  28716. }
  28717. var orig = this._indices;
  28718. if (!copyWhenShared || this._meshes.length === 1) {
  28719. return orig;
  28720. }
  28721. else {
  28722. var len = orig.length;
  28723. var copy = [];
  28724. for (var i = 0; i < len; i++) {
  28725. copy.push(orig[i]);
  28726. }
  28727. return copy;
  28728. }
  28729. };
  28730. Geometry.prototype.getIndexBuffer = function () {
  28731. if (!this.isReady()) {
  28732. return null;
  28733. }
  28734. return this._indexBuffer;
  28735. };
  28736. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28737. var meshes = this._meshes;
  28738. var index = meshes.indexOf(mesh);
  28739. if (index === -1) {
  28740. return;
  28741. }
  28742. for (var kind in this._vertexBuffers) {
  28743. this._vertexBuffers[kind].dispose();
  28744. }
  28745. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28746. this._indexBuffer = null;
  28747. }
  28748. meshes.splice(index, 1);
  28749. mesh._geometry = null;
  28750. if (meshes.length === 0 && shouldDispose) {
  28751. this.dispose();
  28752. }
  28753. };
  28754. Geometry.prototype.applyToMesh = function (mesh) {
  28755. if (mesh._geometry === this) {
  28756. return;
  28757. }
  28758. var previousGeometry = mesh._geometry;
  28759. if (previousGeometry) {
  28760. previousGeometry.releaseForMesh(mesh);
  28761. }
  28762. var meshes = this._meshes;
  28763. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28764. mesh._geometry = this;
  28765. this._scene.pushGeometry(this);
  28766. meshes.push(mesh);
  28767. if (this.isReady()) {
  28768. this._applyToMesh(mesh);
  28769. }
  28770. else {
  28771. mesh._boundingInfo = this._boundingInfo;
  28772. }
  28773. };
  28774. Geometry.prototype._applyToMesh = function (mesh) {
  28775. var numOfMeshes = this._meshes.length;
  28776. // vertexBuffers
  28777. for (var kind in this._vertexBuffers) {
  28778. if (numOfMeshes === 1) {
  28779. this._vertexBuffers[kind].create();
  28780. }
  28781. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28782. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28783. mesh._resetPointsArrayCache();
  28784. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28785. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28786. mesh._createGlobalSubMesh();
  28787. //bounding info was just created again, world matrix should be applied again.
  28788. mesh._updateBoundingInfo();
  28789. }
  28790. }
  28791. // indexBuffer
  28792. if (numOfMeshes === 1 && this._indices) {
  28793. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28794. }
  28795. if (this._indexBuffer) {
  28796. this._indexBuffer.references = numOfMeshes;
  28797. }
  28798. };
  28799. Geometry.prototype.notifyUpdate = function (kind) {
  28800. if (this.onGeometryUpdated) {
  28801. this.onGeometryUpdated(this, kind);
  28802. }
  28803. };
  28804. Geometry.prototype.load = function (scene, onLoaded) {
  28805. var _this = this;
  28806. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28807. return;
  28808. }
  28809. if (this.isReady()) {
  28810. if (onLoaded) {
  28811. onLoaded();
  28812. }
  28813. return;
  28814. }
  28815. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28816. scene._addPendingData(this);
  28817. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28818. _this._delayLoadingFunction(JSON.parse(data), _this);
  28819. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28820. _this._delayInfo = [];
  28821. scene._removePendingData(_this);
  28822. var meshes = _this._meshes;
  28823. var numOfMeshes = meshes.length;
  28824. for (var index = 0; index < numOfMeshes; index++) {
  28825. _this._applyToMesh(meshes[index]);
  28826. }
  28827. if (onLoaded) {
  28828. onLoaded();
  28829. }
  28830. }, function () { }, scene.database);
  28831. };
  28832. Geometry.prototype.isDisposed = function () {
  28833. return this._isDisposed;
  28834. };
  28835. Geometry.prototype.dispose = function () {
  28836. var meshes = this._meshes;
  28837. var numOfMeshes = meshes.length;
  28838. var index;
  28839. for (index = 0; index < numOfMeshes; index++) {
  28840. this.releaseForMesh(meshes[index]);
  28841. }
  28842. this._meshes = [];
  28843. for (var kind in this._vertexBuffers) {
  28844. this._vertexBuffers[kind].dispose();
  28845. }
  28846. this._vertexBuffers = [];
  28847. this._totalVertices = 0;
  28848. if (this._indexBuffer) {
  28849. this._engine._releaseBuffer(this._indexBuffer);
  28850. }
  28851. this._indexBuffer = null;
  28852. this._indices = [];
  28853. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28854. this.delayLoadingFile = null;
  28855. this._delayLoadingFunction = null;
  28856. this._delayInfo = [];
  28857. this._boundingInfo = null; // todo: .dispose()
  28858. this._scene.removeGeometry(this);
  28859. this._isDisposed = true;
  28860. };
  28861. Geometry.prototype.copy = function (id) {
  28862. var vertexData = new BABYLON.VertexData();
  28863. vertexData.indices = [];
  28864. var indices = this.getIndices();
  28865. for (var index = 0; index < indices.length; index++) {
  28866. vertexData.indices.push(indices[index]);
  28867. }
  28868. var updatable = false;
  28869. var stopChecking = false;
  28870. for (var kind in this._vertexBuffers) {
  28871. // using slice() to make a copy of the array and not just reference it
  28872. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  28873. if (!stopChecking) {
  28874. updatable = this.getVertexBuffer(kind).isUpdatable();
  28875. stopChecking = !updatable;
  28876. }
  28877. }
  28878. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28879. geometry.delayLoadState = this.delayLoadState;
  28880. geometry.delayLoadingFile = this.delayLoadingFile;
  28881. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28882. for (kind in this._delayInfo) {
  28883. geometry._delayInfo = geometry._delayInfo || [];
  28884. geometry._delayInfo.push(kind);
  28885. }
  28886. // Bounding info
  28887. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  28888. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28889. return geometry;
  28890. };
  28891. // Statics
  28892. Geometry.ExtractFromMesh = function (mesh, id) {
  28893. var geometry = mesh._geometry;
  28894. if (!geometry) {
  28895. return null;
  28896. }
  28897. return geometry.copy(id);
  28898. };
  28899. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28900. // be aware Math.random() could cause collisions
  28901. Geometry.RandomId = function () {
  28902. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28903. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28904. return v.toString(16);
  28905. });
  28906. };
  28907. return Geometry;
  28908. })();
  28909. BABYLON.Geometry = Geometry;
  28910. /////// Primitives //////////////////////////////////////////////
  28911. var Geometry;
  28912. (function (Geometry) {
  28913. var Primitives;
  28914. (function (Primitives) {
  28915. /// Abstract class
  28916. var _Primitive = (function (_super) {
  28917. __extends(_Primitive, _super);
  28918. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  28919. this._beingRegenerated = true;
  28920. this._canBeRegenerated = canBeRegenerated;
  28921. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  28922. this._beingRegenerated = false;
  28923. }
  28924. _Primitive.prototype.canBeRegenerated = function () {
  28925. return this._canBeRegenerated;
  28926. };
  28927. _Primitive.prototype.regenerate = function () {
  28928. if (!this._canBeRegenerated) {
  28929. return;
  28930. }
  28931. this._beingRegenerated = true;
  28932. this.setAllVerticesData(this._regenerateVertexData(), false);
  28933. this._beingRegenerated = false;
  28934. };
  28935. _Primitive.prototype.asNewGeometry = function (id) {
  28936. return _super.prototype.copy.call(this, id);
  28937. };
  28938. // overrides
  28939. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28940. if (!this._beingRegenerated) {
  28941. return;
  28942. }
  28943. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28944. };
  28945. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28946. if (!this._beingRegenerated) {
  28947. return;
  28948. }
  28949. _super.prototype.setVerticesData.call(this, kind, data, false);
  28950. };
  28951. // to override
  28952. // protected
  28953. _Primitive.prototype._regenerateVertexData = function () {
  28954. throw new Error("Abstract method");
  28955. };
  28956. _Primitive.prototype.copy = function (id) {
  28957. throw new Error("Must be overriden in sub-classes.");
  28958. };
  28959. return _Primitive;
  28960. })(Geometry);
  28961. Primitives._Primitive = _Primitive;
  28962. var Ribbon = (function (_super) {
  28963. __extends(Ribbon, _super);
  28964. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28965. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28966. this.pathArray = pathArray;
  28967. this.closeArray = closeArray;
  28968. this.closePath = closePath;
  28969. this.offset = offset;
  28970. this.side = side;
  28971. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28972. }
  28973. Ribbon.prototype._regenerateVertexData = function () {
  28974. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  28975. };
  28976. Ribbon.prototype.copy = function (id) {
  28977. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28978. };
  28979. return Ribbon;
  28980. })(_Primitive);
  28981. Primitives.Ribbon = Ribbon;
  28982. var Box = (function (_super) {
  28983. __extends(Box, _super);
  28984. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28985. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28986. this.size = size;
  28987. this.side = side;
  28988. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28989. }
  28990. Box.prototype._regenerateVertexData = function () {
  28991. return BABYLON.VertexData.CreateBox(this.size, this.side);
  28992. };
  28993. Box.prototype.copy = function (id) {
  28994. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28995. };
  28996. return Box;
  28997. })(_Primitive);
  28998. Primitives.Box = Box;
  28999. var Sphere = (function (_super) {
  29000. __extends(Sphere, _super);
  29001. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29002. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29003. this.segments = segments;
  29004. this.diameter = diameter;
  29005. this.side = side;
  29006. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29007. }
  29008. Sphere.prototype._regenerateVertexData = function () {
  29009. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  29010. };
  29011. Sphere.prototype.copy = function (id) {
  29012. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29013. };
  29014. return Sphere;
  29015. })(_Primitive);
  29016. Primitives.Sphere = Sphere;
  29017. var Cylinder = (function (_super) {
  29018. __extends(Cylinder, _super);
  29019. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29020. if (subdivisions === void 0) { subdivisions = 1; }
  29021. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29022. this.height = height;
  29023. this.diameterTop = diameterTop;
  29024. this.diameterBottom = diameterBottom;
  29025. this.tessellation = tessellation;
  29026. this.subdivisions = subdivisions;
  29027. this.side = side;
  29028. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29029. }
  29030. Cylinder.prototype._regenerateVertexData = function () {
  29031. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  29032. };
  29033. Cylinder.prototype.copy = function (id) {
  29034. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29035. };
  29036. return Cylinder;
  29037. })(_Primitive);
  29038. Primitives.Cylinder = Cylinder;
  29039. var Torus = (function (_super) {
  29040. __extends(Torus, _super);
  29041. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29042. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29043. this.diameter = diameter;
  29044. this.thickness = thickness;
  29045. this.tessellation = tessellation;
  29046. this.side = side;
  29047. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29048. }
  29049. Torus.prototype._regenerateVertexData = function () {
  29050. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  29051. };
  29052. Torus.prototype.copy = function (id) {
  29053. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29054. };
  29055. return Torus;
  29056. })(_Primitive);
  29057. Primitives.Torus = Torus;
  29058. var Ground = (function (_super) {
  29059. __extends(Ground, _super);
  29060. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29061. this.width = width;
  29062. this.height = height;
  29063. this.subdivisions = subdivisions;
  29064. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29065. }
  29066. Ground.prototype._regenerateVertexData = function () {
  29067. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  29068. };
  29069. Ground.prototype.copy = function (id) {
  29070. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29071. };
  29072. return Ground;
  29073. })(_Primitive);
  29074. Primitives.Ground = Ground;
  29075. var TiledGround = (function (_super) {
  29076. __extends(TiledGround, _super);
  29077. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29078. this.xmin = xmin;
  29079. this.zmin = zmin;
  29080. this.xmax = xmax;
  29081. this.zmax = zmax;
  29082. this.subdivisions = subdivisions;
  29083. this.precision = precision;
  29084. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29085. }
  29086. TiledGround.prototype._regenerateVertexData = function () {
  29087. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  29088. };
  29089. TiledGround.prototype.copy = function (id) {
  29090. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29091. };
  29092. return TiledGround;
  29093. })(_Primitive);
  29094. Primitives.TiledGround = TiledGround;
  29095. var Plane = (function (_super) {
  29096. __extends(Plane, _super);
  29097. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29098. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29099. this.size = size;
  29100. this.side = side;
  29101. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29102. }
  29103. Plane.prototype._regenerateVertexData = function () {
  29104. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  29105. };
  29106. Plane.prototype.copy = function (id) {
  29107. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29108. };
  29109. return Plane;
  29110. })(_Primitive);
  29111. Primitives.Plane = Plane;
  29112. var TorusKnot = (function (_super) {
  29113. __extends(TorusKnot, _super);
  29114. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29115. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29116. this.radius = radius;
  29117. this.tube = tube;
  29118. this.radialSegments = radialSegments;
  29119. this.tubularSegments = tubularSegments;
  29120. this.p = p;
  29121. this.q = q;
  29122. this.side = side;
  29123. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29124. }
  29125. TorusKnot.prototype._regenerateVertexData = function () {
  29126. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  29127. };
  29128. TorusKnot.prototype.copy = function (id) {
  29129. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29130. };
  29131. return TorusKnot;
  29132. })(_Primitive);
  29133. Primitives.TorusKnot = TorusKnot;
  29134. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29135. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29136. })(BABYLON || (BABYLON = {}));
  29137. var BABYLON;
  29138. (function (BABYLON) {
  29139. var GroundMesh = (function (_super) {
  29140. __extends(GroundMesh, _super);
  29141. function GroundMesh(name, scene) {
  29142. _super.call(this, name, scene);
  29143. this.generateOctree = false;
  29144. this._worldInverse = new BABYLON.Matrix();
  29145. }
  29146. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  29147. get: function () {
  29148. return this._subdivisions;
  29149. },
  29150. enumerable: true,
  29151. configurable: true
  29152. });
  29153. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  29154. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  29155. this._subdivisions = chunksCount;
  29156. this.subdivide(this._subdivisions);
  29157. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  29158. };
  29159. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29160. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  29161. this.getWorldMatrix().invertToRef(this._worldInverse);
  29162. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  29163. var pickInfo = this.intersects(ray);
  29164. if (pickInfo.hit) {
  29165. return pickInfo.pickedPoint.y;
  29166. }
  29167. return 0;
  29168. };
  29169. return GroundMesh;
  29170. })(BABYLON.Mesh);
  29171. BABYLON.GroundMesh = GroundMesh;
  29172. })(BABYLON || (BABYLON = {}));
  29173. var BABYLON;
  29174. (function (BABYLON) {
  29175. var LinesMesh = (function (_super) {
  29176. __extends(LinesMesh, _super);
  29177. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29178. if (parent === void 0) { parent = null; }
  29179. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29180. this.color = new BABYLON.Color3(1, 1, 1);
  29181. this.alpha = 1;
  29182. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29183. attributes: ["position"],
  29184. uniforms: ["worldViewProjection", "color"],
  29185. needAlphaBlending: true
  29186. });
  29187. }
  29188. Object.defineProperty(LinesMesh.prototype, "material", {
  29189. get: function () {
  29190. return this._colorShader;
  29191. },
  29192. enumerable: true,
  29193. configurable: true
  29194. });
  29195. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29196. get: function () {
  29197. return false;
  29198. },
  29199. enumerable: true,
  29200. configurable: true
  29201. });
  29202. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29203. get: function () {
  29204. return false;
  29205. },
  29206. enumerable: true,
  29207. configurable: true
  29208. });
  29209. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29210. var engine = this.getScene().getEngine();
  29211. var indexToBind = this._geometry.getIndexBuffer();
  29212. // VBOs
  29213. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29214. // Color
  29215. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29216. };
  29217. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29218. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29219. return;
  29220. }
  29221. var engine = this.getScene().getEngine();
  29222. // Draw order
  29223. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29224. };
  29225. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29226. return null;
  29227. };
  29228. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29229. this._colorShader.dispose();
  29230. _super.prototype.dispose.call(this, doNotRecurse);
  29231. };
  29232. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29233. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29234. };
  29235. return LinesMesh;
  29236. })(BABYLON.Mesh);
  29237. BABYLON.LinesMesh = LinesMesh;
  29238. })(BABYLON || (BABYLON = {}));
  29239. var BABYLON;
  29240. (function (BABYLON) {
  29241. var OutlineRenderer = (function () {
  29242. function OutlineRenderer(scene) {
  29243. this._scene = scene;
  29244. }
  29245. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  29246. var _this = this;
  29247. if (useOverlay === void 0) { useOverlay = false; }
  29248. var scene = this._scene;
  29249. var engine = this._scene.getEngine();
  29250. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29251. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29252. return;
  29253. }
  29254. var mesh = subMesh.getRenderingMesh();
  29255. var material = subMesh.getMaterial();
  29256. engine.enableEffect(this._effect);
  29257. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29258. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29259. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29260. // Bones
  29261. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29262. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29263. }
  29264. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29265. // Alpha test
  29266. if (material && material.needAlphaTesting()) {
  29267. var alphaTexture = material.getAlphaTestTexture();
  29268. this._effect.setTexture("diffuseSampler", alphaTexture);
  29269. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29270. }
  29271. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29272. };
  29273. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29274. var defines = [];
  29275. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29276. var mesh = subMesh.getMesh();
  29277. var material = subMesh.getMaterial();
  29278. // Alpha test
  29279. if (material && material.needAlphaTesting()) {
  29280. defines.push("#define ALPHATEST");
  29281. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29282. attribs.push(BABYLON.VertexBuffer.UVKind);
  29283. defines.push("#define UV1");
  29284. }
  29285. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29286. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29287. defines.push("#define UV2");
  29288. }
  29289. }
  29290. // Bones
  29291. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29292. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29293. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29294. defines.push("#define BONES");
  29295. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29296. }
  29297. // Instances
  29298. if (useInstances) {
  29299. defines.push("#define INSTANCES");
  29300. attribs.push("world0");
  29301. attribs.push("world1");
  29302. attribs.push("world2");
  29303. attribs.push("world3");
  29304. }
  29305. // Get correct effect
  29306. var join = defines.join("\n");
  29307. if (this._cachedDefines !== join) {
  29308. this._cachedDefines = join;
  29309. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29310. }
  29311. return this._effect.isReady();
  29312. };
  29313. return OutlineRenderer;
  29314. })();
  29315. BABYLON.OutlineRenderer = OutlineRenderer;
  29316. })(BABYLON || (BABYLON = {}));
  29317. var BABYLON;
  29318. (function (BABYLON) {
  29319. var MeshAssetTask = (function () {
  29320. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29321. this.name = name;
  29322. this.meshesNames = meshesNames;
  29323. this.rootUrl = rootUrl;
  29324. this.sceneFilename = sceneFilename;
  29325. this.isCompleted = false;
  29326. }
  29327. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29328. var _this = this;
  29329. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29330. _this.loadedMeshes = meshes;
  29331. _this.loadedParticleSystems = particleSystems;
  29332. _this.loadedSkeletons = skeletons;
  29333. _this.isCompleted = true;
  29334. if (_this.onSuccess) {
  29335. _this.onSuccess(_this);
  29336. }
  29337. onSuccess();
  29338. }, null, function () {
  29339. if (_this.onError) {
  29340. _this.onError(_this);
  29341. }
  29342. onError();
  29343. });
  29344. };
  29345. return MeshAssetTask;
  29346. })();
  29347. BABYLON.MeshAssetTask = MeshAssetTask;
  29348. var TextFileAssetTask = (function () {
  29349. function TextFileAssetTask(name, url) {
  29350. this.name = name;
  29351. this.url = url;
  29352. this.isCompleted = false;
  29353. }
  29354. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29355. var _this = this;
  29356. BABYLON.Tools.LoadFile(this.url, function (data) {
  29357. _this.text = data;
  29358. _this.isCompleted = true;
  29359. if (_this.onSuccess) {
  29360. _this.onSuccess(_this);
  29361. }
  29362. onSuccess();
  29363. }, null, scene.database, false, function () {
  29364. if (_this.onError) {
  29365. _this.onError(_this);
  29366. }
  29367. onError();
  29368. });
  29369. };
  29370. return TextFileAssetTask;
  29371. })();
  29372. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29373. var BinaryFileAssetTask = (function () {
  29374. function BinaryFileAssetTask(name, url) {
  29375. this.name = name;
  29376. this.url = url;
  29377. this.isCompleted = false;
  29378. }
  29379. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29380. var _this = this;
  29381. BABYLON.Tools.LoadFile(this.url, function (data) {
  29382. _this.data = data;
  29383. _this.isCompleted = true;
  29384. if (_this.onSuccess) {
  29385. _this.onSuccess(_this);
  29386. }
  29387. onSuccess();
  29388. }, null, scene.database, true, function () {
  29389. if (_this.onError) {
  29390. _this.onError(_this);
  29391. }
  29392. onError();
  29393. });
  29394. };
  29395. return BinaryFileAssetTask;
  29396. })();
  29397. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29398. var ImageAssetTask = (function () {
  29399. function ImageAssetTask(name, url) {
  29400. this.name = name;
  29401. this.url = url;
  29402. this.isCompleted = false;
  29403. }
  29404. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29405. var _this = this;
  29406. var img = new Image();
  29407. img.onload = function () {
  29408. _this.image = img;
  29409. _this.isCompleted = true;
  29410. if (_this.onSuccess) {
  29411. _this.onSuccess(_this);
  29412. }
  29413. onSuccess();
  29414. };
  29415. img.onerror = function () {
  29416. if (_this.onError) {
  29417. _this.onError(_this);
  29418. }
  29419. onError();
  29420. };
  29421. img.src = this.url;
  29422. };
  29423. return ImageAssetTask;
  29424. })();
  29425. BABYLON.ImageAssetTask = ImageAssetTask;
  29426. var TextureAssetTask = (function () {
  29427. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29428. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29429. this.name = name;
  29430. this.url = url;
  29431. this.noMipmap = noMipmap;
  29432. this.invertY = invertY;
  29433. this.samplingMode = samplingMode;
  29434. this.isCompleted = false;
  29435. }
  29436. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29437. var _this = this;
  29438. var onload = function () {
  29439. _this.isCompleted = true;
  29440. if (_this.onSuccess) {
  29441. _this.onSuccess(_this);
  29442. }
  29443. onSuccess();
  29444. };
  29445. var onerror = function () {
  29446. if (_this.onError) {
  29447. _this.onError(_this);
  29448. }
  29449. onError();
  29450. };
  29451. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29452. };
  29453. return TextureAssetTask;
  29454. })();
  29455. BABYLON.TextureAssetTask = TextureAssetTask;
  29456. var AssetsManager = (function () {
  29457. function AssetsManager(scene) {
  29458. this._tasks = new Array();
  29459. this._waitingTasksCount = 0;
  29460. this.useDefaultLoadingScreen = true;
  29461. this._scene = scene;
  29462. }
  29463. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29464. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29465. this._tasks.push(task);
  29466. return task;
  29467. };
  29468. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29469. var task = new TextFileAssetTask(taskName, url);
  29470. this._tasks.push(task);
  29471. return task;
  29472. };
  29473. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29474. var task = new BinaryFileAssetTask(taskName, url);
  29475. this._tasks.push(task);
  29476. return task;
  29477. };
  29478. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29479. var task = new ImageAssetTask(taskName, url);
  29480. this._tasks.push(task);
  29481. return task;
  29482. };
  29483. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29484. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29485. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29486. this._tasks.push(task);
  29487. return task;
  29488. };
  29489. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29490. this._waitingTasksCount--;
  29491. if (this._waitingTasksCount === 0) {
  29492. if (this.onFinish) {
  29493. this.onFinish(this._tasks);
  29494. }
  29495. this._scene.getEngine().hideLoadingUI();
  29496. }
  29497. };
  29498. AssetsManager.prototype._runTask = function (task) {
  29499. var _this = this;
  29500. task.run(this._scene, function () {
  29501. if (_this.onTaskSuccess) {
  29502. _this.onTaskSuccess(task);
  29503. }
  29504. _this._decreaseWaitingTasksCount();
  29505. }, function () {
  29506. if (_this.onTaskError) {
  29507. _this.onTaskError(task);
  29508. }
  29509. _this._decreaseWaitingTasksCount();
  29510. });
  29511. };
  29512. AssetsManager.prototype.reset = function () {
  29513. this._tasks = new Array();
  29514. return this;
  29515. };
  29516. AssetsManager.prototype.load = function () {
  29517. this._waitingTasksCount = this._tasks.length;
  29518. if (this._waitingTasksCount === 0) {
  29519. if (this.onFinish) {
  29520. this.onFinish(this._tasks);
  29521. }
  29522. return this;
  29523. }
  29524. if (this.useDefaultLoadingScreen) {
  29525. this._scene.getEngine().displayLoadingUI();
  29526. }
  29527. for (var index = 0; index < this._tasks.length; index++) {
  29528. var task = this._tasks[index];
  29529. this._runTask(task);
  29530. }
  29531. return this;
  29532. };
  29533. return AssetsManager;
  29534. })();
  29535. BABYLON.AssetsManager = AssetsManager;
  29536. })(BABYLON || (BABYLON = {}));
  29537. var BABYLON;
  29538. (function (BABYLON) {
  29539. var VRDeviceOrientationFreeCamera = (function (_super) {
  29540. __extends(VRDeviceOrientationFreeCamera, _super);
  29541. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  29542. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29543. _super.call(this, name, position, scene);
  29544. this._alpha = 0;
  29545. this._beta = 0;
  29546. this._gamma = 0;
  29547. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29548. metrics.compensateDistorsion = compensateDistorsion;
  29549. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29550. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  29551. }
  29552. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  29553. this._alpha = +evt.alpha | 0;
  29554. this._beta = +evt.beta | 0;
  29555. this._gamma = +evt.gamma | 0;
  29556. if (this._gamma < 0) {
  29557. this._gamma = 90 + this._gamma;
  29558. }
  29559. else {
  29560. // Incline it in the correct angle.
  29561. this._gamma = 270 - this._gamma;
  29562. }
  29563. this.rotation.x = this._gamma / 180.0 * Math.PI;
  29564. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  29565. this.rotation.z = this._beta / 180.0 * Math.PI;
  29566. };
  29567. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29568. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29569. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  29570. };
  29571. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  29572. _super.prototype.detachControl.call(this, element);
  29573. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  29574. };
  29575. return VRDeviceOrientationFreeCamera;
  29576. })(BABYLON.FreeCamera);
  29577. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  29578. })(BABYLON || (BABYLON = {}));
  29579. var BABYLON;
  29580. (function (BABYLON) {
  29581. var WebVRFreeCamera = (function (_super) {
  29582. __extends(WebVRFreeCamera, _super);
  29583. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  29584. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29585. _super.call(this, name, position, scene);
  29586. this._hmdDevice = null;
  29587. this._sensorDevice = null;
  29588. this._cacheState = null;
  29589. this._cacheQuaternion = new BABYLON.Quaternion();
  29590. this._cacheRotation = BABYLON.Vector3.Zero();
  29591. this._vrEnabled = false;
  29592. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29593. metrics.compensateDistorsion = compensateDistorsion;
  29594. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29595. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  29596. }
  29597. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  29598. var size = devices.length;
  29599. var i = 0;
  29600. // Reset devices.
  29601. this._sensorDevice = null;
  29602. this._hmdDevice = null;
  29603. // Search for a HmdDevice.
  29604. while (i < size && this._hmdDevice === null) {
  29605. if (devices[i] instanceof HMDVRDevice) {
  29606. this._hmdDevice = devices[i];
  29607. }
  29608. i++;
  29609. }
  29610. i = 0;
  29611. while (i < size && this._sensorDevice === null) {
  29612. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  29613. this._sensorDevice = devices[i];
  29614. }
  29615. i++;
  29616. }
  29617. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  29618. };
  29619. WebVRFreeCamera.prototype._checkInputs = function () {
  29620. if (this._vrEnabled) {
  29621. this._cacheState = this._sensorDevice.getState();
  29622. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  29623. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  29624. this.rotation.x = -this._cacheRotation.z;
  29625. this.rotation.y = -this._cacheRotation.y;
  29626. this.rotation.z = this._cacheRotation.x;
  29627. }
  29628. _super.prototype._checkInputs.call(this);
  29629. };
  29630. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29631. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29632. if (navigator.getVRDevices) {
  29633. navigator.getVRDevices().then(this._getWebVRDevices);
  29634. }
  29635. else if (navigator.mozGetVRDevices) {
  29636. navigator.mozGetVRDevices(this._getWebVRDevices);
  29637. }
  29638. };
  29639. WebVRFreeCamera.prototype.detachControl = function (element) {
  29640. _super.prototype.detachControl.call(this, element);
  29641. this._vrEnabled = false;
  29642. };
  29643. return WebVRFreeCamera;
  29644. })(BABYLON.FreeCamera);
  29645. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  29646. })(BABYLON || (BABYLON = {}));
  29647. var BABYLON;
  29648. (function (BABYLON) {
  29649. // Standard optimizations
  29650. var SceneOptimization = (function () {
  29651. function SceneOptimization(priority) {
  29652. if (priority === void 0) { priority = 0; }
  29653. this.priority = priority;
  29654. this.apply = function (scene) {
  29655. return true; // Return true if everything that can be done was applied
  29656. };
  29657. }
  29658. return SceneOptimization;
  29659. })();
  29660. BABYLON.SceneOptimization = SceneOptimization;
  29661. var TextureOptimization = (function (_super) {
  29662. __extends(TextureOptimization, _super);
  29663. function TextureOptimization(priority, maximumSize) {
  29664. var _this = this;
  29665. if (priority === void 0) { priority = 0; }
  29666. if (maximumSize === void 0) { maximumSize = 1024; }
  29667. _super.call(this, priority);
  29668. this.priority = priority;
  29669. this.maximumSize = maximumSize;
  29670. this.apply = function (scene) {
  29671. var allDone = true;
  29672. for (var index = 0; index < scene.textures.length; index++) {
  29673. var texture = scene.textures[index];
  29674. if (!texture.canRescale) {
  29675. continue;
  29676. }
  29677. var currentSize = texture.getSize();
  29678. var maxDimension = Math.max(currentSize.width, currentSize.height);
  29679. if (maxDimension > _this.maximumSize) {
  29680. texture.scale(0.5);
  29681. allDone = false;
  29682. }
  29683. }
  29684. return allDone;
  29685. };
  29686. }
  29687. return TextureOptimization;
  29688. })(SceneOptimization);
  29689. BABYLON.TextureOptimization = TextureOptimization;
  29690. var HardwareScalingOptimization = (function (_super) {
  29691. __extends(HardwareScalingOptimization, _super);
  29692. function HardwareScalingOptimization(priority, maximumScale) {
  29693. var _this = this;
  29694. if (priority === void 0) { priority = 0; }
  29695. if (maximumScale === void 0) { maximumScale = 2; }
  29696. _super.call(this, priority);
  29697. this.priority = priority;
  29698. this.maximumScale = maximumScale;
  29699. this._currentScale = 1;
  29700. this.apply = function (scene) {
  29701. _this._currentScale++;
  29702. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  29703. return _this._currentScale >= _this.maximumScale;
  29704. };
  29705. }
  29706. return HardwareScalingOptimization;
  29707. })(SceneOptimization);
  29708. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  29709. var ShadowsOptimization = (function (_super) {
  29710. __extends(ShadowsOptimization, _super);
  29711. function ShadowsOptimization() {
  29712. _super.apply(this, arguments);
  29713. this.apply = function (scene) {
  29714. scene.shadowsEnabled = false;
  29715. return true;
  29716. };
  29717. }
  29718. return ShadowsOptimization;
  29719. })(SceneOptimization);
  29720. BABYLON.ShadowsOptimization = ShadowsOptimization;
  29721. var PostProcessesOptimization = (function (_super) {
  29722. __extends(PostProcessesOptimization, _super);
  29723. function PostProcessesOptimization() {
  29724. _super.apply(this, arguments);
  29725. this.apply = function (scene) {
  29726. scene.postProcessesEnabled = false;
  29727. return true;
  29728. };
  29729. }
  29730. return PostProcessesOptimization;
  29731. })(SceneOptimization);
  29732. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  29733. var LensFlaresOptimization = (function (_super) {
  29734. __extends(LensFlaresOptimization, _super);
  29735. function LensFlaresOptimization() {
  29736. _super.apply(this, arguments);
  29737. this.apply = function (scene) {
  29738. scene.lensFlaresEnabled = false;
  29739. return true;
  29740. };
  29741. }
  29742. return LensFlaresOptimization;
  29743. })(SceneOptimization);
  29744. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  29745. var ParticlesOptimization = (function (_super) {
  29746. __extends(ParticlesOptimization, _super);
  29747. function ParticlesOptimization() {
  29748. _super.apply(this, arguments);
  29749. this.apply = function (scene) {
  29750. scene.particlesEnabled = false;
  29751. return true;
  29752. };
  29753. }
  29754. return ParticlesOptimization;
  29755. })(SceneOptimization);
  29756. BABYLON.ParticlesOptimization = ParticlesOptimization;
  29757. var RenderTargetsOptimization = (function (_super) {
  29758. __extends(RenderTargetsOptimization, _super);
  29759. function RenderTargetsOptimization() {
  29760. _super.apply(this, arguments);
  29761. this.apply = function (scene) {
  29762. scene.renderTargetsEnabled = false;
  29763. return true;
  29764. };
  29765. }
  29766. return RenderTargetsOptimization;
  29767. })(SceneOptimization);
  29768. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  29769. var MergeMeshesOptimization = (function (_super) {
  29770. __extends(MergeMeshesOptimization, _super);
  29771. function MergeMeshesOptimization() {
  29772. var _this = this;
  29773. _super.apply(this, arguments);
  29774. this._canBeMerged = function (abstractMesh) {
  29775. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  29776. return false;
  29777. }
  29778. var mesh = abstractMesh;
  29779. if (!mesh.isVisible || !mesh.isEnabled()) {
  29780. return false;
  29781. }
  29782. if (mesh.instances.length > 0) {
  29783. return false;
  29784. }
  29785. if (mesh.skeleton || mesh.hasLODLevels) {
  29786. return false;
  29787. }
  29788. return true;
  29789. };
  29790. this.apply = function (scene, updateSelectionTree) {
  29791. var globalPool = scene.meshes.slice(0);
  29792. var globalLength = globalPool.length;
  29793. for (var index = 0; index < globalLength; index++) {
  29794. var currentPool = new Array();
  29795. var current = globalPool[index];
  29796. // Checks
  29797. if (!_this._canBeMerged(current)) {
  29798. continue;
  29799. }
  29800. currentPool.push(current);
  29801. // Find compatible meshes
  29802. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  29803. var otherMesh = globalPool[subIndex];
  29804. if (!_this._canBeMerged(otherMesh)) {
  29805. continue;
  29806. }
  29807. if (otherMesh.material !== current.material) {
  29808. continue;
  29809. }
  29810. if (otherMesh.checkCollisions !== current.checkCollisions) {
  29811. continue;
  29812. }
  29813. currentPool.push(otherMesh);
  29814. globalLength--;
  29815. globalPool.splice(subIndex, 1);
  29816. subIndex--;
  29817. }
  29818. if (currentPool.length < 2) {
  29819. continue;
  29820. }
  29821. // Merge meshes
  29822. BABYLON.Mesh.MergeMeshes(currentPool);
  29823. }
  29824. if (updateSelectionTree != undefined) {
  29825. if (updateSelectionTree) {
  29826. scene.createOrUpdateSelectionOctree();
  29827. }
  29828. }
  29829. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  29830. scene.createOrUpdateSelectionOctree();
  29831. }
  29832. return true;
  29833. };
  29834. }
  29835. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  29836. get: function () {
  29837. return MergeMeshesOptimization._UpdateSelectionTree;
  29838. },
  29839. set: function (value) {
  29840. MergeMeshesOptimization._UpdateSelectionTree = value;
  29841. },
  29842. enumerable: true,
  29843. configurable: true
  29844. });
  29845. MergeMeshesOptimization._UpdateSelectionTree = false;
  29846. return MergeMeshesOptimization;
  29847. })(SceneOptimization);
  29848. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  29849. // Options
  29850. var SceneOptimizerOptions = (function () {
  29851. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  29852. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  29853. if (trackerDuration === void 0) { trackerDuration = 2000; }
  29854. this.targetFrameRate = targetFrameRate;
  29855. this.trackerDuration = trackerDuration;
  29856. this.optimizations = new Array();
  29857. }
  29858. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  29859. var result = new SceneOptimizerOptions(targetFrameRate);
  29860. var priority = 0;
  29861. result.optimizations.push(new MergeMeshesOptimization(priority));
  29862. result.optimizations.push(new ShadowsOptimization(priority));
  29863. result.optimizations.push(new LensFlaresOptimization(priority));
  29864. // Next priority
  29865. priority++;
  29866. result.optimizations.push(new PostProcessesOptimization(priority));
  29867. result.optimizations.push(new ParticlesOptimization(priority));
  29868. // Next priority
  29869. priority++;
  29870. result.optimizations.push(new TextureOptimization(priority, 1024));
  29871. return result;
  29872. };
  29873. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  29874. var result = new SceneOptimizerOptions(targetFrameRate);
  29875. var priority = 0;
  29876. result.optimizations.push(new MergeMeshesOptimization(priority));
  29877. result.optimizations.push(new ShadowsOptimization(priority));
  29878. result.optimizations.push(new LensFlaresOptimization(priority));
  29879. // Next priority
  29880. priority++;
  29881. result.optimizations.push(new PostProcessesOptimization(priority));
  29882. result.optimizations.push(new ParticlesOptimization(priority));
  29883. // Next priority
  29884. priority++;
  29885. result.optimizations.push(new TextureOptimization(priority, 512));
  29886. // Next priority
  29887. priority++;
  29888. result.optimizations.push(new RenderTargetsOptimization(priority));
  29889. // Next priority
  29890. priority++;
  29891. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  29892. return result;
  29893. };
  29894. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  29895. var result = new SceneOptimizerOptions(targetFrameRate);
  29896. var priority = 0;
  29897. result.optimizations.push(new MergeMeshesOptimization(priority));
  29898. result.optimizations.push(new ShadowsOptimization(priority));
  29899. result.optimizations.push(new LensFlaresOptimization(priority));
  29900. // Next priority
  29901. priority++;
  29902. result.optimizations.push(new PostProcessesOptimization(priority));
  29903. result.optimizations.push(new ParticlesOptimization(priority));
  29904. // Next priority
  29905. priority++;
  29906. result.optimizations.push(new TextureOptimization(priority, 256));
  29907. // Next priority
  29908. priority++;
  29909. result.optimizations.push(new RenderTargetsOptimization(priority));
  29910. // Next priority
  29911. priority++;
  29912. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  29913. return result;
  29914. };
  29915. return SceneOptimizerOptions;
  29916. })();
  29917. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  29918. // Scene optimizer tool
  29919. var SceneOptimizer = (function () {
  29920. function SceneOptimizer() {
  29921. }
  29922. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  29923. // TODO: add an epsilon
  29924. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  29925. if (onSuccess) {
  29926. onSuccess();
  29927. }
  29928. return;
  29929. }
  29930. // Apply current level of optimizations
  29931. var allDone = true;
  29932. var noOptimizationApplied = true;
  29933. for (var index = 0; index < options.optimizations.length; index++) {
  29934. var optimization = options.optimizations[index];
  29935. if (optimization.priority === currentPriorityLevel) {
  29936. noOptimizationApplied = false;
  29937. allDone = allDone && optimization.apply(scene);
  29938. }
  29939. }
  29940. // If no optimization was applied, this is a failure :(
  29941. if (noOptimizationApplied) {
  29942. if (onFailure) {
  29943. onFailure();
  29944. }
  29945. return;
  29946. }
  29947. // If all optimizations were done, move to next level
  29948. if (allDone) {
  29949. currentPriorityLevel++;
  29950. }
  29951. // Let's the system running for a specific amount of time before checking FPS
  29952. scene.executeWhenReady(function () {
  29953. setTimeout(function () {
  29954. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  29955. }, options.trackerDuration);
  29956. });
  29957. };
  29958. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  29959. if (!options) {
  29960. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  29961. }
  29962. // Let's the system running for a specific amount of time before checking FPS
  29963. scene.executeWhenReady(function () {
  29964. setTimeout(function () {
  29965. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  29966. }, options.trackerDuration);
  29967. });
  29968. };
  29969. return SceneOptimizer;
  29970. })();
  29971. BABYLON.SceneOptimizer = SceneOptimizer;
  29972. })(BABYLON || (BABYLON = {}));
  29973. var BABYLON;
  29974. (function (BABYLON) {
  29975. var Internals;
  29976. (function (Internals) {
  29977. var MeshLODLevel = (function () {
  29978. function MeshLODLevel(distance, mesh) {
  29979. this.distance = distance;
  29980. this.mesh = mesh;
  29981. }
  29982. return MeshLODLevel;
  29983. })();
  29984. Internals.MeshLODLevel = MeshLODLevel;
  29985. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29986. })(BABYLON || (BABYLON = {}));
  29987. var BABYLON;
  29988. (function (BABYLON) {
  29989. var AudioEngine = (function () {
  29990. function AudioEngine() {
  29991. this._audioContext = null;
  29992. this._audioContextInitialized = false;
  29993. this.canUseWebAudio = false;
  29994. this.WarnedWebAudioUnsupported = false;
  29995. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  29996. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  29997. this.canUseWebAudio = true;
  29998. }
  29999. }
  30000. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  30001. get: function () {
  30002. if (!this._audioContextInitialized) {
  30003. this._initializeAudioContext();
  30004. }
  30005. return this._audioContext;
  30006. },
  30007. enumerable: true,
  30008. configurable: true
  30009. });
  30010. AudioEngine.prototype._initializeAudioContext = function () {
  30011. try {
  30012. if (this.canUseWebAudio) {
  30013. this._audioContext = new AudioContext();
  30014. // create a global volume gain node
  30015. this.masterGain = this._audioContext.createGain();
  30016. this.masterGain.gain.value = 1;
  30017. this.masterGain.connect(this._audioContext.destination);
  30018. this._audioContextInitialized = true;
  30019. }
  30020. }
  30021. catch (e) {
  30022. this.canUseWebAudio = false;
  30023. BABYLON.Tools.Error("Web Audio: " + e.message);
  30024. }
  30025. };
  30026. AudioEngine.prototype.dispose = function () {
  30027. if (this.canUseWebAudio && this._audioContextInitialized) {
  30028. if (this._connectedAnalyser) {
  30029. this._connectedAnalyser.stopDebugCanvas();
  30030. this._connectedAnalyser.dispose();
  30031. this.masterGain.disconnect();
  30032. this.masterGain.connect(this._audioContext.destination);
  30033. this._connectedAnalyser = null;
  30034. }
  30035. this.masterGain.gain.value = 1;
  30036. }
  30037. this.WarnedWebAudioUnsupported = false;
  30038. };
  30039. AudioEngine.prototype.getGlobalVolume = function () {
  30040. if (this.canUseWebAudio && this._audioContextInitialized) {
  30041. return this.masterGain.gain.value;
  30042. }
  30043. else {
  30044. return -1;
  30045. }
  30046. };
  30047. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  30048. if (this.canUseWebAudio && this._audioContextInitialized) {
  30049. this.masterGain.gain.value = newVolume;
  30050. }
  30051. };
  30052. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  30053. if (this._connectedAnalyser) {
  30054. this._connectedAnalyser.stopDebugCanvas();
  30055. }
  30056. if (this.canUseWebAudio && this._audioContextInitialized) {
  30057. this._connectedAnalyser = analyser;
  30058. this.masterGain.disconnect();
  30059. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  30060. }
  30061. };
  30062. return AudioEngine;
  30063. })();
  30064. BABYLON.AudioEngine = AudioEngine;
  30065. })(BABYLON || (BABYLON = {}));
  30066. var BABYLON;
  30067. (function (BABYLON) {
  30068. var Sound = (function () {
  30069. /**
  30070. * Create a sound and attach it to a scene
  30071. * @param name Name of your sound
  30072. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  30073. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  30074. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  30075. */
  30076. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  30077. var _this = this;
  30078. this.autoplay = false;
  30079. this.loop = false;
  30080. this.useCustomAttenuation = false;
  30081. this.spatialSound = false;
  30082. this.refDistance = 1;
  30083. this.rolloffFactor = 1;
  30084. this.maxDistance = 100;
  30085. this.distanceModel = "linear";
  30086. this._panningModel = "equalpower";
  30087. this._playbackRate = 1;
  30088. this._startTime = 0;
  30089. this._startOffset = 0;
  30090. this._position = BABYLON.Vector3.Zero();
  30091. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  30092. this._volume = 1;
  30093. this._isLoaded = false;
  30094. this._isReadyToPlay = false;
  30095. this.isPlaying = false;
  30096. this.isPaused = false;
  30097. this._isDirectional = false;
  30098. // Used if you'd like to create a directional sound.
  30099. // If not set, the sound will be omnidirectional
  30100. this._coneInnerAngle = 360;
  30101. this._coneOuterAngle = 360;
  30102. this._coneOuterGain = 0;
  30103. this.name = name;
  30104. this._scene = scene;
  30105. this._readyToPlayCallback = readyToPlayCallback;
  30106. // Default custom attenuation function is a linear attenuation
  30107. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  30108. if (currentDistance < maxDistance) {
  30109. return currentVolume * (1 - currentDistance / maxDistance);
  30110. }
  30111. else {
  30112. return 0;
  30113. }
  30114. };
  30115. if (options) {
  30116. this.autoplay = options.autoplay || false;
  30117. this.loop = options.loop || false;
  30118. // if volume === 0, we need another way to check this option
  30119. if (options.volume !== undefined) {
  30120. this._volume = options.volume;
  30121. }
  30122. this.spatialSound = options.spatialSound || false;
  30123. this.maxDistance = options.maxDistance || 100;
  30124. this.useCustomAttenuation = options.useCustomAttenuation || false;
  30125. this.rolloffFactor = options.rolloffFactor || 1;
  30126. this.refDistance = options.refDistance || 1;
  30127. this.distanceModel = options.distanceModel || "linear";
  30128. this._playbackRate = options.playbackRate || 1;
  30129. }
  30130. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30131. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  30132. this._soundGain.gain.value = this._volume;
  30133. this._inputAudioNode = this._soundGain;
  30134. this._ouputAudioNode = this._soundGain;
  30135. if (this.spatialSound) {
  30136. this._createSpatialParameters();
  30137. }
  30138. this._scene.mainSoundTrack.AddSound(this);
  30139. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  30140. if (urlOrArrayBuffer) {
  30141. // If it's an URL
  30142. if (typeof (urlOrArrayBuffer) === "string") {
  30143. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  30144. }
  30145. else {
  30146. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  30147. this._soundLoaded(urlOrArrayBuffer);
  30148. }
  30149. else {
  30150. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  30151. }
  30152. }
  30153. }
  30154. }
  30155. else {
  30156. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  30157. this._scene.mainSoundTrack.AddSound(this);
  30158. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  30159. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  30160. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  30161. }
  30162. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  30163. if (this._readyToPlayCallback) {
  30164. window.setTimeout(function () {
  30165. _this._readyToPlayCallback();
  30166. }, 1000);
  30167. }
  30168. }
  30169. }
  30170. Sound.prototype.dispose = function () {
  30171. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30172. if (this.isPlaying) {
  30173. this.stop();
  30174. }
  30175. this._isReadyToPlay = false;
  30176. if (this.soundTrackId === -1) {
  30177. this._scene.mainSoundTrack.RemoveSound(this);
  30178. }
  30179. else {
  30180. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30181. }
  30182. if (this._soundGain) {
  30183. this._soundGain.disconnect();
  30184. this._soundGain = null;
  30185. }
  30186. if (this._soundPanner) {
  30187. this._soundPanner.disconnect();
  30188. this._soundPanner = null;
  30189. }
  30190. if (this._soundSource) {
  30191. this._soundSource.disconnect();
  30192. this._soundSource = null;
  30193. }
  30194. this._audioBuffer = null;
  30195. if (this._connectedMesh) {
  30196. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30197. this._connectedMesh = null;
  30198. }
  30199. }
  30200. };
  30201. Sound.prototype._soundLoaded = function (audioData) {
  30202. var _this = this;
  30203. this._isLoaded = true;
  30204. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30205. _this._audioBuffer = buffer;
  30206. _this._isReadyToPlay = true;
  30207. if (_this.autoplay) {
  30208. _this.play();
  30209. }
  30210. if (_this._readyToPlayCallback) {
  30211. _this._readyToPlayCallback();
  30212. }
  30213. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30214. };
  30215. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30216. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30217. this._audioBuffer = audioBuffer;
  30218. this._isReadyToPlay = true;
  30219. }
  30220. };
  30221. Sound.prototype.updateOptions = function (options) {
  30222. if (options) {
  30223. this.loop = options.loop || this.loop;
  30224. this.maxDistance = options.maxDistance || this.maxDistance;
  30225. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30226. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30227. this.refDistance = options.refDistance || this.refDistance;
  30228. this.distanceModel = options.distanceModel || this.distanceModel;
  30229. this._playbackRate = options.playbackRate || this._playbackRate;
  30230. this._updateSpatialParameters();
  30231. if (this.isPlaying) {
  30232. this._soundSource.playbackRate.value = this._playbackRate;
  30233. }
  30234. }
  30235. };
  30236. Sound.prototype._createSpatialParameters = function () {
  30237. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30238. if (this._scene.headphone) {
  30239. this._panningModel = "HRTF";
  30240. }
  30241. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30242. this._updateSpatialParameters();
  30243. this._soundPanner.connect(this._ouputAudioNode);
  30244. this._inputAudioNode = this._soundPanner;
  30245. }
  30246. };
  30247. Sound.prototype._updateSpatialParameters = function () {
  30248. if (this.spatialSound) {
  30249. if (this.useCustomAttenuation) {
  30250. // Tricks to disable in a way embedded Web Audio attenuation
  30251. this._soundPanner.distanceModel = "linear";
  30252. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30253. this._soundPanner.refDistance = 1;
  30254. this._soundPanner.rolloffFactor = 1;
  30255. this._soundPanner.panningModel = this._panningModel;
  30256. }
  30257. else {
  30258. this._soundPanner.distanceModel = this.distanceModel;
  30259. this._soundPanner.maxDistance = this.maxDistance;
  30260. this._soundPanner.refDistance = this.refDistance;
  30261. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30262. this._soundPanner.panningModel = this._panningModel;
  30263. }
  30264. }
  30265. };
  30266. Sound.prototype.switchPanningModelToHRTF = function () {
  30267. this._panningModel = "HRTF";
  30268. this._switchPanningModel();
  30269. };
  30270. Sound.prototype.switchPanningModelToEqualPower = function () {
  30271. this._panningModel = "equalpower";
  30272. this._switchPanningModel();
  30273. };
  30274. Sound.prototype._switchPanningModel = function () {
  30275. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30276. this._soundPanner.panningModel = this._panningModel;
  30277. }
  30278. };
  30279. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30280. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30281. this._ouputAudioNode.disconnect();
  30282. this._ouputAudioNode.connect(soundTrackAudioNode);
  30283. }
  30284. };
  30285. /**
  30286. * Transform this sound into a directional source
  30287. * @param coneInnerAngle Size of the inner cone in degree
  30288. * @param coneOuterAngle Size of the outer cone in degree
  30289. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30290. */
  30291. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30292. if (coneOuterAngle < coneInnerAngle) {
  30293. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30294. return;
  30295. }
  30296. this._coneInnerAngle = coneInnerAngle;
  30297. this._coneOuterAngle = coneOuterAngle;
  30298. this._coneOuterGain = coneOuterGain;
  30299. this._isDirectional = true;
  30300. if (this.isPlaying && this.loop) {
  30301. this.stop();
  30302. this.play();
  30303. }
  30304. };
  30305. Sound.prototype.setPosition = function (newPosition) {
  30306. this._position = newPosition;
  30307. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30308. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30309. }
  30310. };
  30311. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30312. this._localDirection = newLocalDirection;
  30313. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30314. this._updateDirection();
  30315. }
  30316. };
  30317. Sound.prototype._updateDirection = function () {
  30318. var mat = this._connectedMesh.getWorldMatrix();
  30319. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30320. direction.normalize();
  30321. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30322. };
  30323. Sound.prototype.updateDistanceFromListener = function () {
  30324. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30325. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30326. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30327. }
  30328. };
  30329. Sound.prototype.setAttenuationFunction = function (callback) {
  30330. this._customAttenuationFunction = callback;
  30331. };
  30332. /**
  30333. * Play the sound
  30334. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30335. */
  30336. Sound.prototype.play = function (time) {
  30337. var _this = this;
  30338. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30339. try {
  30340. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30341. if (!this._soundSource) {
  30342. if (this.spatialSound) {
  30343. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30344. if (this._isDirectional) {
  30345. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30346. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30347. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30348. if (this._connectedMesh) {
  30349. this._updateDirection();
  30350. }
  30351. else {
  30352. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30353. }
  30354. }
  30355. }
  30356. }
  30357. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30358. this._soundSource.buffer = this._audioBuffer;
  30359. this._soundSource.connect(this._inputAudioNode);
  30360. this._soundSource.loop = this.loop;
  30361. this._soundSource.playbackRate.value = this._playbackRate;
  30362. this._startTime = startTime;
  30363. this._soundSource.onended = function () { _this._onended(); };
  30364. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30365. this.isPlaying = true;
  30366. this.isPaused = false;
  30367. }
  30368. catch (ex) {
  30369. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30370. }
  30371. }
  30372. };
  30373. Sound.prototype._onended = function () {
  30374. this.isPlaying = false;
  30375. if (this.onended) {
  30376. this.onended();
  30377. }
  30378. };
  30379. /**
  30380. * Stop the sound
  30381. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30382. */
  30383. Sound.prototype.stop = function (time) {
  30384. if (this.isPlaying) {
  30385. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30386. this._soundSource.stop(stopTime);
  30387. this.isPlaying = false;
  30388. }
  30389. };
  30390. Sound.prototype.pause = function () {
  30391. if (this.isPlaying) {
  30392. this.stop(0);
  30393. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30394. this.isPaused = true;
  30395. }
  30396. };
  30397. Sound.prototype.setVolume = function (newVolume, time) {
  30398. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30399. if (time) {
  30400. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30401. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30402. }
  30403. else {
  30404. this._soundGain.gain.value = newVolume;
  30405. }
  30406. }
  30407. this._volume = newVolume;
  30408. };
  30409. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30410. this._playbackRate = newPlaybackRate;
  30411. if (this.isPlaying) {
  30412. this._soundSource.playbackRate.value = this._playbackRate;
  30413. }
  30414. };
  30415. Sound.prototype.getVolume = function () {
  30416. return this._volume;
  30417. };
  30418. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30419. var _this = this;
  30420. this._connectedMesh = meshToConnectTo;
  30421. if (!this.spatialSound) {
  30422. this.spatialSound = true;
  30423. this._createSpatialParameters();
  30424. if (this.isPlaying && this.loop) {
  30425. this.stop();
  30426. this.play();
  30427. }
  30428. }
  30429. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30430. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30431. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30432. };
  30433. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30434. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30435. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30436. this._updateDirection();
  30437. }
  30438. };
  30439. return Sound;
  30440. })();
  30441. BABYLON.Sound = Sound;
  30442. })(BABYLON || (BABYLON = {}));
  30443. var BABYLON;
  30444. (function (BABYLON) {
  30445. var SoundTrack = (function () {
  30446. function SoundTrack(scene, options) {
  30447. this.id = -1;
  30448. this._isMainTrack = false;
  30449. this._scene = scene;
  30450. this._audioEngine = BABYLON.Engine.audioEngine;
  30451. this.soundCollection = new Array();
  30452. if (this._audioEngine.canUseWebAudio) {
  30453. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30454. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30455. if (options) {
  30456. if (options.volume) {
  30457. this._outputAudioNode.gain.value = options.volume;
  30458. }
  30459. if (options.mainTrack) {
  30460. this._isMainTrack = options.mainTrack;
  30461. }
  30462. }
  30463. }
  30464. if (!this._isMainTrack) {
  30465. this._scene.soundTracks.push(this);
  30466. this.id = this._scene.soundTracks.length - 1;
  30467. }
  30468. }
  30469. SoundTrack.prototype.dispose = function () {
  30470. if (this._audioEngine.canUseWebAudio) {
  30471. if (this._connectedAnalyser) {
  30472. this._connectedAnalyser.stopDebugCanvas();
  30473. }
  30474. while (this.soundCollection.length) {
  30475. this.soundCollection[0].dispose();
  30476. }
  30477. if (this._outputAudioNode) {
  30478. this._outputAudioNode.disconnect();
  30479. }
  30480. this._outputAudioNode = null;
  30481. }
  30482. };
  30483. SoundTrack.prototype.AddSound = function (sound) {
  30484. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30485. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30486. }
  30487. if (sound.soundTrackId) {
  30488. if (sound.soundTrackId === -1) {
  30489. this._scene.mainSoundTrack.RemoveSound(sound);
  30490. }
  30491. else {
  30492. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30493. }
  30494. }
  30495. this.soundCollection.push(sound);
  30496. sound.soundTrackId = this.id;
  30497. };
  30498. SoundTrack.prototype.RemoveSound = function (sound) {
  30499. var index = this.soundCollection.indexOf(sound);
  30500. if (index !== -1) {
  30501. this.soundCollection.splice(index, 1);
  30502. }
  30503. };
  30504. SoundTrack.prototype.setVolume = function (newVolume) {
  30505. if (this._audioEngine.canUseWebAudio) {
  30506. this._outputAudioNode.gain.value = newVolume;
  30507. }
  30508. };
  30509. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30510. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30511. for (var i = 0; i < this.soundCollection.length; i++) {
  30512. this.soundCollection[i].switchPanningModelToHRTF();
  30513. }
  30514. }
  30515. };
  30516. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30517. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30518. for (var i = 0; i < this.soundCollection.length; i++) {
  30519. this.soundCollection[i].switchPanningModelToEqualPower();
  30520. }
  30521. }
  30522. };
  30523. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30524. if (this._connectedAnalyser) {
  30525. this._connectedAnalyser.stopDebugCanvas();
  30526. }
  30527. this._connectedAnalyser = analyser;
  30528. if (this._audioEngine.canUseWebAudio) {
  30529. this._outputAudioNode.disconnect();
  30530. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  30531. }
  30532. };
  30533. return SoundTrack;
  30534. })();
  30535. BABYLON.SoundTrack = SoundTrack;
  30536. })(BABYLON || (BABYLON = {}));
  30537. var BABYLON;
  30538. (function (BABYLON) {
  30539. var DebugLayer = (function () {
  30540. function DebugLayer(scene) {
  30541. var _this = this;
  30542. this._transformationMatrix = BABYLON.Matrix.Identity();
  30543. this._enabled = false;
  30544. this._labelsEnabled = false;
  30545. this._displayStatistics = true;
  30546. this._displayTree = false;
  30547. this._displayLogs = false;
  30548. this._identityMatrix = BABYLON.Matrix.Identity();
  30549. this.axisRatio = 0.02;
  30550. this.accentColor = "orange";
  30551. this._scene = scene;
  30552. this._syncPositions = function () {
  30553. var engine = _this._scene.getEngine();
  30554. var canvasRect = engine.getRenderingCanvasClientRect();
  30555. if (_this._showUI) {
  30556. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30557. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30558. _this._statsDiv.style.width = "400px";
  30559. _this._statsDiv.style.height = "auto";
  30560. _this._statsSubsetDiv.style.maxHeight = "240px";
  30561. _this._optionsDiv.style.left = "0px";
  30562. _this._optionsDiv.style.top = "10px";
  30563. _this._optionsDiv.style.width = "200px";
  30564. _this._optionsDiv.style.height = "auto";
  30565. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30566. _this._logDiv.style.left = "0px";
  30567. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30568. _this._logDiv.style.width = "600px";
  30569. _this._logDiv.style.height = "160px";
  30570. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30571. _this._treeDiv.style.top = "10px";
  30572. _this._treeDiv.style.width = "300px";
  30573. _this._treeDiv.style.height = "auto";
  30574. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30575. }
  30576. _this._globalDiv.style.left = canvasRect.left + "px";
  30577. _this._globalDiv.style.top = canvasRect.top + "px";
  30578. _this._drawingCanvas.style.left = "0px";
  30579. _this._drawingCanvas.style.top = "0px";
  30580. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30581. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30582. var devicePixelRatio = window.devicePixelRatio || 1;
  30583. var context = _this._drawingContext;
  30584. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30585. context.mozBackingStorePixelRatio ||
  30586. context.msBackingStorePixelRatio ||
  30587. context.oBackingStorePixelRatio ||
  30588. context.backingStorePixelRatio || 1;
  30589. _this._ratio = devicePixelRatio / backingStoreRatio;
  30590. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30591. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30592. };
  30593. this._onCanvasClick = function (evt) {
  30594. _this._clickPosition = {
  30595. x: evt.clientX * _this._ratio,
  30596. y: evt.clientY * _this._ratio
  30597. };
  30598. };
  30599. this._syncUI = function () {
  30600. if (_this._showUI) {
  30601. if (_this._displayStatistics) {
  30602. _this._displayStats();
  30603. _this._statsDiv.style.display = "";
  30604. }
  30605. else {
  30606. _this._statsDiv.style.display = "none";
  30607. }
  30608. if (_this._displayLogs) {
  30609. _this._logDiv.style.display = "";
  30610. }
  30611. else {
  30612. _this._logDiv.style.display = "none";
  30613. }
  30614. if (_this._displayTree) {
  30615. _this._treeDiv.style.display = "";
  30616. if (_this._needToRefreshMeshesTree) {
  30617. _this._needToRefreshMeshesTree = false;
  30618. _this._refreshMeshesTreeContent();
  30619. }
  30620. }
  30621. else {
  30622. _this._treeDiv.style.display = "none";
  30623. }
  30624. }
  30625. };
  30626. this._syncData = function () {
  30627. if (_this._labelsEnabled || !_this._showUI) {
  30628. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30629. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30630. var engine = _this._scene.getEngine();
  30631. var viewport = _this._camera.viewport;
  30632. var globalViewport = viewport.toGlobal(engine);
  30633. // Meshes
  30634. var meshes = _this._camera.getActiveMeshes();
  30635. for (var index = 0; index < meshes.length; index++) {
  30636. var mesh = meshes.data[index];
  30637. var position = mesh.getBoundingInfo().boundingSphere.center;
  30638. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30639. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30640. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30641. }
  30642. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30643. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30644. }
  30645. }
  30646. // Cameras
  30647. var cameras = _this._scene.cameras;
  30648. for (index = 0; index < cameras.length; index++) {
  30649. var camera = cameras[index];
  30650. if (camera === _this._camera) {
  30651. continue;
  30652. }
  30653. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30654. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30655. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30656. _this._camera.detachControl(engine.getRenderingCanvas());
  30657. _this._camera = camera;
  30658. _this._camera.attachControl(engine.getRenderingCanvas());
  30659. }, function () { return "purple"; });
  30660. }
  30661. }
  30662. // Lights
  30663. var lights = _this._scene.lights;
  30664. for (index = 0; index < lights.length; index++) {
  30665. var light = lights[index];
  30666. if (light.position) {
  30667. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30668. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30669. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30670. light.setEnabled(!light.isEnabled());
  30671. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30672. }
  30673. }
  30674. }
  30675. }
  30676. _this._clickPosition = undefined;
  30677. };
  30678. }
  30679. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30680. while (this._treeSubsetDiv.hasChildNodes()) {
  30681. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30682. }
  30683. // Add meshes
  30684. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30685. sortedArray.sort(function (a, b) {
  30686. if (a.name === b.name) {
  30687. return 0;
  30688. }
  30689. return (a.name > b.name) ? 1 : -1;
  30690. });
  30691. for (var index = 0; index < sortedArray.length; index++) {
  30692. var mesh = sortedArray[index];
  30693. if (!mesh.isEnabled()) {
  30694. continue;
  30695. }
  30696. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30697. m.isVisible = element.checked;
  30698. }, mesh);
  30699. }
  30700. };
  30701. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30702. this._drawingContext.beginPath();
  30703. this._drawingContext.moveTo(zero.x, zero.y);
  30704. this._drawingContext.lineTo(unit.x, unit.y);
  30705. this._drawingContext.strokeStyle = color;
  30706. this._drawingContext.lineWidth = 4;
  30707. this._drawingContext.stroke();
  30708. this._drawingContext.font = "normal 14px Segoe UI";
  30709. this._drawingContext.fillStyle = color;
  30710. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30711. };
  30712. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30713. var position = mesh.getBoundingInfo().boundingSphere.center;
  30714. var worldMatrix = mesh.getWorldMatrix();
  30715. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30716. var unit = (unprojectedVector.subtract(position)).length();
  30717. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30718. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30719. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30720. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30721. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30722. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30723. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30724. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30725. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30726. };
  30727. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30728. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30729. this._drawingContext.font = "normal 12px Segoe UI";
  30730. var textMetrics = this._drawingContext.measureText(text);
  30731. var centerX = projectedPosition.x - textMetrics.width / 2;
  30732. var centerY = projectedPosition.y;
  30733. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30734. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30735. onClick();
  30736. }
  30737. this._drawingContext.beginPath();
  30738. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30739. this._drawingContext.fillStyle = getFillStyle();
  30740. this._drawingContext.globalAlpha = 0.5;
  30741. this._drawingContext.fill();
  30742. this._drawingContext.globalAlpha = 1.0;
  30743. this._drawingContext.strokeStyle = '#FFFFFF';
  30744. this._drawingContext.lineWidth = 1;
  30745. this._drawingContext.stroke();
  30746. this._drawingContext.fillStyle = "#FFFFFF";
  30747. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30748. this._drawingContext.beginPath();
  30749. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30750. this._drawingContext.fill();
  30751. }
  30752. };
  30753. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30754. if (!this._clickPosition) {
  30755. return false;
  30756. }
  30757. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30758. return false;
  30759. }
  30760. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30761. return false;
  30762. }
  30763. return true;
  30764. };
  30765. DebugLayer.prototype.isVisible = function () {
  30766. return this._enabled;
  30767. };
  30768. DebugLayer.prototype.hide = function () {
  30769. if (!this._enabled) {
  30770. return;
  30771. }
  30772. this._enabled = false;
  30773. var engine = this._scene.getEngine();
  30774. this._scene.unregisterBeforeRender(this._syncData);
  30775. this._scene.unregisterAfterRender(this._syncUI);
  30776. document.body.removeChild(this._globalDiv);
  30777. window.removeEventListener("resize", this._syncPositions);
  30778. this._scene.forceShowBoundingBoxes = false;
  30779. this._scene.forceWireframe = false;
  30780. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30781. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30782. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30783. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30784. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30785. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30786. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30787. this._scene.shadowsEnabled = true;
  30788. this._scene.particlesEnabled = true;
  30789. this._scene.postProcessesEnabled = true;
  30790. this._scene.collisionsEnabled = true;
  30791. this._scene.lightsEnabled = true;
  30792. this._scene.texturesEnabled = true;
  30793. this._scene.lensFlaresEnabled = true;
  30794. this._scene.proceduralTexturesEnabled = true;
  30795. this._scene.renderTargetsEnabled = true;
  30796. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30797. };
  30798. DebugLayer.prototype.show = function (showUI, camera) {
  30799. if (showUI === void 0) { showUI = true; }
  30800. if (camera === void 0) { camera = null; }
  30801. if (this._enabled) {
  30802. return;
  30803. }
  30804. this._enabled = true;
  30805. if (camera) {
  30806. this._camera = camera;
  30807. }
  30808. else {
  30809. this._camera = this._scene.activeCamera;
  30810. }
  30811. this._showUI = showUI;
  30812. var engine = this._scene.getEngine();
  30813. this._globalDiv = document.createElement("div");
  30814. document.body.appendChild(this._globalDiv);
  30815. this._generateDOMelements();
  30816. window.addEventListener("resize", this._syncPositions);
  30817. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30818. this._syncPositions();
  30819. this._scene.registerBeforeRender(this._syncData);
  30820. this._scene.registerAfterRender(this._syncUI);
  30821. };
  30822. DebugLayer.prototype._clearLabels = function () {
  30823. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30824. for (var index = 0; index < this._scene.meshes.length; index++) {
  30825. var mesh = this._scene.meshes[index];
  30826. mesh.renderOverlay = false;
  30827. }
  30828. };
  30829. DebugLayer.prototype._generateheader = function (root, text) {
  30830. var header = document.createElement("div");
  30831. header.innerHTML = text + "&nbsp;";
  30832. header.style.textAlign = "right";
  30833. header.style.width = "100%";
  30834. header.style.color = "white";
  30835. header.style.backgroundColor = "Black";
  30836. header.style.padding = "5px 5px 4px 0px";
  30837. header.style.marginLeft = "-5px";
  30838. header.style.fontWeight = "bold";
  30839. root.appendChild(header);
  30840. };
  30841. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  30842. var label = document.createElement("label");
  30843. label.innerHTML = title;
  30844. label.style.color = color;
  30845. root.appendChild(label);
  30846. root.appendChild(document.createElement("br"));
  30847. };
  30848. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  30849. if (tag === void 0) { tag = null; }
  30850. var label = document.createElement("label");
  30851. var boundingBoxesCheckbox = document.createElement("input");
  30852. boundingBoxesCheckbox.type = "checkbox";
  30853. boundingBoxesCheckbox.checked = initialState;
  30854. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  30855. task(evt.target, tag);
  30856. });
  30857. label.appendChild(boundingBoxesCheckbox);
  30858. var container = document.createElement("span");
  30859. var leftPart = document.createElement("span");
  30860. var rightPart = document.createElement("span");
  30861. rightPart.style.cssFloat = "right";
  30862. leftPart.innerHTML = leftTitle;
  30863. rightPart.innerHTML = rightTitle;
  30864. rightPart.style.fontSize = "12px";
  30865. rightPart.style.maxWidth = "200px";
  30866. container.appendChild(leftPart);
  30867. container.appendChild(rightPart);
  30868. label.appendChild(container);
  30869. root.appendChild(label);
  30870. root.appendChild(document.createElement("br"));
  30871. };
  30872. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  30873. if (tag === void 0) { tag = null; }
  30874. var label = document.createElement("label");
  30875. var checkBox = document.createElement("input");
  30876. checkBox.type = "checkbox";
  30877. checkBox.checked = initialState;
  30878. checkBox.addEventListener("change", function (evt) {
  30879. task(evt.target, tag);
  30880. });
  30881. label.appendChild(checkBox);
  30882. label.appendChild(document.createTextNode(title));
  30883. root.appendChild(label);
  30884. root.appendChild(document.createElement("br"));
  30885. };
  30886. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  30887. if (tag === void 0) { tag = null; }
  30888. var button = document.createElement("button");
  30889. button.innerHTML = title;
  30890. button.style.height = "24px";
  30891. button.style.color = "#444444";
  30892. button.style.border = "1px solid white";
  30893. button.className = "debugLayerButton";
  30894. button.addEventListener("click", function (evt) {
  30895. task(evt.target, tag);
  30896. });
  30897. root.appendChild(button);
  30898. root.appendChild(document.createElement("br"));
  30899. };
  30900. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  30901. if (tag === void 0) { tag = null; }
  30902. var label = document.createElement("label");
  30903. var boundingBoxesRadio = document.createElement("input");
  30904. boundingBoxesRadio.type = "radio";
  30905. boundingBoxesRadio.name = name;
  30906. boundingBoxesRadio.checked = initialState;
  30907. boundingBoxesRadio.addEventListener("change", function (evt) {
  30908. task(evt.target, tag);
  30909. });
  30910. label.appendChild(boundingBoxesRadio);
  30911. label.appendChild(document.createTextNode(title));
  30912. root.appendChild(label);
  30913. root.appendChild(document.createElement("br"));
  30914. };
  30915. DebugLayer.prototype._generateDOMelements = function () {
  30916. var _this = this;
  30917. this._globalDiv.id = "DebugLayer";
  30918. this._globalDiv.style.position = "absolute";
  30919. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  30920. this._globalDiv.style.fontSize = "14px";
  30921. this._globalDiv.style.color = "white";
  30922. // Drawing canvas
  30923. this._drawingCanvas = document.createElement("canvas");
  30924. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  30925. this._drawingCanvas.style.position = "absolute";
  30926. this._drawingCanvas.style.pointerEvents = "none";
  30927. this._drawingContext = this._drawingCanvas.getContext("2d");
  30928. this._globalDiv.appendChild(this._drawingCanvas);
  30929. if (this._showUI) {
  30930. var background = "rgba(128, 128, 128, 0.4)";
  30931. var border = "rgb(180, 180, 180) solid 1px";
  30932. // Stats
  30933. this._statsDiv = document.createElement("div");
  30934. this._statsDiv.id = "DebugLayerStats";
  30935. this._statsDiv.style.border = border;
  30936. this._statsDiv.style.position = "absolute";
  30937. this._statsDiv.style.background = background;
  30938. this._statsDiv.style.padding = "0px 0px 0px 5px";
  30939. this._generateheader(this._statsDiv, "STATISTICS");
  30940. this._statsSubsetDiv = document.createElement("div");
  30941. this._statsSubsetDiv.style.paddingTop = "5px";
  30942. this._statsSubsetDiv.style.paddingBottom = "5px";
  30943. this._statsSubsetDiv.style.overflowY = "auto";
  30944. this._statsDiv.appendChild(this._statsSubsetDiv);
  30945. // Tree
  30946. this._treeDiv = document.createElement("div");
  30947. this._treeDiv.id = "DebugLayerTree";
  30948. this._treeDiv.style.border = border;
  30949. this._treeDiv.style.position = "absolute";
  30950. this._treeDiv.style.background = background;
  30951. this._treeDiv.style.padding = "0px 0px 0px 5px";
  30952. this._treeDiv.style.display = "none";
  30953. this._generateheader(this._treeDiv, "MESHES TREE");
  30954. this._treeSubsetDiv = document.createElement("div");
  30955. this._treeSubsetDiv.style.paddingTop = "5px";
  30956. this._treeSubsetDiv.style.paddingRight = "5px";
  30957. this._treeSubsetDiv.style.overflowY = "auto";
  30958. this._treeSubsetDiv.style.maxHeight = "300px";
  30959. this._treeDiv.appendChild(this._treeSubsetDiv);
  30960. this._needToRefreshMeshesTree = true;
  30961. // Logs
  30962. this._logDiv = document.createElement("div");
  30963. this._logDiv.style.border = border;
  30964. this._logDiv.id = "DebugLayerLogs";
  30965. this._logDiv.style.position = "absolute";
  30966. this._logDiv.style.background = background;
  30967. this._logDiv.style.padding = "0px 0px 0px 5px";
  30968. this._logDiv.style.display = "none";
  30969. this._generateheader(this._logDiv, "LOGS");
  30970. this._logSubsetDiv = document.createElement("div");
  30971. this._logSubsetDiv.style.height = "127px";
  30972. this._logSubsetDiv.style.paddingTop = "5px";
  30973. this._logSubsetDiv.style.overflowY = "auto";
  30974. this._logSubsetDiv.style.fontSize = "12px";
  30975. this._logSubsetDiv.style.fontFamily = "consolas";
  30976. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  30977. this._logDiv.appendChild(this._logSubsetDiv);
  30978. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  30979. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  30980. };
  30981. // Options
  30982. this._optionsDiv = document.createElement("div");
  30983. this._optionsDiv.id = "DebugLayerOptions";
  30984. this._optionsDiv.style.border = border;
  30985. this._optionsDiv.style.position = "absolute";
  30986. this._optionsDiv.style.background = background;
  30987. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  30988. this._optionsDiv.style.overflowY = "auto";
  30989. this._generateheader(this._optionsDiv, "OPTIONS");
  30990. this._optionsSubsetDiv = document.createElement("div");
  30991. this._optionsSubsetDiv.style.paddingTop = "5px";
  30992. this._optionsSubsetDiv.style.paddingBottom = "5px";
  30993. this._optionsSubsetDiv.style.overflowY = "auto";
  30994. this._optionsSubsetDiv.style.maxHeight = "200px";
  30995. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  30996. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  30997. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  30998. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  30999. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  31000. _this._displayTree = element.checked;
  31001. _this._needToRefreshMeshesTree = true;
  31002. });
  31003. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31004. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  31005. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  31006. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  31007. _this._labelsEnabled = element.checked;
  31008. if (!_this._labelsEnabled) {
  31009. _this._clearLabels();
  31010. }
  31011. });
  31012. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31013. if (element.checked) {
  31014. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31015. }
  31016. else {
  31017. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31018. }
  31019. });
  31020. ;
  31021. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31022. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31023. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31024. if (element.checked) {
  31025. _this._scene.forceWireframe = false;
  31026. _this._scene.forcePointsCloud = false;
  31027. }
  31028. });
  31029. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31030. if (element.checked) {
  31031. _this._scene.forceWireframe = true;
  31032. _this._scene.forcePointsCloud = false;
  31033. }
  31034. });
  31035. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31036. if (element.checked) {
  31037. _this._scene.forceWireframe = false;
  31038. _this._scene.forcePointsCloud = true;
  31039. }
  31040. });
  31041. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31042. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31043. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31044. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31045. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31046. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31047. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31048. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31049. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31050. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31051. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31052. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31053. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31054. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31055. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31056. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31057. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31058. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31059. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31060. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31061. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31062. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31063. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31064. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31065. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31066. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31067. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31068. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31069. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31070. if (element.checked) {
  31071. _this._scene.headphone = true;
  31072. }
  31073. });
  31074. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31075. if (element.checked) {
  31076. _this._scene.headphone = false;
  31077. }
  31078. });
  31079. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31080. _this._scene.audioEnabled = !element.checked;
  31081. });
  31082. }
  31083. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31084. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31085. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31086. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31087. this._globalDiv.appendChild(this._statsDiv);
  31088. this._globalDiv.appendChild(this._logDiv);
  31089. this._globalDiv.appendChild(this._optionsDiv);
  31090. this._globalDiv.appendChild(this._treeDiv);
  31091. }
  31092. };
  31093. DebugLayer.prototype._displayStats = function () {
  31094. var scene = this._scene;
  31095. var engine = scene.getEngine();
  31096. var glInfo = engine.getGlInfo();
  31097. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31098. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31099. + "<b>Count</b><br>"
  31100. + "Total meshes: " + scene.meshes.length + "<br>"
  31101. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31102. + "Total materials: " + scene.materials.length + "<br>"
  31103. + "Total textures: " + scene.textures.length + "<br>"
  31104. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31105. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31106. + "Active bones: " + scene.getActiveBones() + "<br>"
  31107. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31108. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  31109. + "<b>Duration</b><br>"
  31110. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31111. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31112. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31113. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31114. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31115. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31116. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  31117. + "</div>"
  31118. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31119. + "<b>Extensions</b><br>"
  31120. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31121. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31122. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31123. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  31124. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31125. + "<b>Caps.</b><br>"
  31126. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31127. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31128. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  31129. + "</div><br>"
  31130. + "<b>Info</b><br>"
  31131. + glInfo.version + "<br>"
  31132. + glInfo.renderer + "<br>";
  31133. if (this.customStatsFunction) {
  31134. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31135. }
  31136. };
  31137. return DebugLayer;
  31138. })();
  31139. BABYLON.DebugLayer = DebugLayer;
  31140. })(BABYLON || (BABYLON = {}));
  31141. var BABYLON;
  31142. (function (BABYLON) {
  31143. var RawTexture = (function (_super) {
  31144. __extends(RawTexture, _super);
  31145. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31146. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31147. if (invertY === void 0) { invertY = false; }
  31148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31149. _super.call(this, null, scene, !generateMipMaps, invertY);
  31150. this.format = format;
  31151. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31152. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31153. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31154. }
  31155. RawTexture.prototype.update = function (data) {
  31156. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31157. };
  31158. // Statics
  31159. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31160. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31161. if (invertY === void 0) { invertY = false; }
  31162. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31163. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31164. };
  31165. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31166. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31167. if (invertY === void 0) { invertY = false; }
  31168. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31169. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31170. };
  31171. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31172. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31173. if (invertY === void 0) { invertY = false; }
  31174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31175. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31176. };
  31177. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31178. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31179. if (invertY === void 0) { invertY = false; }
  31180. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31181. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31182. };
  31183. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31184. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31185. if (invertY === void 0) { invertY = false; }
  31186. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31187. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31188. };
  31189. return RawTexture;
  31190. })(BABYLON.Texture);
  31191. BABYLON.RawTexture = RawTexture;
  31192. })(BABYLON || (BABYLON = {}));
  31193. var BABYLON;
  31194. (function (BABYLON) {
  31195. var IndexedVector2 = (function (_super) {
  31196. __extends(IndexedVector2, _super);
  31197. function IndexedVector2(original, index) {
  31198. _super.call(this, original.x, original.y);
  31199. this.index = index;
  31200. }
  31201. return IndexedVector2;
  31202. })(BABYLON.Vector2);
  31203. var PolygonPoints = (function () {
  31204. function PolygonPoints() {
  31205. this.elements = new Array();
  31206. }
  31207. PolygonPoints.prototype.add = function (originalPoints) {
  31208. var _this = this;
  31209. var result = new Array();
  31210. originalPoints.forEach(function (point) {
  31211. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31212. var newPoint = new IndexedVector2(point, _this.elements.length);
  31213. result.push(newPoint);
  31214. _this.elements.push(newPoint);
  31215. }
  31216. });
  31217. return result;
  31218. };
  31219. PolygonPoints.prototype.computeBounds = function () {
  31220. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31221. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31222. this.elements.forEach(function (point) {
  31223. // x
  31224. if (point.x < lmin.x) {
  31225. lmin.x = point.x;
  31226. }
  31227. else if (point.x > lmax.x) {
  31228. lmax.x = point.x;
  31229. }
  31230. // y
  31231. if (point.y < lmin.y) {
  31232. lmin.y = point.y;
  31233. }
  31234. else if (point.y > lmax.y) {
  31235. lmax.y = point.y;
  31236. }
  31237. });
  31238. return {
  31239. min: lmin,
  31240. max: lmax,
  31241. width: lmax.x - lmin.x,
  31242. height: lmax.y - lmin.y
  31243. };
  31244. };
  31245. return PolygonPoints;
  31246. })();
  31247. var Polygon = (function () {
  31248. function Polygon() {
  31249. }
  31250. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31251. return [
  31252. new BABYLON.Vector2(xmin, ymin),
  31253. new BABYLON.Vector2(xmax, ymin),
  31254. new BABYLON.Vector2(xmax, ymax),
  31255. new BABYLON.Vector2(xmin, ymax)
  31256. ];
  31257. };
  31258. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31259. if (cx === void 0) { cx = 0; }
  31260. if (cy === void 0) { cy = 0; }
  31261. if (numberOfSides === void 0) { numberOfSides = 32; }
  31262. var result = new Array();
  31263. var angle = 0;
  31264. var increment = (Math.PI * 2) / numberOfSides;
  31265. for (var i = 0; i < numberOfSides; i++) {
  31266. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31267. angle -= increment;
  31268. }
  31269. return result;
  31270. };
  31271. Polygon.Parse = function (input) {
  31272. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31273. var i, result = [];
  31274. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31275. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31276. }
  31277. return result;
  31278. };
  31279. Polygon.StartingAt = function (x, y) {
  31280. return BABYLON.Path2.StartingAt(x, y);
  31281. };
  31282. return Polygon;
  31283. })();
  31284. BABYLON.Polygon = Polygon;
  31285. var PolygonMeshBuilder = (function () {
  31286. function PolygonMeshBuilder(name, contours, scene) {
  31287. this._points = new PolygonPoints();
  31288. this._outlinepoints = new PolygonPoints();
  31289. this._holes = [];
  31290. if (!("poly2tri" in window)) {
  31291. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31292. }
  31293. this._name = name;
  31294. this._scene = scene;
  31295. var points;
  31296. if (contours instanceof BABYLON.Path2) {
  31297. points = contours.getPoints();
  31298. }
  31299. else {
  31300. points = contours;
  31301. }
  31302. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31303. this._outlinepoints.add(points);
  31304. }
  31305. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31306. this._swctx.addHole(this._points.add(hole));
  31307. var holepoints = new PolygonPoints();
  31308. holepoints.add(hole);
  31309. this._holes.push(holepoints);
  31310. return this;
  31311. };
  31312. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31313. var _this = this;
  31314. if (updatable === void 0) { updatable = false; }
  31315. var result = new BABYLON.Mesh(this._name, this._scene);
  31316. var normals = [];
  31317. var positions = [];
  31318. var uvs = [];
  31319. var bounds = this._points.computeBounds();
  31320. this._points.elements.forEach(function (p) {
  31321. normals.push(0, 1.0, 0);
  31322. positions.push(p.x, 0, p.y);
  31323. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31324. });
  31325. var indices = [];
  31326. this._swctx.triangulate();
  31327. this._swctx.getTriangles().forEach(function (triangle) {
  31328. triangle.getPoints().forEach(function (point) {
  31329. indices.push(point.index);
  31330. });
  31331. });
  31332. if (depth > 0) {
  31333. var positionscount = (positions.length / 3); //get the current pointcount
  31334. this._points.elements.forEach(function (p) {
  31335. normals.push(0, -1.0, 0);
  31336. positions.push(p.x, -depth, p.y);
  31337. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31338. });
  31339. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31340. var p2;
  31341. var poscounter = 0;
  31342. this._swctx.getTriangles().forEach(function (triangle) {
  31343. triangle.getPoints().forEach(function (point) {
  31344. switch (poscounter) {
  31345. case 0:
  31346. p1 = point;
  31347. break;
  31348. case 1:
  31349. p2 = point;
  31350. break;
  31351. case 2:
  31352. indices.push(point.index + positionscount);
  31353. indices.push(p2.index + positionscount);
  31354. indices.push(p1.index + positionscount);
  31355. poscounter = -1;
  31356. break;
  31357. }
  31358. poscounter++;
  31359. //indices.push((<IndexedVector2>point).index + positionscount);
  31360. });
  31361. });
  31362. //Add the sides
  31363. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31364. this._holes.forEach(function (hole) {
  31365. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31366. });
  31367. }
  31368. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31369. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31370. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31371. result.setIndices(indices);
  31372. return result;
  31373. };
  31374. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31375. var StartIndex = positions.length / 3;
  31376. var ulength = 0;
  31377. for (var i = 0; i < points.elements.length; i++) {
  31378. var p = points.elements[i];
  31379. var p1;
  31380. if ((i + 1) > points.elements.length - 1) {
  31381. p1 = points.elements[0];
  31382. }
  31383. else {
  31384. p1 = points.elements[i + 1];
  31385. }
  31386. positions.push(p.x, 0, p.y);
  31387. positions.push(p.x, -depth, p.y);
  31388. positions.push(p1.x, 0, p1.y);
  31389. positions.push(p1.x, -depth, p1.y);
  31390. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31391. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31392. var v3 = v2.subtract(v1);
  31393. var v4 = new BABYLON.Vector3(0, 1, 0);
  31394. var vn = BABYLON.Vector3.Cross(v3, v4);
  31395. vn = vn.normalize();
  31396. uvs.push(ulength / bounds.width, 0);
  31397. uvs.push(ulength / bounds.width, 1);
  31398. ulength += v3.length();
  31399. uvs.push((ulength / bounds.width), 0);
  31400. uvs.push((ulength / bounds.width), 1);
  31401. if (!flip) {
  31402. normals.push(-vn.x, -vn.y, -vn.z);
  31403. normals.push(-vn.x, -vn.y, -vn.z);
  31404. normals.push(-vn.x, -vn.y, -vn.z);
  31405. normals.push(-vn.x, -vn.y, -vn.z);
  31406. indices.push(StartIndex);
  31407. indices.push(StartIndex + 1);
  31408. indices.push(StartIndex + 2);
  31409. indices.push(StartIndex + 1);
  31410. indices.push(StartIndex + 3);
  31411. indices.push(StartIndex + 2);
  31412. }
  31413. else {
  31414. normals.push(vn.x, vn.y, vn.z);
  31415. normals.push(vn.x, vn.y, vn.z);
  31416. normals.push(vn.x, vn.y, vn.z);
  31417. normals.push(vn.x, vn.y, vn.z);
  31418. indices.push(StartIndex);
  31419. indices.push(StartIndex + 2);
  31420. indices.push(StartIndex + 1);
  31421. indices.push(StartIndex + 1);
  31422. indices.push(StartIndex + 2);
  31423. indices.push(StartIndex + 3);
  31424. }
  31425. StartIndex += 4;
  31426. }
  31427. ;
  31428. };
  31429. return PolygonMeshBuilder;
  31430. })();
  31431. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31432. })(BABYLON || (BABYLON = {}));
  31433. var BABYLON;
  31434. (function (BABYLON) {
  31435. var SimplificationSettings = (function () {
  31436. function SimplificationSettings(quality, distance, optimizeMesh) {
  31437. this.quality = quality;
  31438. this.distance = distance;
  31439. this.optimizeMesh = optimizeMesh;
  31440. }
  31441. return SimplificationSettings;
  31442. })();
  31443. BABYLON.SimplificationSettings = SimplificationSettings;
  31444. var SimplificationQueue = (function () {
  31445. function SimplificationQueue() {
  31446. this.running = false;
  31447. this._simplificationArray = [];
  31448. }
  31449. SimplificationQueue.prototype.addTask = function (task) {
  31450. this._simplificationArray.push(task);
  31451. };
  31452. SimplificationQueue.prototype.executeNext = function () {
  31453. var task = this._simplificationArray.pop();
  31454. if (task) {
  31455. this.running = true;
  31456. this.runSimplification(task);
  31457. }
  31458. else {
  31459. this.running = false;
  31460. }
  31461. };
  31462. SimplificationQueue.prototype.runSimplification = function (task) {
  31463. var _this = this;
  31464. if (task.parallelProcessing) {
  31465. //parallel simplifier
  31466. task.settings.forEach(function (setting) {
  31467. var simplifier = _this.getSimplifier(task);
  31468. simplifier.simplify(setting, function (newMesh) {
  31469. task.mesh.addLODLevel(setting.distance, newMesh);
  31470. newMesh.isVisible = true;
  31471. //check if it is the last
  31472. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31473. //all done, run the success callback.
  31474. task.successCallback();
  31475. }
  31476. _this.executeNext();
  31477. });
  31478. });
  31479. }
  31480. else {
  31481. //single simplifier.
  31482. var simplifier = this.getSimplifier(task);
  31483. var runDecimation = function (setting, callback) {
  31484. simplifier.simplify(setting, function (newMesh) {
  31485. task.mesh.addLODLevel(setting.distance, newMesh);
  31486. newMesh.isVisible = true;
  31487. //run the next quality level
  31488. callback();
  31489. });
  31490. };
  31491. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31492. runDecimation(task.settings[loop.index], function () {
  31493. loop.executeNext();
  31494. });
  31495. }, function () {
  31496. //execution ended, run the success callback.
  31497. if (task.successCallback) {
  31498. task.successCallback();
  31499. }
  31500. _this.executeNext();
  31501. });
  31502. }
  31503. };
  31504. SimplificationQueue.prototype.getSimplifier = function (task) {
  31505. switch (task.simplificationType) {
  31506. case SimplificationType.QUADRATIC:
  31507. default:
  31508. return new QuadraticErrorSimplification(task.mesh);
  31509. }
  31510. };
  31511. return SimplificationQueue;
  31512. })();
  31513. BABYLON.SimplificationQueue = SimplificationQueue;
  31514. /**
  31515. * The implemented types of simplification.
  31516. * At the moment only Quadratic Error Decimation is implemented.
  31517. */
  31518. (function (SimplificationType) {
  31519. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31520. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31521. var SimplificationType = BABYLON.SimplificationType;
  31522. var DecimationTriangle = (function () {
  31523. function DecimationTriangle(vertices) {
  31524. this.vertices = vertices;
  31525. this.error = new Array(4);
  31526. this.deleted = false;
  31527. this.isDirty = false;
  31528. this.deletePending = false;
  31529. this.borderFactor = 0;
  31530. }
  31531. return DecimationTriangle;
  31532. })();
  31533. BABYLON.DecimationTriangle = DecimationTriangle;
  31534. var DecimationVertex = (function () {
  31535. function DecimationVertex(position, id) {
  31536. this.position = position;
  31537. this.id = id;
  31538. this.isBorder = true;
  31539. this.q = new QuadraticMatrix();
  31540. this.triangleCount = 0;
  31541. this.triangleStart = 0;
  31542. this.originalOffsets = [];
  31543. }
  31544. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31545. this.position.copyFrom(newPosition);
  31546. };
  31547. return DecimationVertex;
  31548. })();
  31549. BABYLON.DecimationVertex = DecimationVertex;
  31550. var QuadraticMatrix = (function () {
  31551. function QuadraticMatrix(data) {
  31552. this.data = new Array(10);
  31553. for (var i = 0; i < 10; ++i) {
  31554. if (data && data[i]) {
  31555. this.data[i] = data[i];
  31556. }
  31557. else {
  31558. this.data[i] = 0;
  31559. }
  31560. }
  31561. }
  31562. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31563. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31564. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31565. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31566. return det;
  31567. };
  31568. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31569. for (var i = 0; i < 10; ++i) {
  31570. this.data[i] += matrix.data[i];
  31571. }
  31572. };
  31573. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31574. for (var i = 0; i < 10; ++i) {
  31575. this.data[i] += data[i];
  31576. }
  31577. };
  31578. QuadraticMatrix.prototype.add = function (matrix) {
  31579. var m = new QuadraticMatrix();
  31580. for (var i = 0; i < 10; ++i) {
  31581. m.data[i] = this.data[i] + matrix.data[i];
  31582. }
  31583. return m;
  31584. };
  31585. QuadraticMatrix.FromData = function (a, b, c, d) {
  31586. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31587. };
  31588. //returning an array to avoid garbage collection
  31589. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31590. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31591. };
  31592. return QuadraticMatrix;
  31593. })();
  31594. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31595. var Reference = (function () {
  31596. function Reference(vertexId, triangleId) {
  31597. this.vertexId = vertexId;
  31598. this.triangleId = triangleId;
  31599. }
  31600. return Reference;
  31601. })();
  31602. BABYLON.Reference = Reference;
  31603. /**
  31604. * An implementation of the Quadratic Error simplification algorithm.
  31605. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31606. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31607. * @author RaananW
  31608. */
  31609. var QuadraticErrorSimplification = (function () {
  31610. function QuadraticErrorSimplification(_mesh) {
  31611. this._mesh = _mesh;
  31612. this.initialized = false;
  31613. this.syncIterations = 5000;
  31614. this.aggressiveness = 7;
  31615. this.decimationIterations = 100;
  31616. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31617. }
  31618. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31619. var _this = this;
  31620. this.initDecimatedMesh();
  31621. //iterating through the submeshes array, one after the other.
  31622. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31623. _this.initWithMesh(loop.index, function () {
  31624. _this.runDecimation(settings, loop.index, function () {
  31625. loop.executeNext();
  31626. });
  31627. }, settings.optimizeMesh);
  31628. }, function () {
  31629. setTimeout(function () {
  31630. successCallback(_this._reconstructedMesh);
  31631. }, 0);
  31632. });
  31633. };
  31634. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31635. var _this = this;
  31636. var gCount = 0;
  31637. triangle.vertices.forEach(function (vertex) {
  31638. var count = 0;
  31639. var vPos = vertex.position;
  31640. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31641. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31642. ++count;
  31643. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  31644. ++count;
  31645. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  31646. ++count;
  31647. if (count > 1) {
  31648. ++gCount;
  31649. }
  31650. ;
  31651. });
  31652. if (gCount > 1) {
  31653. console.log(triangle, gCount);
  31654. }
  31655. return gCount > 1;
  31656. };
  31657. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31658. var _this = this;
  31659. var targetCount = ~~(this.triangles.length * settings.quality);
  31660. var deletedTriangles = 0;
  31661. var triangleCount = this.triangles.length;
  31662. var iterationFunction = function (iteration, callback) {
  31663. setTimeout(function () {
  31664. if (iteration % 5 === 0) {
  31665. _this.updateMesh(iteration === 0);
  31666. }
  31667. for (var i = 0; i < _this.triangles.length; ++i) {
  31668. _this.triangles[i].isDirty = false;
  31669. }
  31670. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31671. var trianglesIterator = function (i) {
  31672. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31673. var t = _this.triangles[tIdx];
  31674. if (!t)
  31675. return;
  31676. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31677. return;
  31678. }
  31679. for (var j = 0; j < 3; ++j) {
  31680. if (t.error[j] < threshold) {
  31681. var deleted0 = [];
  31682. var deleted1 = [];
  31683. var v0 = t.vertices[j];
  31684. var v1 = t.vertices[(j + 1) % 3];
  31685. if (v0.isBorder !== v1.isBorder)
  31686. continue;
  31687. var p = BABYLON.Vector3.Zero();
  31688. var n = BABYLON.Vector3.Zero();
  31689. var uv = BABYLON.Vector2.Zero();
  31690. var color = new BABYLON.Color4(0, 0, 0, 1);
  31691. _this.calculateError(v0, v1, p, n, uv, color);
  31692. var delTr = [];
  31693. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31694. continue;
  31695. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31696. continue;
  31697. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31698. continue;
  31699. var uniqueArray = [];
  31700. delTr.forEach(function (deletedT) {
  31701. if (uniqueArray.indexOf(deletedT) === -1) {
  31702. deletedT.deletePending = true;
  31703. uniqueArray.push(deletedT);
  31704. }
  31705. });
  31706. if (uniqueArray.length % 2 != 0) {
  31707. continue;
  31708. }
  31709. v0.q = v1.q.add(v0.q);
  31710. v0.updatePosition(p);
  31711. var tStart = _this.references.length;
  31712. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31713. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31714. var tCount = _this.references.length - tStart;
  31715. if (tCount <= v0.triangleCount) {
  31716. if (tCount) {
  31717. for (var c = 0; c < tCount; c++) {
  31718. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31719. }
  31720. }
  31721. }
  31722. else {
  31723. v0.triangleStart = tStart;
  31724. }
  31725. v0.triangleCount = tCount;
  31726. break;
  31727. }
  31728. }
  31729. };
  31730. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31731. }, 0);
  31732. };
  31733. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31734. if (triangleCount - deletedTriangles <= targetCount)
  31735. loop.breakLoop();
  31736. else {
  31737. iterationFunction(loop.index, function () {
  31738. loop.executeNext();
  31739. });
  31740. }
  31741. }, function () {
  31742. setTimeout(function () {
  31743. //reconstruct this part of the mesh
  31744. _this.reconstructMesh(submeshIndex);
  31745. successCallback();
  31746. }, 0);
  31747. });
  31748. };
  31749. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31750. var _this = this;
  31751. this.vertices = [];
  31752. this.triangles = [];
  31753. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31754. var indices = this._mesh.getIndices();
  31755. var submesh = this._mesh.subMeshes[submeshIndex];
  31756. var findInVertices = function (positionToSearch) {
  31757. if (optimizeMesh) {
  31758. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31759. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31760. return _this.vertices[ii];
  31761. }
  31762. }
  31763. }
  31764. return null;
  31765. };
  31766. var vertexReferences = [];
  31767. var vertexInit = function (i) {
  31768. var offset = i + submesh.verticesStart;
  31769. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31770. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31771. vertex.originalOffsets.push(offset);
  31772. if (vertex.id == _this.vertices.length) {
  31773. _this.vertices.push(vertex);
  31774. }
  31775. vertexReferences.push(vertex.id);
  31776. };
  31777. //var totalVertices = mesh.getTotalVertices();
  31778. var totalVertices = submesh.verticesCount;
  31779. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31780. var indicesInit = function (i) {
  31781. var offset = (submesh.indexStart / 3) + i;
  31782. var pos = (offset * 3);
  31783. var i0 = indices[pos + 0];
  31784. var i1 = indices[pos + 1];
  31785. var i2 = indices[pos + 2];
  31786. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31787. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31788. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31789. var triangle = new DecimationTriangle([v0, v1, v2]);
  31790. triangle.originalOffset = pos;
  31791. _this.triangles.push(triangle);
  31792. };
  31793. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31794. _this.init(callback);
  31795. });
  31796. });
  31797. };
  31798. QuadraticErrorSimplification.prototype.init = function (callback) {
  31799. var _this = this;
  31800. var triangleInit1 = function (i) {
  31801. var t = _this.triangles[i];
  31802. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31803. for (var j = 0; j < 3; j++) {
  31804. 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))));
  31805. }
  31806. };
  31807. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31808. var triangleInit2 = function (i) {
  31809. var t = _this.triangles[i];
  31810. for (var j = 0; j < 3; ++j) {
  31811. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31812. }
  31813. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31814. };
  31815. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31816. _this.initialized = true;
  31817. callback();
  31818. });
  31819. });
  31820. };
  31821. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31822. var newTriangles = [];
  31823. var i;
  31824. for (i = 0; i < this.vertices.length; ++i) {
  31825. this.vertices[i].triangleCount = 0;
  31826. }
  31827. var t;
  31828. var j;
  31829. for (i = 0; i < this.triangles.length; ++i) {
  31830. if (!this.triangles[i].deleted) {
  31831. t = this.triangles[i];
  31832. for (j = 0; j < 3; ++j) {
  31833. t.vertices[j].triangleCount = 1;
  31834. }
  31835. newTriangles.push(t);
  31836. }
  31837. }
  31838. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  31839. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  31840. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  31841. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  31842. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31843. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31844. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31845. var vertexCount = 0;
  31846. for (i = 0; i < this.vertices.length; ++i) {
  31847. var vertex = this.vertices[i];
  31848. vertex.id = vertexCount;
  31849. if (vertex.triangleCount) {
  31850. vertex.originalOffsets.forEach(function (originalOffset) {
  31851. newPositionData.push(vertex.position.x);
  31852. newPositionData.push(vertex.position.y);
  31853. newPositionData.push(vertex.position.z);
  31854. newNormalData.push(normalData[originalOffset * 3]);
  31855. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31856. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31857. if (uvs && uvs.length) {
  31858. newUVsData.push(uvs[(originalOffset * 2)]);
  31859. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31860. }
  31861. else if (colorsData && colorsData.length) {
  31862. newColorsData.push(colorsData[(originalOffset * 4)]);
  31863. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31864. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31865. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31866. }
  31867. ++vertexCount;
  31868. });
  31869. }
  31870. }
  31871. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31872. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31873. var submeshesArray = this._reconstructedMesh.subMeshes;
  31874. this._reconstructedMesh.subMeshes = [];
  31875. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31876. var originalIndices = this._mesh.getIndices();
  31877. for (i = 0; i < newTriangles.length; ++i) {
  31878. var t = newTriangles[i];
  31879. //now get the new referencing point for each vertex
  31880. [0, 1, 2].forEach(function (idx) {
  31881. var id = originalIndices[t.originalOffset + idx];
  31882. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31883. if (offset < 0)
  31884. offset = 0;
  31885. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31886. });
  31887. }
  31888. //overwriting the old vertex buffers and indices.
  31889. this._reconstructedMesh.setIndices(newIndicesArray);
  31890. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31891. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31892. if (newUVsData.length > 0)
  31893. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31894. if (newColorsData.length > 0)
  31895. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31896. //create submesh
  31897. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31898. if (submeshIndex > 0) {
  31899. this._reconstructedMesh.subMeshes = [];
  31900. submeshesArray.forEach(function (submesh) {
  31901. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31902. });
  31903. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31904. }
  31905. };
  31906. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31907. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31908. this._reconstructedMesh.material = this._mesh.material;
  31909. this._reconstructedMesh.parent = this._mesh.parent;
  31910. this._reconstructedMesh.isVisible = false;
  31911. };
  31912. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31913. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31914. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31915. if (t.deleted)
  31916. continue;
  31917. var s = this.references[vertex1.triangleStart + i].vertexId;
  31918. var v1 = t.vertices[(s + 1) % 3];
  31919. var v2 = t.vertices[(s + 2) % 3];
  31920. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31921. deletedArray[i] = true;
  31922. delTr.push(t);
  31923. continue;
  31924. }
  31925. var d1 = v1.position.subtract(point);
  31926. d1 = d1.normalize();
  31927. var d2 = v2.position.subtract(point);
  31928. d2 = d2.normalize();
  31929. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31930. return true;
  31931. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31932. deletedArray[i] = false;
  31933. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31934. return true;
  31935. }
  31936. return false;
  31937. };
  31938. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31939. var newDeleted = deletedTriangles;
  31940. for (var i = 0; i < vertex.triangleCount; ++i) {
  31941. var ref = this.references[vertex.triangleStart + i];
  31942. var t = this.triangles[ref.triangleId];
  31943. if (t.deleted)
  31944. continue;
  31945. if (deletedArray[i] && t.deletePending) {
  31946. t.deleted = true;
  31947. newDeleted++;
  31948. continue;
  31949. }
  31950. t.vertices[ref.vertexId] = origVertex;
  31951. t.isDirty = true;
  31952. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31953. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31954. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31955. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31956. this.references.push(ref);
  31957. }
  31958. return newDeleted;
  31959. };
  31960. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31961. for (var i = 0; i < this.vertices.length; ++i) {
  31962. var vCount = [];
  31963. var vId = [];
  31964. var v = this.vertices[i];
  31965. var j;
  31966. for (j = 0; j < v.triangleCount; ++j) {
  31967. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31968. for (var ii = 0; ii < 3; ii++) {
  31969. var ofs = 0;
  31970. var vv = triangle.vertices[ii];
  31971. while (ofs < vCount.length) {
  31972. if (vId[ofs] === vv.id)
  31973. break;
  31974. ++ofs;
  31975. }
  31976. if (ofs === vCount.length) {
  31977. vCount.push(1);
  31978. vId.push(vv.id);
  31979. }
  31980. else {
  31981. vCount[ofs]++;
  31982. }
  31983. }
  31984. }
  31985. for (j = 0; j < vCount.length; ++j) {
  31986. if (vCount[j] === 1) {
  31987. this.vertices[vId[j]].isBorder = true;
  31988. }
  31989. else {
  31990. this.vertices[vId[j]].isBorder = false;
  31991. }
  31992. }
  31993. }
  31994. };
  31995. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31996. if (identifyBorders === void 0) { identifyBorders = false; }
  31997. var i;
  31998. if (!identifyBorders) {
  31999. var newTrianglesVector = [];
  32000. for (i = 0; i < this.triangles.length; ++i) {
  32001. if (!this.triangles[i].deleted) {
  32002. newTrianglesVector.push(this.triangles[i]);
  32003. }
  32004. }
  32005. this.triangles = newTrianglesVector;
  32006. }
  32007. for (i = 0; i < this.vertices.length; ++i) {
  32008. this.vertices[i].triangleCount = 0;
  32009. this.vertices[i].triangleStart = 0;
  32010. }
  32011. var t;
  32012. var j;
  32013. var v;
  32014. for (i = 0; i < this.triangles.length; ++i) {
  32015. t = this.triangles[i];
  32016. for (j = 0; j < 3; ++j) {
  32017. v = t.vertices[j];
  32018. v.triangleCount++;
  32019. }
  32020. }
  32021. var tStart = 0;
  32022. for (i = 0; i < this.vertices.length; ++i) {
  32023. this.vertices[i].triangleStart = tStart;
  32024. tStart += this.vertices[i].triangleCount;
  32025. this.vertices[i].triangleCount = 0;
  32026. }
  32027. var newReferences = new Array(this.triangles.length * 3);
  32028. for (i = 0; i < this.triangles.length; ++i) {
  32029. t = this.triangles[i];
  32030. for (j = 0; j < 3; ++j) {
  32031. v = t.vertices[j];
  32032. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32033. v.triangleCount++;
  32034. }
  32035. }
  32036. this.references = newReferences;
  32037. if (identifyBorders) {
  32038. this.identifyBorder();
  32039. }
  32040. };
  32041. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32042. var x = point.x;
  32043. var y = point.y;
  32044. var z = point.z;
  32045. 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
  32046. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32047. };
  32048. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32049. var q = vertex1.q.add(vertex2.q);
  32050. var border = vertex1.isBorder && vertex2.isBorder;
  32051. var error = 0;
  32052. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32053. if (qDet !== 0 && !border) {
  32054. if (!pointResult) {
  32055. pointResult = BABYLON.Vector3.Zero();
  32056. }
  32057. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32058. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32059. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32060. error = this.vertexError(q, pointResult);
  32061. }
  32062. else {
  32063. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32064. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32065. var error1 = this.vertexError(q, vertex1.position);
  32066. var error2 = this.vertexError(q, vertex2.position);
  32067. var error3 = this.vertexError(q, p3);
  32068. error = Math.min(error1, error2, error3);
  32069. if (error === error1) {
  32070. if (pointResult) {
  32071. pointResult.copyFrom(vertex1.position);
  32072. }
  32073. }
  32074. else if (error === error2) {
  32075. if (pointResult) {
  32076. pointResult.copyFrom(vertex2.position);
  32077. }
  32078. }
  32079. else {
  32080. if (pointResult) {
  32081. pointResult.copyFrom(p3);
  32082. }
  32083. }
  32084. }
  32085. return error;
  32086. };
  32087. return QuadraticErrorSimplification;
  32088. })();
  32089. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32090. })(BABYLON || (BABYLON = {}));
  32091. var BABYLON;
  32092. (function (BABYLON) {
  32093. var Analyser = (function () {
  32094. function Analyser(scene) {
  32095. this.SMOOTHING = 0.75;
  32096. this.FFT_SIZE = 512;
  32097. this.BARGRAPHAMPLITUDE = 256;
  32098. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32099. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32100. this._scene = scene;
  32101. this._audioEngine = BABYLON.Engine.audioEngine;
  32102. if (this._audioEngine.canUseWebAudio) {
  32103. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32104. this._webAudioAnalyser.minDecibels = -140;
  32105. this._webAudioAnalyser.maxDecibels = 0;
  32106. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32107. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32108. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32109. }
  32110. }
  32111. Analyser.prototype.getFrequencyBinCount = function () {
  32112. if (this._audioEngine.canUseWebAudio) {
  32113. return this._webAudioAnalyser.frequencyBinCount;
  32114. }
  32115. else {
  32116. return 0;
  32117. }
  32118. };
  32119. Analyser.prototype.getByteFrequencyData = function () {
  32120. if (this._audioEngine.canUseWebAudio) {
  32121. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32122. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32123. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32124. }
  32125. return this._byteFreqs;
  32126. };
  32127. Analyser.prototype.getByteTimeDomainData = function () {
  32128. if (this._audioEngine.canUseWebAudio) {
  32129. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32130. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32131. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32132. }
  32133. return this._byteTime;
  32134. };
  32135. Analyser.prototype.getFloatFrequencyData = function () {
  32136. if (this._audioEngine.canUseWebAudio) {
  32137. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32138. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32139. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32140. }
  32141. return this._floatFreqs;
  32142. };
  32143. Analyser.prototype.drawDebugCanvas = function () {
  32144. var _this = this;
  32145. if (this._audioEngine.canUseWebAudio) {
  32146. if (!this._debugCanvas) {
  32147. this._debugCanvas = document.createElement("canvas");
  32148. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32149. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32150. this._debugCanvas.style.position = "absolute";
  32151. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32152. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32153. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32154. document.body.appendChild(this._debugCanvas);
  32155. this._registerFunc = function () {
  32156. _this.drawDebugCanvas();
  32157. };
  32158. this._scene.registerBeforeRender(this._registerFunc);
  32159. }
  32160. if (this._registerFunc) {
  32161. var workingArray = this.getByteFrequencyData();
  32162. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32163. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32164. // Draw the frequency domain chart.
  32165. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32166. var value = workingArray[i];
  32167. var percent = value / this.BARGRAPHAMPLITUDE;
  32168. var height = this.DEBUGCANVASSIZE.height * percent;
  32169. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32170. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32171. var hue = i / this.getFrequencyBinCount() * 360;
  32172. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32173. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32174. }
  32175. }
  32176. }
  32177. };
  32178. Analyser.prototype.stopDebugCanvas = function () {
  32179. if (this._debugCanvas) {
  32180. this._scene.unregisterBeforeRender(this._registerFunc);
  32181. this._registerFunc = null;
  32182. document.body.removeChild(this._debugCanvas);
  32183. this._debugCanvas = null;
  32184. this._debugCanvasContext = null;
  32185. }
  32186. };
  32187. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32188. if (this._audioEngine.canUseWebAudio) {
  32189. inputAudioNode.connect(this._webAudioAnalyser);
  32190. this._webAudioAnalyser.connect(outputAudioNode);
  32191. }
  32192. };
  32193. Analyser.prototype.dispose = function () {
  32194. if (this._audioEngine.canUseWebAudio) {
  32195. this._webAudioAnalyser.disconnect();
  32196. }
  32197. };
  32198. return Analyser;
  32199. })();
  32200. BABYLON.Analyser = Analyser;
  32201. })(BABYLON || (BABYLON = {}));
  32202. var BABYLON;
  32203. (function (BABYLON) {
  32204. var DepthRenderer = (function () {
  32205. function DepthRenderer(scene, type) {
  32206. var _this = this;
  32207. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  32208. this._viewMatrix = BABYLON.Matrix.Zero();
  32209. this._projectionMatrix = BABYLON.Matrix.Zero();
  32210. this._transformMatrix = BABYLON.Matrix.Zero();
  32211. this._worldViewProjection = BABYLON.Matrix.Zero();
  32212. this._scene = scene;
  32213. var engine = scene.getEngine();
  32214. // Render target
  32215. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  32216. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32217. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32218. this._depthMap.refreshRate = 1;
  32219. this._depthMap.renderParticles = false;
  32220. this._depthMap.renderList = null;
  32221. // set default depth value to 1.0 (far away)
  32222. this._depthMap.onClear = function (engine) {
  32223. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  32224. };
  32225. // Custom render function
  32226. var renderSubMesh = function (subMesh) {
  32227. var mesh = subMesh.getRenderingMesh();
  32228. var scene = _this._scene;
  32229. var engine = scene.getEngine();
  32230. // Culling
  32231. engine.setState(subMesh.getMaterial().backFaceCulling);
  32232. // Managing instances
  32233. var batch = mesh._getInstancesRenderList(subMesh._id);
  32234. if (batch.mustReturn) {
  32235. return;
  32236. }
  32237. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32238. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32239. engine.enableEffect(_this._effect);
  32240. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  32241. var material = subMesh.getMaterial();
  32242. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32243. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  32244. // Alpha test
  32245. if (material && material.needAlphaTesting()) {
  32246. var alphaTexture = material.getAlphaTestTexture();
  32247. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32248. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32249. }
  32250. // Bones
  32251. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32252. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32253. }
  32254. // Draw
  32255. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32256. }
  32257. };
  32258. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32259. var index;
  32260. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32261. renderSubMesh(opaqueSubMeshes.data[index]);
  32262. }
  32263. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32264. renderSubMesh(alphaTestSubMeshes.data[index]);
  32265. }
  32266. };
  32267. }
  32268. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32269. var defines = [];
  32270. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32271. var mesh = subMesh.getMesh();
  32272. var scene = mesh.getScene();
  32273. var material = subMesh.getMaterial();
  32274. // Alpha test
  32275. if (material && material.needAlphaTesting()) {
  32276. defines.push("#define ALPHATEST");
  32277. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32278. attribs.push(BABYLON.VertexBuffer.UVKind);
  32279. defines.push("#define UV1");
  32280. }
  32281. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32282. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32283. defines.push("#define UV2");
  32284. }
  32285. }
  32286. // Bones
  32287. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32290. defines.push("#define BONES");
  32291. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32292. }
  32293. // Instances
  32294. if (useInstances) {
  32295. defines.push("#define INSTANCES");
  32296. attribs.push("world0");
  32297. attribs.push("world1");
  32298. attribs.push("world2");
  32299. attribs.push("world3");
  32300. }
  32301. // Get correct effect
  32302. var join = defines.join("\n");
  32303. if (this._cachedDefines !== join) {
  32304. this._cachedDefines = join;
  32305. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32306. }
  32307. return this._effect.isReady();
  32308. };
  32309. DepthRenderer.prototype.getDepthMap = function () {
  32310. return this._depthMap;
  32311. };
  32312. // Methods
  32313. DepthRenderer.prototype.dispose = function () {
  32314. this._depthMap.dispose();
  32315. };
  32316. return DepthRenderer;
  32317. })();
  32318. BABYLON.DepthRenderer = DepthRenderer;
  32319. })(BABYLON || (BABYLON = {}));
  32320. var BABYLON;
  32321. (function (BABYLON) {
  32322. var SSAORenderingPipeline = (function (_super) {
  32323. __extends(SSAORenderingPipeline, _super);
  32324. /**
  32325. * @constructor
  32326. * @param {string} name - The rendering pipeline name
  32327. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32328. * @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 }
  32329. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32330. */
  32331. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32332. var _this = this;
  32333. _super.call(this, scene.getEngine(), name);
  32334. // Members
  32335. /**
  32336. * The PassPostProcess id in the pipeline that contains the original scene color
  32337. * @type {string}
  32338. */
  32339. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32340. /**
  32341. * The SSAO PostProcess id in the pipeline
  32342. * @type {string}
  32343. */
  32344. this.SSAORenderEffect = "SSAORenderEffect";
  32345. /**
  32346. * The horizontal blur PostProcess id in the pipeline
  32347. * @type {string}
  32348. */
  32349. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32350. /**
  32351. * The vertical blur PostProcess id in the pipeline
  32352. * @type {string}
  32353. */
  32354. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32355. /**
  32356. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32357. * @type {string}
  32358. */
  32359. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32360. /**
  32361. * The output strength of the SSAO post-process. Default value is 1.0.
  32362. * @type {number}
  32363. */
  32364. this.totalStrength = 1.0;
  32365. /**
  32366. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32367. * @type {number}
  32368. */
  32369. this.radius = 0.0002;
  32370. /**
  32371. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32372. * Must not be equal to fallOff and superior to fallOff.
  32373. * Default value is 0.0075
  32374. * @type {number}
  32375. */
  32376. this.area = 0.0075;
  32377. /**
  32378. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32379. * Must not be equal to area and inferior to area.
  32380. * Default value is 0.0002
  32381. * @type {number}
  32382. */
  32383. this.fallOff = 0.0002;
  32384. this._firstUpdate = true;
  32385. this._scene = scene;
  32386. // Set up assets
  32387. this._createRandomTexture();
  32388. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32389. var ssaoRatio = ratio.ssaoRatio || ratio;
  32390. var combineRatio = ratio.combineRatio || ratio;
  32391. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32392. this._createSSAOPostProcess(ssaoRatio);
  32393. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32394. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32395. this._createSSAOCombinePostProcess(combineRatio);
  32396. // Set up pipeline
  32397. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32398. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32399. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32400. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32401. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32402. // Finish
  32403. scene.postProcessRenderPipelineManager.addPipeline(this);
  32404. if (cameras)
  32405. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32406. }
  32407. // Public Methods
  32408. /**
  32409. * Returns the horizontal blur PostProcess
  32410. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32411. */
  32412. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32413. return this._blurHPostProcess;
  32414. };
  32415. /**
  32416. * Returns the vertical blur PostProcess
  32417. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32418. */
  32419. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32420. return this._blurVPostProcess;
  32421. };
  32422. /**
  32423. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32424. */
  32425. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32426. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32427. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32428. this._originalColorPostProcess = undefined;
  32429. this._ssaoPostProcess = undefined;
  32430. this._blurHPostProcess = undefined;
  32431. this._blurVPostProcess = undefined;
  32432. this._ssaoCombinePostProcess = undefined;
  32433. this._randomTexture.dispose();
  32434. if (disableDepthRender)
  32435. this._scene.disableDepthRenderer();
  32436. };
  32437. // Private Methods
  32438. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32439. var _this = this;
  32440. var sampleSphere = [
  32441. 0.5381, 0.1856, -0.4319,
  32442. 0.1379, 0.2486, 0.4430,
  32443. 0.3371, 0.5679, -0.0057,
  32444. -0.6999, -0.0451, -0.0019,
  32445. 0.0689, -0.1598, -0.8547,
  32446. 0.0560, 0.0069, -0.1843,
  32447. -0.0146, 0.1402, 0.0762,
  32448. 0.0100, -0.1924, -0.0344,
  32449. -0.3577, -0.5301, -0.4358,
  32450. -0.3169, 0.1063, 0.0158,
  32451. 0.0103, -0.5869, 0.0046,
  32452. -0.0897, -0.4940, 0.3287,
  32453. 0.7119, -0.0154, -0.0918,
  32454. -0.0533, 0.0596, -0.5411,
  32455. 0.0352, -0.0631, 0.5460,
  32456. -0.4776, 0.2847, -0.0271
  32457. ];
  32458. var samplesFactor = 1.0 / 16.0;
  32459. 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);
  32460. this._ssaoPostProcess.onApply = function (effect) {
  32461. if (_this._firstUpdate) {
  32462. effect.setArray3("sampleSphere", sampleSphere);
  32463. effect.setFloat("samplesFactor", samplesFactor);
  32464. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32465. _this._firstUpdate = false;
  32466. }
  32467. effect.setFloat("totalStrength", _this.totalStrength);
  32468. effect.setFloat("radius", _this.radius);
  32469. effect.setFloat("area", _this.area);
  32470. effect.setFloat("fallOff", _this.fallOff);
  32471. effect.setTexture("textureSampler", _this._depthTexture);
  32472. effect.setTexture("randomSampler", _this._randomTexture);
  32473. };
  32474. };
  32475. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32476. var _this = this;
  32477. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32478. this._ssaoCombinePostProcess.onApply = function (effect) {
  32479. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32480. };
  32481. };
  32482. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32483. var size = 512;
  32484. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32485. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32486. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32487. var context = this._randomTexture.getContext();
  32488. var rand = function (min, max) {
  32489. return Math.random() * (max - min) + min;
  32490. };
  32491. for (var x = 0; x < size; x++) {
  32492. for (var y = 0; y < size; y++) {
  32493. var randVector = BABYLON.Vector3.Zero();
  32494. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  32495. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  32496. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  32497. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  32498. context.fillRect(x, y, 1, 1);
  32499. }
  32500. }
  32501. this._randomTexture.update(false);
  32502. };
  32503. return SSAORenderingPipeline;
  32504. })(BABYLON.PostProcessRenderPipeline);
  32505. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  32506. })(BABYLON || (BABYLON = {}));
  32507. var BABYLON;
  32508. (function (BABYLON) {
  32509. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  32510. var VolumetricLightScatteringPostProcess = (function (_super) {
  32511. __extends(VolumetricLightScatteringPostProcess, _super);
  32512. /**
  32513. * @constructor
  32514. * @param {string} name - The post-process name
  32515. * @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)
  32516. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  32517. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  32518. * @param {number} samples - The post-process quality, default 100
  32519. * @param {number} samplingMode - The post-process filtering mode
  32520. * @param {BABYLON.Engine} engine - The babylon engine
  32521. * @param {boolean} reusable - If the post-process is reusable
  32522. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  32523. */
  32524. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  32525. var _this = this;
  32526. if (samples === void 0) { samples = 100; }
  32527. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32528. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  32529. this._screenCoordinates = BABYLON.Vector2.Zero();
  32530. /**
  32531. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  32532. * @type {boolean}
  32533. */
  32534. this.useCustomMeshPosition = false;
  32535. /**
  32536. * If the post-process should inverse the light scattering direction
  32537. * @type {boolean}
  32538. */
  32539. this.invert = true;
  32540. /**
  32541. * Set to true to use the diffuseColor instead of the diffuseTexture
  32542. * @type {boolean}
  32543. */
  32544. this.useDiffuseColor = false;
  32545. /**
  32546. * Array containing the excluded meshes not rendered in the internal pass
  32547. */
  32548. this.excludedMeshes = new Array();
  32549. /**
  32550. * Controls the overall intensity of the post-process
  32551. * @type {number}
  32552. */
  32553. this.exposure = 0.3;
  32554. /**
  32555. * Dissipates each sample's contribution in range [0, 1]
  32556. * @type {number}
  32557. */
  32558. this.decay = 0.96815;
  32559. /**
  32560. * Controls the overall intensity of each sample
  32561. * @type {number}
  32562. */
  32563. this.weight = 0.58767;
  32564. /**
  32565. * Controls the density of each sample
  32566. * @type {number}
  32567. */
  32568. this.density = 0.926;
  32569. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  32570. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  32571. // Configure mesh
  32572. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  32573. // Configure
  32574. this._createPass(scene, ratio.passRatio || ratio);
  32575. this.onApply = function (effect) {
  32576. _this._updateMeshScreenCoordinates(scene);
  32577. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  32578. effect.setFloat("exposure", _this.exposure);
  32579. effect.setFloat("decay", _this.decay);
  32580. effect.setFloat("weight", _this.weight);
  32581. effect.setFloat("density", _this.density);
  32582. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  32583. };
  32584. }
  32585. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  32586. var mesh = subMesh.getMesh();
  32587. var defines = [];
  32588. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32589. var material = subMesh.getMaterial();
  32590. var needUV = false;
  32591. // Render this.mesh as default
  32592. if (mesh === this.mesh) {
  32593. if (this.useDiffuseColor) {
  32594. defines.push("#define DIFFUSE_COLOR_RENDER");
  32595. }
  32596. else if (material) {
  32597. if (material.diffuseTexture !== undefined) {
  32598. defines.push("#define BASIC_RENDER");
  32599. }
  32600. else {
  32601. defines.push("#define DIFFUSE_COLOR_RENDER");
  32602. }
  32603. }
  32604. defines.push("#define NEED_UV");
  32605. needUV = true;
  32606. }
  32607. // Alpha test
  32608. if (material) {
  32609. if (material.needAlphaTesting()) {
  32610. defines.push("#define ALPHATEST");
  32611. }
  32612. if (material.opacityTexture !== undefined) {
  32613. defines.push("#define OPACITY");
  32614. if (material.opacityTexture.getAlphaFromRGB) {
  32615. defines.push("#define OPACITYRGB");
  32616. }
  32617. if (!needUV) {
  32618. defines.push("#define NEED_UV");
  32619. }
  32620. }
  32621. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32622. attribs.push(BABYLON.VertexBuffer.UVKind);
  32623. defines.push("#define UV1");
  32624. }
  32625. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32626. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32627. defines.push("#define UV2");
  32628. }
  32629. }
  32630. // Bones
  32631. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32632. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32633. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32634. defines.push("#define BONES");
  32635. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32636. }
  32637. // Instances
  32638. if (useInstances) {
  32639. defines.push("#define INSTANCES");
  32640. attribs.push("world0");
  32641. attribs.push("world1");
  32642. attribs.push("world2");
  32643. attribs.push("world3");
  32644. }
  32645. // Get correct effect
  32646. var join = defines.join("\n");
  32647. if (this._cachedDefines !== join) {
  32648. this._cachedDefines = join;
  32649. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  32650. }
  32651. return this._volumetricLightScatteringPass.isReady();
  32652. };
  32653. /**
  32654. * Sets the new light position for light scattering effect
  32655. * @param {BABYLON.Vector3} The new custom light position
  32656. */
  32657. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  32658. this._customMeshPosition = position;
  32659. };
  32660. /**
  32661. * Returns the light position for light scattering effect
  32662. * @return {BABYLON.Vector3} The custom light position
  32663. */
  32664. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  32665. return this._customMeshPosition;
  32666. };
  32667. /**
  32668. * Disposes the internal assets and detaches the post-process from the camera
  32669. */
  32670. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  32671. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  32672. if (rttIndex !== -1) {
  32673. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  32674. }
  32675. this._volumetricLightScatteringRTT.dispose();
  32676. _super.prototype.dispose.call(this, camera);
  32677. };
  32678. /**
  32679. * Returns the render target texture used by the post-process
  32680. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  32681. */
  32682. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  32683. return this._volumetricLightScatteringRTT;
  32684. };
  32685. // Private methods
  32686. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  32687. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  32688. return true;
  32689. }
  32690. return false;
  32691. };
  32692. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  32693. var _this = this;
  32694. var engine = scene.getEngine();
  32695. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  32696. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32697. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32698. this._volumetricLightScatteringRTT.renderList = null;
  32699. this._volumetricLightScatteringRTT.renderParticles = false;
  32700. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  32701. // Custom render function for submeshes
  32702. var renderSubMesh = function (subMesh) {
  32703. var mesh = subMesh.getRenderingMesh();
  32704. if (_this._meshExcluded(mesh)) {
  32705. return;
  32706. }
  32707. var scene = mesh.getScene();
  32708. var engine = scene.getEngine();
  32709. // Culling
  32710. engine.setState(subMesh.getMaterial().backFaceCulling);
  32711. // Managing instances
  32712. var batch = mesh._getInstancesRenderList(subMesh._id);
  32713. if (batch.mustReturn) {
  32714. return;
  32715. }
  32716. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32717. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32718. engine.enableEffect(_this._volumetricLightScatteringPass);
  32719. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  32720. var material = subMesh.getMaterial();
  32721. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  32722. // Alpha test
  32723. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  32724. var alphaTexture = material.getAlphaTestTexture();
  32725. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  32726. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  32727. }
  32728. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  32729. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  32730. if (alphaTexture) {
  32731. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32732. }
  32733. }
  32734. if (material.opacityTexture !== undefined) {
  32735. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  32736. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  32737. }
  32738. }
  32739. // Bones
  32740. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32741. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32742. }
  32743. // Draw
  32744. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  32745. }
  32746. };
  32747. // Render target texture callbacks
  32748. var savedSceneClearColor;
  32749. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  32750. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  32751. savedSceneClearColor = scene.clearColor;
  32752. scene.clearColor = sceneClearColor;
  32753. };
  32754. this._volumetricLightScatteringRTT.onAfterRender = function () {
  32755. scene.clearColor = savedSceneClearColor;
  32756. };
  32757. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  32758. var engine = scene.getEngine();
  32759. var index;
  32760. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32761. renderSubMesh(opaqueSubMeshes.data[index]);
  32762. }
  32763. engine.setAlphaTesting(true);
  32764. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32765. renderSubMesh(alphaTestSubMeshes.data[index]);
  32766. }
  32767. engine.setAlphaTesting(false);
  32768. if (transparentSubMeshes.length) {
  32769. // Sort sub meshes
  32770. for (index = 0; index < transparentSubMeshes.length; index++) {
  32771. var submesh = transparentSubMeshes.data[index];
  32772. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  32773. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  32774. }
  32775. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  32776. sortedArray.sort(function (a, b) {
  32777. // Alpha index first
  32778. if (a._alphaIndex > b._alphaIndex) {
  32779. return 1;
  32780. }
  32781. if (a._alphaIndex < b._alphaIndex) {
  32782. return -1;
  32783. }
  32784. // Then distance to camera
  32785. if (a._distanceToCamera < b._distanceToCamera) {
  32786. return 1;
  32787. }
  32788. if (a._distanceToCamera > b._distanceToCamera) {
  32789. return -1;
  32790. }
  32791. return 0;
  32792. });
  32793. // Render sub meshes
  32794. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32795. for (index = 0; index < sortedArray.length; index++) {
  32796. renderSubMesh(sortedArray[index]);
  32797. }
  32798. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32799. }
  32800. };
  32801. };
  32802. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  32803. var transform = scene.getTransformMatrix();
  32804. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  32805. this._screenCoordinates.x = pos.x / this._viewPort.width;
  32806. this._screenCoordinates.y = pos.y / this._viewPort.height;
  32807. if (this.invert)
  32808. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  32809. };
  32810. // Static methods
  32811. /**
  32812. * Creates a default mesh for the Volumeric Light Scattering post-process
  32813. * @param {string} The mesh name
  32814. * @param {BABYLON.Scene} The scene where to create the mesh
  32815. * @return {BABYLON.Mesh} the default mesh
  32816. */
  32817. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  32818. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  32819. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  32820. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  32821. return mesh;
  32822. };
  32823. return VolumetricLightScatteringPostProcess;
  32824. })(BABYLON.PostProcess);
  32825. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  32826. })(BABYLON || (BABYLON = {}));
  32827. var BABYLON;
  32828. (function (BABYLON) {
  32829. var LensRenderingPipeline = (function (_super) {
  32830. __extends(LensRenderingPipeline, _super);
  32831. /**
  32832. * @constructor
  32833. *
  32834. * Effect parameters are as follow:
  32835. * {
  32836. * chromatic_aberration: number; // from 0 to x (1 for realism)
  32837. * edge_blur: number; // from 0 to x (1 for realism)
  32838. * distortion: number; // from 0 to x (1 for realism)
  32839. * grain_amount: number; // from 0 to 1
  32840. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  32841. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  32842. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  32843. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  32844. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  32845. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  32846. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  32847. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  32848. * }
  32849. * Note: if an effect parameter is unset, effect is disabled
  32850. *
  32851. * @param {string} name - The rendering pipeline name
  32852. * @param {object} parameters - An object containing all parameters (see above)
  32853. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32854. * @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)
  32855. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32856. */
  32857. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  32858. var _this = this;
  32859. if (ratio === void 0) { ratio = 1.0; }
  32860. _super.call(this, scene.getEngine(), name);
  32861. // Lens effects can be of the following:
  32862. // - chromatic aberration (slight shift of RGB colors)
  32863. // - blur on the edge of the lens
  32864. // - lens distortion
  32865. // - depth-of-field blur & highlights enhancing
  32866. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  32867. // - grain effect (noise or custom texture)
  32868. // Two additional texture samplers are needed:
  32869. // - depth map (for depth-of-field)
  32870. // - grain texture
  32871. /**
  32872. * The chromatic aberration PostProcess id in the pipeline
  32873. * @type {string}
  32874. */
  32875. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  32876. /**
  32877. * The highlights enhancing PostProcess id in the pipeline
  32878. * @type {string}
  32879. */
  32880. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  32881. /**
  32882. * The depth-of-field PostProcess id in the pipeline
  32883. * @type {string}
  32884. */
  32885. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  32886. this._scene = scene;
  32887. // Fetch texture samplers
  32888. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32889. if (parameters.grain_texture) {
  32890. this._grainTexture = parameters.grain_texture;
  32891. }
  32892. else {
  32893. this._createGrainTexture();
  32894. }
  32895. // save parameters
  32896. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  32897. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  32898. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  32899. this._distortion = parameters.distortion ? parameters.distortion : 0;
  32900. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  32901. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  32902. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  32903. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  32904. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  32905. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  32906. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  32907. // Create effects
  32908. this._createChromaticAberrationPostProcess(ratio);
  32909. this._createHighlightsPostProcess(ratio);
  32910. this._createDepthOfFieldPostProcess(ratio / 4);
  32911. // Set up pipeline
  32912. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  32913. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  32914. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  32915. if (this._highlightsGain == -1) {
  32916. this._disableEffect(this.HighlightsEnhancingEffect, null);
  32917. }
  32918. // Finish
  32919. scene.postProcessRenderPipelineManager.addPipeline(this);
  32920. if (cameras) {
  32921. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32922. }
  32923. }
  32924. // public methods (self explanatory)
  32925. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  32926. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  32927. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  32928. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  32929. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  32930. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  32931. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  32932. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  32933. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  32934. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  32935. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  32936. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  32937. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  32938. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  32939. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  32940. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  32941. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  32942. this._highlightsGain = amount;
  32943. };
  32944. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  32945. if (this._highlightsGain == -1) {
  32946. this._highlightsGain = 1.0;
  32947. }
  32948. this._highlightsThreshold = amount;
  32949. };
  32950. LensRenderingPipeline.prototype.disableHighlights = function () {
  32951. this._highlightsGain = -1;
  32952. };
  32953. /**
  32954. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  32955. */
  32956. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32957. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32958. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32959. this._chromaticAberrationPostProcess = undefined;
  32960. this._highlightsPostProcess = undefined;
  32961. this._depthOfFieldPostProcess = undefined;
  32962. this._grainTexture.dispose();
  32963. if (disableDepthRender)
  32964. this._scene.disableDepthRenderer();
  32965. };
  32966. // colors shifting and distortion
  32967. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  32968. var _this = this;
  32969. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32970. this._chromaticAberrationPostProcess.onApply = function (effect) {
  32971. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  32972. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32973. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32974. };
  32975. };
  32976. // highlights enhancing
  32977. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  32978. var _this = this;
  32979. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32980. this._highlightsPostProcess.onApply = function (effect) {
  32981. effect.setFloat('gain', _this._highlightsGain);
  32982. effect.setFloat('threshold', _this._highlightsThreshold);
  32983. effect.setBool('pentagon', _this._dofPentagon);
  32984. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  32985. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32986. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32987. };
  32988. };
  32989. // colors shifting and distortion
  32990. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  32991. var _this = this;
  32992. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  32993. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  32994. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  32995. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32996. this._depthOfFieldPostProcess.onApply = function (effect) {
  32997. effect.setTexture("depthSampler", _this._depthTexture);
  32998. effect.setTexture("grainSampler", _this._grainTexture);
  32999. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  33000. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  33001. effect.setFloat('grain_amount', _this._grainAmount);
  33002. effect.setBool('blur_noise', _this._blurNoise);
  33003. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33004. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33005. effect.setFloat('distortion', _this._distortion);
  33006. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  33007. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  33008. effect.setFloat('aperture', _this._dofAperture);
  33009. effect.setFloat('darken', _this._dofDarken);
  33010. effect.setFloat('edge_blur', _this._edgeBlur);
  33011. effect.setBool('highlights', (_this._highlightsGain != -1));
  33012. effect.setFloat('near', _this._scene.activeCamera.minZ);
  33013. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  33014. };
  33015. };
  33016. // creates a black and white random noise texture, 512x512
  33017. LensRenderingPipeline.prototype._createGrainTexture = function () {
  33018. var size = 512;
  33019. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33020. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33021. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33022. var context = this._grainTexture.getContext();
  33023. var rand = function (min, max) {
  33024. return Math.random() * (max - min) + min;
  33025. };
  33026. var value;
  33027. for (var x = 0; x < size; x++) {
  33028. for (var y = 0; y < size; y++) {
  33029. value = Math.floor(rand(0.42, 0.58) * 255);
  33030. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  33031. context.fillRect(x, y, 1, 1);
  33032. }
  33033. }
  33034. this._grainTexture.update(false);
  33035. };
  33036. return LensRenderingPipeline;
  33037. })(BABYLON.PostProcessRenderPipeline);
  33038. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  33039. })(BABYLON || (BABYLON = {}));
  33040. //
  33041. // This post-process allows the modification of rendered colors by using
  33042. // a 'look-up table' (LUT). This effect is also called Color Grading.
  33043. //
  33044. // The object needs to be provided an url to a texture containing the color
  33045. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  33046. // Use an image editing software to tweak the LUT to match your needs.
  33047. //
  33048. // For an example of a color LUT, see here:
  33049. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  33050. // For explanations on color grading, see here:
  33051. // http://udn.epicgames.com/Three/ColorGrading.html
  33052. //
  33053. var BABYLON;
  33054. (function (BABYLON) {
  33055. var ColorCorrectionPostProcess = (function (_super) {
  33056. __extends(ColorCorrectionPostProcess, _super);
  33057. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  33058. var _this = this;
  33059. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  33060. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  33061. this._colorTableTexture.anisotropicFilteringLevel = 1;
  33062. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33063. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33064. this.onApply = function (effect) {
  33065. effect.setTexture("colorTable", _this._colorTableTexture);
  33066. };
  33067. }
  33068. return ColorCorrectionPostProcess;
  33069. })(BABYLON.PostProcess);
  33070. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  33071. })(BABYLON || (BABYLON = {}));
  33072. var BABYLON;
  33073. (function (BABYLON) {
  33074. var AnaglyphFreeCamera = (function (_super) {
  33075. __extends(AnaglyphFreeCamera, _super);
  33076. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  33077. _super.call(this, name, position, scene);
  33078. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33079. }
  33080. return AnaglyphFreeCamera;
  33081. })(BABYLON.FreeCamera);
  33082. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  33083. var AnaglyphArcRotateCamera = (function (_super) {
  33084. __extends(AnaglyphArcRotateCamera, _super);
  33085. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  33086. _super.call(this, name, alpha, beta, radius, target, scene);
  33087. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33088. }
  33089. return AnaglyphArcRotateCamera;
  33090. })(BABYLON.ArcRotateCamera);
  33091. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  33092. var AnaglyphGamepadCamera = (function (_super) {
  33093. __extends(AnaglyphGamepadCamera, _super);
  33094. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  33095. _super.call(this, name, position, scene);
  33096. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33097. }
  33098. return AnaglyphGamepadCamera;
  33099. })(BABYLON.GamepadCamera);
  33100. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  33101. var StereoscopicFreeCamera = (function (_super) {
  33102. __extends(StereoscopicFreeCamera, _super);
  33103. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33104. _super.call(this, name, position, scene);
  33105. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33106. }
  33107. return StereoscopicFreeCamera;
  33108. })(BABYLON.FreeCamera);
  33109. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  33110. var StereoscopicArcRotateCamera = (function (_super) {
  33111. __extends(StereoscopicArcRotateCamera, _super);
  33112. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  33113. _super.call(this, name, alpha, beta, radius, target, scene);
  33114. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33115. }
  33116. return StereoscopicArcRotateCamera;
  33117. })(BABYLON.ArcRotateCamera);
  33118. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  33119. var StereoscopicGamepadCamera = (function (_super) {
  33120. __extends(StereoscopicGamepadCamera, _super);
  33121. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33122. _super.call(this, name, position, scene);
  33123. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33124. }
  33125. return StereoscopicGamepadCamera;
  33126. })(BABYLON.GamepadCamera);
  33127. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  33128. })(BABYLON || (BABYLON = {}));
  33129. var BABYLON;
  33130. (function (BABYLON) {
  33131. var HDRRenderingPipeline = (function (_super) {
  33132. __extends(HDRRenderingPipeline, _super);
  33133. /**
  33134. * @constructor
  33135. * @param {string} name - The rendering pipeline name
  33136. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33137. * @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)
  33138. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  33139. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33140. */
  33141. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  33142. var _this = this;
  33143. if (originalPostProcess === void 0) { originalPostProcess = null; }
  33144. _super.call(this, scene.getEngine(), name);
  33145. /**
  33146. * Public members
  33147. */
  33148. // Gaussian Blur
  33149. /**
  33150. * Gaussian blur coefficient
  33151. * @type {number}
  33152. */
  33153. this.gaussCoeff = 0.3;
  33154. /**
  33155. * Gaussian blur mean
  33156. * @type {number}
  33157. */
  33158. this.gaussMean = 1.0;
  33159. /**
  33160. * Gaussian blur standard deviation
  33161. * @type {number}
  33162. */
  33163. this.gaussStandDev = 0.8;
  33164. // HDR
  33165. /**
  33166. * Exposure, controls the overall intensity of the pipeline
  33167. * @type {number}
  33168. */
  33169. this.exposure = 1.0;
  33170. /**
  33171. * Minimum luminance that the post-process can output. Luminance is >= 0
  33172. * @type {number}
  33173. */
  33174. this.minimumLuminance = 1.0;
  33175. /**
  33176. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  33177. * @type {number}
  33178. */
  33179. this.maximumLuminance = 1e20;
  33180. /**
  33181. * Increase rate for luminance: eye adaptation speed to dark
  33182. * @type {number}
  33183. */
  33184. this.luminanceIncreaserate = 0.5;
  33185. /**
  33186. * Decrease rate for luminance: eye adaptation speed to bright
  33187. * @type {number}
  33188. */
  33189. this.luminanceDecreaseRate = 0.5;
  33190. // Bright pass
  33191. /**
  33192. * Minimum luminance needed to compute HDR
  33193. * @type {number}
  33194. */
  33195. this.brightThreshold = 0.8;
  33196. this._needUpdate = true;
  33197. this._scene = scene;
  33198. // Bright pass
  33199. this._createBrightPassPostProcess(scene, ratio);
  33200. // Down sample X4
  33201. this._createDownSampleX4PostProcess(scene, ratio);
  33202. // Create gaussian blur post-processes
  33203. this._createGaussianBlurPostProcess(scene, ratio);
  33204. // Texture adder
  33205. this._createTextureAdderPostProcess(scene, ratio);
  33206. // Luminance generator
  33207. this._createLuminanceGeneratorPostProcess(scene);
  33208. // HDR
  33209. this._createHDRPostProcess(scene, ratio);
  33210. // Pass postprocess
  33211. if (originalPostProcess === null) {
  33212. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33213. }
  33214. else {
  33215. this._originalPostProcess = originalPostProcess;
  33216. }
  33217. // Configure pipeline
  33218. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  33219. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  33220. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  33221. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  33222. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  33223. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  33224. var addDownSamplerPostProcess = function (id) {
  33225. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  33226. };
  33227. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33228. addDownSamplerPostProcess(i);
  33229. }
  33230. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  33231. // Finish
  33232. scene.postProcessRenderPipelineManager.addPipeline(this);
  33233. if (cameras !== null) {
  33234. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33235. }
  33236. this.update();
  33237. }
  33238. /**
  33239. * Tells the pipeline to update its post-processes
  33240. */
  33241. HDRRenderingPipeline.prototype.update = function () {
  33242. this._needUpdate = true;
  33243. };
  33244. /**
  33245. * Returns the current calculated luminance
  33246. */
  33247. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33248. return this._hdrCurrentLuminance;
  33249. };
  33250. /**
  33251. * Returns the currently drawn luminance
  33252. */
  33253. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33254. return this._hdrOutputLuminance;
  33255. };
  33256. /**
  33257. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33258. */
  33259. HDRRenderingPipeline.prototype.dispose = function () {
  33260. this._originalPostProcess = undefined;
  33261. this._brightPassPostProcess = undefined;
  33262. this._downSampleX4PostProcess = undefined;
  33263. this._guassianBlurHPostProcess = undefined;
  33264. this._guassianBlurVPostProcess = undefined;
  33265. this._textureAdderPostProcess = undefined;
  33266. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33267. this._downSamplePostProcesses[i] = undefined;
  33268. }
  33269. this._hdrPostProcess = undefined;
  33270. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33271. };
  33272. /**
  33273. * Creates the HDR post-process and computes the luminance adaptation
  33274. */
  33275. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33276. var _this = this;
  33277. var hdrLastLuminance = 0.0;
  33278. this._hdrOutputLuminance = -1.0;
  33279. this._hdrCurrentLuminance = 1.0;
  33280. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33281. this._hdrPostProcess.onApply = function (effect) {
  33282. if (_this._hdrOutputLuminance < 0.0) {
  33283. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33284. }
  33285. else {
  33286. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33287. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33288. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33289. }
  33290. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33291. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33292. }
  33293. else {
  33294. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33295. }
  33296. }
  33297. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33298. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33299. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33300. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33301. effect.setFloat("exposure", _this.exposure);
  33302. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33303. _this._needUpdate = false;
  33304. };
  33305. };
  33306. /**
  33307. * Texture Adder post-process
  33308. */
  33309. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33310. var _this = this;
  33311. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33312. this._textureAdderPostProcess.onApply = function (effect) {
  33313. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33314. };
  33315. };
  33316. /**
  33317. * Down sample X4 post-process
  33318. */
  33319. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33320. var _this = this;
  33321. var downSampleX4Offsets = new Array(32);
  33322. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33323. this._downSampleX4PostProcess.onApply = function (effect) {
  33324. if (_this._needUpdate) {
  33325. var id = 0;
  33326. for (var i = -2; i < 2; i++) {
  33327. for (var j = -2; j < 2; j++) {
  33328. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33329. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33330. id += 2;
  33331. }
  33332. }
  33333. }
  33334. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33335. };
  33336. };
  33337. /**
  33338. * Bright pass post-process
  33339. */
  33340. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33341. var _this = this;
  33342. var brightOffsets = new Array(8);
  33343. var brightPassCallback = function (effect) {
  33344. if (_this._needUpdate) {
  33345. var sU = (1.0 / _this._brightPassPostProcess.width);
  33346. var sV = (1.0 / _this._brightPassPostProcess.height);
  33347. brightOffsets[0] = -0.5 * sU;
  33348. brightOffsets[1] = 0.5 * sV;
  33349. brightOffsets[2] = 0.5 * sU;
  33350. brightOffsets[3] = 0.5 * sV;
  33351. brightOffsets[4] = -0.5 * sU;
  33352. brightOffsets[5] = -0.5 * sV;
  33353. brightOffsets[6] = 0.5 * sU;
  33354. brightOffsets[7] = -0.5 * sV;
  33355. }
  33356. effect.setArray2("dsOffsets", brightOffsets);
  33357. effect.setFloat("brightThreshold", _this.brightThreshold);
  33358. };
  33359. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33360. this._brightPassPostProcess.onApply = brightPassCallback;
  33361. };
  33362. /**
  33363. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33364. */
  33365. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33366. var _this = this;
  33367. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33368. var luminanceOffsets = new Array(8);
  33369. var downSampleOffsets = new Array(18);
  33370. var halfDestPixelSize;
  33371. this._downSamplePostProcesses = new Array(lumSteps);
  33372. // Utils for luminance
  33373. var luminanceUpdateSourceOffsets = function (width, height) {
  33374. var sU = (1.0 / width);
  33375. var sV = (1.0 / height);
  33376. luminanceOffsets[0] = -0.5 * sU;
  33377. luminanceOffsets[1] = 0.5 * sV;
  33378. luminanceOffsets[2] = 0.5 * sU;
  33379. luminanceOffsets[3] = 0.5 * sV;
  33380. luminanceOffsets[4] = -0.5 * sU;
  33381. luminanceOffsets[5] = -0.5 * sV;
  33382. luminanceOffsets[6] = 0.5 * sU;
  33383. luminanceOffsets[7] = -0.5 * sV;
  33384. };
  33385. var luminanceUpdateDestOffsets = function (width, height) {
  33386. var id = 0;
  33387. for (var x = -1; x < 2; x++) {
  33388. for (var y = -1; y < 2; y++) {
  33389. downSampleOffsets[id] = (x) / width;
  33390. downSampleOffsets[id + 1] = (y) / height;
  33391. id += 2;
  33392. }
  33393. }
  33394. };
  33395. // Luminance callback
  33396. var luminanceCallback = function (effect) {
  33397. if (_this._needUpdate) {
  33398. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33399. }
  33400. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33401. effect.setArray2("lumOffsets", luminanceOffsets);
  33402. };
  33403. // Down sample callbacks
  33404. var downSampleCallback = function (indice) {
  33405. var i = indice;
  33406. return function (effect) {
  33407. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33408. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33409. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33410. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33411. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33412. effect.setArray2("dsOffsets", downSampleOffsets);
  33413. };
  33414. };
  33415. var downSampleAfterRenderCallback = function (effect) {
  33416. // Unpack result
  33417. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33418. 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);
  33419. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33420. };
  33421. // Create luminance post-process
  33422. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33423. 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);
  33424. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33425. // Create down sample post-processes
  33426. for (var i = lumSteps - 2; i >= 0; i--) {
  33427. var length = Math.pow(3, i);
  33428. ratio = { width: length, height: length };
  33429. var defines = "#define DOWN_SAMPLE\n";
  33430. if (i === 0) {
  33431. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33432. }
  33433. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33434. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33435. if (i === 0) {
  33436. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33437. }
  33438. }
  33439. };
  33440. /**
  33441. * Gaussian blur post-processes. Horizontal and Vertical
  33442. */
  33443. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33444. var _this = this;
  33445. var blurOffsetsW = new Array(9);
  33446. var blurOffsetsH = new Array(9);
  33447. var blurWeights = new Array(9);
  33448. var uniforms = ["blurOffsets", "blurWeights"];
  33449. // Utils for gaussian blur
  33450. var calculateBlurOffsets = function (height) {
  33451. var lastOutputDimensions = {
  33452. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33453. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33454. };
  33455. for (var i = 0; i < 9; i++) {
  33456. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33457. if (height) {
  33458. blurOffsetsH[i] = value;
  33459. }
  33460. else {
  33461. blurOffsetsW[i] = value;
  33462. }
  33463. }
  33464. };
  33465. var calculateWeights = function () {
  33466. var x = 0.0;
  33467. for (var i = 0; i < 9; i++) {
  33468. x = (i - 4.0) / 4.0;
  33469. 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));
  33470. }
  33471. };
  33472. // Callback
  33473. var gaussianBlurCallback = function (height) {
  33474. return function (effect) {
  33475. if (_this._needUpdate) {
  33476. calculateWeights();
  33477. calculateBlurOffsets(height);
  33478. }
  33479. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33480. effect.setArray("blurWeights", blurWeights);
  33481. };
  33482. };
  33483. // Create horizontal gaussian blur post-processes
  33484. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33485. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  33486. // Create vertical gaussian blur post-process
  33487. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  33488. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  33489. };
  33490. // Luminance generator
  33491. HDRRenderingPipeline.LUM_STEPS = 6;
  33492. return HDRRenderingPipeline;
  33493. })(BABYLON.PostProcessRenderPipeline);
  33494. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  33495. })(BABYLON || (BABYLON = {}));
  33496. var BABYLON;
  33497. (function (BABYLON) {
  33498. var FaceAdjacencies = (function () {
  33499. function FaceAdjacencies() {
  33500. this.edges = new Array();
  33501. this.edgesConnectedCount = 0;
  33502. }
  33503. return FaceAdjacencies;
  33504. })();
  33505. var EdgesRenderer = (function () {
  33506. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  33507. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  33508. if (epsilon === void 0) { epsilon = 0.95; }
  33509. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  33510. this._linesPositions = new Array();
  33511. this._linesNormals = new Array();
  33512. this._linesIndices = new Array();
  33513. this._buffers = new Array();
  33514. this._checkVerticesInsteadOfIndices = false;
  33515. this._source = source;
  33516. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  33517. this._epsilon = epsilon;
  33518. this._prepareRessources();
  33519. this._generateEdgesLines();
  33520. }
  33521. EdgesRenderer.prototype._prepareRessources = function () {
  33522. if (this._lineShader) {
  33523. return;
  33524. }
  33525. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  33526. attributes: ["position", "normal"],
  33527. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  33528. });
  33529. this._lineShader.disableDepthWrite = true;
  33530. this._lineShader.backFaceCulling = false;
  33531. };
  33532. EdgesRenderer.prototype.dispose = function () {
  33533. this._vb0.dispose();
  33534. this._vb1.dispose();
  33535. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  33536. this._lineShader.dispose();
  33537. };
  33538. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  33539. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  33540. return 0;
  33541. }
  33542. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  33543. return 1;
  33544. }
  33545. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  33546. return 2;
  33547. }
  33548. return -1;
  33549. };
  33550. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  33551. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  33552. return 0;
  33553. }
  33554. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  33555. return 1;
  33556. }
  33557. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  33558. return 2;
  33559. }
  33560. return -1;
  33561. };
  33562. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  33563. var needToCreateLine;
  33564. if (edge === undefined) {
  33565. needToCreateLine = true;
  33566. }
  33567. else {
  33568. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  33569. needToCreateLine = dotProduct < this._epsilon;
  33570. }
  33571. if (needToCreateLine) {
  33572. var offset = this._linesPositions.length / 3;
  33573. var normal = p0.subtract(p1);
  33574. normal.normalize();
  33575. // Positions
  33576. this._linesPositions.push(p0.x);
  33577. this._linesPositions.push(p0.y);
  33578. this._linesPositions.push(p0.z);
  33579. this._linesPositions.push(p0.x);
  33580. this._linesPositions.push(p0.y);
  33581. this._linesPositions.push(p0.z);
  33582. this._linesPositions.push(p1.x);
  33583. this._linesPositions.push(p1.y);
  33584. this._linesPositions.push(p1.z);
  33585. this._linesPositions.push(p1.x);
  33586. this._linesPositions.push(p1.y);
  33587. this._linesPositions.push(p1.z);
  33588. // Normals
  33589. this._linesNormals.push(p1.x);
  33590. this._linesNormals.push(p1.y);
  33591. this._linesNormals.push(p1.z);
  33592. this._linesNormals.push(-1);
  33593. this._linesNormals.push(p1.x);
  33594. this._linesNormals.push(p1.y);
  33595. this._linesNormals.push(p1.z);
  33596. this._linesNormals.push(1);
  33597. this._linesNormals.push(p0.x);
  33598. this._linesNormals.push(p0.y);
  33599. this._linesNormals.push(p0.z);
  33600. this._linesNormals.push(-1);
  33601. this._linesNormals.push(p0.x);
  33602. this._linesNormals.push(p0.y);
  33603. this._linesNormals.push(p0.z);
  33604. this._linesNormals.push(1);
  33605. // Indices
  33606. this._linesIndices.push(offset);
  33607. this._linesIndices.push(offset + 1);
  33608. this._linesIndices.push(offset + 2);
  33609. this._linesIndices.push(offset);
  33610. this._linesIndices.push(offset + 2);
  33611. this._linesIndices.push(offset + 3);
  33612. }
  33613. };
  33614. EdgesRenderer.prototype._generateEdgesLines = function () {
  33615. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33616. var indices = this._source.getIndices();
  33617. // First let's find adjacencies
  33618. var adjacencies = new Array();
  33619. var faceNormals = new Array();
  33620. var index;
  33621. var faceAdjacencies;
  33622. // Prepare faces
  33623. for (index = 0; index < indices.length; index += 3) {
  33624. faceAdjacencies = new FaceAdjacencies();
  33625. var p0Index = indices[index];
  33626. var p1Index = indices[index + 1];
  33627. var p2Index = indices[index + 2];
  33628. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  33629. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  33630. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  33631. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  33632. faceNormal.normalize();
  33633. faceNormals.push(faceNormal);
  33634. adjacencies.push(faceAdjacencies);
  33635. }
  33636. // Scan
  33637. for (index = 0; index < adjacencies.length; index++) {
  33638. faceAdjacencies = adjacencies[index];
  33639. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  33640. var otherFaceAdjacencies = adjacencies[otherIndex];
  33641. if (faceAdjacencies.edgesConnectedCount === 3) {
  33642. break;
  33643. }
  33644. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  33645. continue;
  33646. }
  33647. var otherP0 = indices[otherIndex * 3];
  33648. var otherP1 = indices[otherIndex * 3 + 1];
  33649. var otherP2 = indices[otherIndex * 3 + 2];
  33650. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  33651. var otherEdgeIndex;
  33652. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  33653. continue;
  33654. }
  33655. switch (edgeIndex) {
  33656. case 0:
  33657. if (this._checkVerticesInsteadOfIndices) {
  33658. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33659. }
  33660. else {
  33661. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  33662. }
  33663. break;
  33664. case 1:
  33665. if (this._checkVerticesInsteadOfIndices) {
  33666. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33667. }
  33668. else {
  33669. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  33670. }
  33671. break;
  33672. case 2:
  33673. if (this._checkVerticesInsteadOfIndices) {
  33674. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33675. }
  33676. else {
  33677. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  33678. }
  33679. break;
  33680. }
  33681. if (otherEdgeIndex === -1) {
  33682. continue;
  33683. }
  33684. faceAdjacencies.edges[edgeIndex] = otherIndex;
  33685. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  33686. faceAdjacencies.edgesConnectedCount++;
  33687. otherFaceAdjacencies.edgesConnectedCount++;
  33688. if (faceAdjacencies.edgesConnectedCount === 3) {
  33689. break;
  33690. }
  33691. }
  33692. }
  33693. }
  33694. // Create lines
  33695. for (index = 0; index < adjacencies.length; index++) {
  33696. // 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
  33697. var current = adjacencies[index];
  33698. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  33699. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  33700. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  33701. }
  33702. // Merge into a single mesh
  33703. var engine = this._source.getScene().getEngine();
  33704. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  33705. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  33706. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  33707. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  33708. this._ib = engine.createIndexBuffer(this._linesIndices);
  33709. this._indicesCount = this._linesIndices.length;
  33710. };
  33711. EdgesRenderer.prototype.render = function () {
  33712. if (!this._lineShader.isReady()) {
  33713. return;
  33714. }
  33715. var scene = this._source.getScene();
  33716. var engine = scene.getEngine();
  33717. this._lineShader._preBind();
  33718. // VBOs
  33719. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  33720. scene.resetCachedMaterial();
  33721. this._lineShader.setColor4("color", this._source.edgesColor);
  33722. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  33723. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  33724. this._lineShader.bind(this._source.getWorldMatrix());
  33725. // Draw order
  33726. engine.draw(true, 0, this._indicesCount);
  33727. this._lineShader.unbind();
  33728. engine.setDepthWrite(true);
  33729. };
  33730. return EdgesRenderer;
  33731. })();
  33732. BABYLON.EdgesRenderer = EdgesRenderer;
  33733. })(BABYLON || (BABYLON = {}));
  33734. var BABYLON;
  33735. (function (BABYLON) {
  33736. (function (TonemappingOperator) {
  33737. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  33738. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  33739. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  33740. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  33741. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  33742. var TonemappingOperator = BABYLON.TonemappingOperator;
  33743. ;
  33744. var TonemapPostProcess = (function (_super) {
  33745. __extends(TonemapPostProcess, _super);
  33746. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  33747. var _this = this;
  33748. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33749. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33750. this._operator = operator;
  33751. this._exposureAdjustment = exposureAdjustment;
  33752. var params = ["_ExposureAdjustment"];
  33753. var defines = "#define ";
  33754. if (operator === TonemappingOperator.Hable)
  33755. defines += "HABLE_TONEMAPPING";
  33756. else if (operator === TonemappingOperator.Reinhard)
  33757. defines += "REINHARD_TONEMAPPING";
  33758. else if (operator === TonemappingOperator.HejiDawson)
  33759. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  33760. else if (operator === TonemappingOperator.Photographic)
  33761. defines += "PHOTOGRAPHIC_TONEMAPPING";
  33762. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  33763. this.onApply = function (effect) {
  33764. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  33765. };
  33766. }
  33767. return TonemapPostProcess;
  33768. })(BABYLON.PostProcess);
  33769. BABYLON.TonemapPostProcess = TonemapPostProcess;
  33770. })(BABYLON || (BABYLON = {}));
  33771. 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#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\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#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// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\n#ifdef ROUGHNESS\r\nuniform float roughness;\r\n#endif\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\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\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\tfloat bias = 0.;\r\n\r\n#ifdef ROUGHNESS\r\n\t\tbias = roughness;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n#ifdef SPECULAR\r\n#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\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 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#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\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \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 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\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\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 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\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\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#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\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 REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\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\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\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\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, 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}","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}"};
  33772. 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.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=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,r;if(r=e.subMeshes,i=r.length,!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;i>s;s++){var l=r[s];i>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){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,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.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 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=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},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),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={}));";
  33773. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  33774. module.exports = BABYLON;
  33775. };