babylon.max.js 1.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  680. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  681. var m0 = SIMD.float32x4.load(transformation.m, 0);
  682. var m1 = SIMD.float32x4.load(transformation.m, 4);
  683. var m2 = SIMD.float32x4.load(transformation.m, 8);
  684. var m3 = SIMD.float32x4.load(transformation.m, 12);
  685. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  686. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  687. SIMD.float32x4.storeXYZ(result._data, 0, r);
  688. };
  689. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  690. var v0 = SIMD.float32x4.splat(x);
  691. var v1 = SIMD.float32x4.splat(y);
  692. var v2 = SIMD.float32x4.splat(z);
  693. var m0 = SIMD.float32x4.load(transformation.m, 0);
  694. var m1 = SIMD.float32x4.load(transformation.m, 4);
  695. var m2 = SIMD.float32x4.load(transformation.m, 8);
  696. var m3 = SIMD.float32x4.load(transformation.m, 12);
  697. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  698. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  699. SIMD.float32x4.storeXYZ(result._data, 0, r);
  700. };
  701. Vector3.TransformNormal = function (vector, transformation) {
  702. var result = Vector3.Zero();
  703. Vector3.TransformNormalToRef(vector, transformation, result);
  704. return result;
  705. };
  706. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  707. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  708. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  709. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  710. };
  711. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  712. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  713. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  714. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  715. };
  716. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  717. var squared = amount * amount;
  718. var cubed = amount * squared;
  719. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  720. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  721. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  722. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  723. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  724. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  725. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  726. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  727. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  728. return new Vector3(x, y, z);
  729. };
  730. Vector3.Clamp = function (value, min, max) {
  731. var x = value.x;
  732. x = (x > max.x) ? max.x : x;
  733. x = (x < min.x) ? min.x : x;
  734. var y = value.y;
  735. y = (y > max.y) ? max.y : y;
  736. y = (y < min.y) ? min.y : y;
  737. var z = value.z;
  738. z = (z > max.z) ? max.z : z;
  739. z = (z < min.z) ? min.z : z;
  740. return new Vector3(x, y, z);
  741. };
  742. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  743. var squared = amount * amount;
  744. var cubed = amount * squared;
  745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  747. var part3 = (cubed - (2.0 * squared)) + amount;
  748. var part4 = cubed - squared;
  749. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  750. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  751. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  752. return new Vector3(x, y, z);
  753. };
  754. Vector3.Lerp = function (start, end, amount) {
  755. var x = start.x + ((end.x - start.x) * amount);
  756. var y = start.y + ((end.y - start.y) * amount);
  757. var z = start.z + ((end.z - start.z) * amount);
  758. return new Vector3(x, y, z);
  759. };
  760. Vector3.Dot = function (left, right) {
  761. return (left.x * right.x + left.y * right.y + left.z * right.z);
  762. };
  763. Vector3.Cross = function (left, right) {
  764. var result = Vector3.Zero();
  765. Vector3.CrossToRef(left, right, result);
  766. return result;
  767. };
  768. Vector3.CrossToRef = function (left, right, result) {
  769. result.x = left.y * right.z - left.z * right.y;
  770. result.y = left.z * right.x - left.x * right.z;
  771. result.z = left.x * right.y - left.y * right.x;
  772. };
  773. Vector3.Normalize = function (vector) {
  774. var result = Vector3.Zero();
  775. Vector3.NormalizeToRef(vector, result);
  776. return result;
  777. };
  778. Vector3.NormalizeToRef = function (vector, result) {
  779. result.copyFrom(vector);
  780. result.normalize();
  781. };
  782. Vector3.Project = function (vector, world, transform, viewport) {
  783. var cw = viewport.width;
  784. var ch = viewport.height;
  785. var cx = viewport.x;
  786. var cy = viewport.y;
  787. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  788. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  789. return Vector3.TransformCoordinates(vector, finalMatrix);
  790. };
  791. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  792. var matrix = world.multiply(transform);
  793. matrix.invert();
  794. source.x = source.x / viewportWidth * 2 - 1;
  795. source.y = -(source.y / viewportHeight * 2 - 1);
  796. var vector = Vector3.TransformCoordinates(source, matrix);
  797. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  798. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  799. vector = vector.scale(1.0 / num);
  800. }
  801. return vector;
  802. };
  803. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  804. var matrix = world.multiply(view).multiply(projection);
  805. matrix.invert();
  806. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  807. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  808. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  809. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  810. vector = vector.scale(1.0 / num);
  811. }
  812. return vector;
  813. };
  814. Vector3.Minimize = function (left, right) {
  815. var min = left.clone();
  816. min.MinimizeInPlace(right);
  817. return min;
  818. };
  819. Vector3.Maximize = function (left, right) {
  820. var max = left.clone();
  821. max.MaximizeInPlace(right);
  822. return max;
  823. };
  824. Vector3.Distance = function (value1, value2) {
  825. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  826. };
  827. Vector3.DistanceSquared = function (value1, value2) {
  828. var x = value1.x - value2.x;
  829. var y = value1.y - value2.y;
  830. var z = value1.z - value2.z;
  831. return (x * x) + (y * y) + (z * z);
  832. };
  833. Vector3.Center = function (value1, value2) {
  834. var center = value1.add(value2);
  835. center.scaleInPlace(0.5);
  836. return center;
  837. };
  838. /**
  839. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  840. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  841. * to something in order to rotate it from its local system to the given target system.
  842. */
  843. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  844. var rotation = Vector3.Zero();
  845. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  846. return rotation;
  847. };
  848. /**
  849. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  850. */
  851. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  852. var u = Vector3.Normalize(axis1);
  853. var w = Vector3.Normalize(axis3);
  854. // world axis
  855. var X = Axis.X;
  856. var Y = Axis.Y;
  857. // equation unknowns and vars
  858. var yaw = 0.0;
  859. var pitch = 0.0;
  860. var roll = 0.0;
  861. var x = 0.0;
  862. var y = 0.0;
  863. var z = 0.0;
  864. var t = 0.0;
  865. var sign = -1.0;
  866. var nbRevert = 0;
  867. var cross;
  868. var dot = 0.0;
  869. // step 1 : rotation around w
  870. // Rv3(u) = u1, and u1 belongs to plane xOz
  871. // Rv3(w) = w1 = w invariant
  872. var u1;
  873. var v1;
  874. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  875. z = 1.0;
  876. }
  877. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  878. x = 1.0;
  879. }
  880. else {
  881. t = w.z / w.x;
  882. x = -t * Math.sqrt(1 / (1 + t * t));
  883. z = Math.sqrt(1 / (1 + t * t));
  884. }
  885. u1 = new Vector3(x, y, z);
  886. u1.normalize();
  887. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  888. v1.normalize();
  889. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  890. cross.normalize();
  891. if (Vector3.Dot(w, cross) < 0) {
  892. sign = 1.0;
  893. }
  894. dot = Vector3.Dot(u, u1);
  895. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  896. roll = Math.acos(dot) * sign;
  897. if (Vector3.Dot(u1, X) < 0) {
  898. roll = Math.PI + roll;
  899. u1 = u1.scaleInPlace(-1);
  900. v1 = v1.scaleInPlace(-1);
  901. nbRevert++;
  902. }
  903. // step 2 : rotate around u1
  904. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  905. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  906. var w2;
  907. var v2;
  908. x = 0.0;
  909. y = 0.0;
  910. z = 0.0;
  911. sign = -1;
  912. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  913. x = 1.0;
  914. }
  915. else {
  916. t = u1.z / u1.x;
  917. x = -t * Math.sqrt(1 / (1 + t * t));
  918. z = Math.sqrt(1 / (1 + t * t));
  919. }
  920. w2 = new Vector3(x, y, z);
  921. w2.normalize();
  922. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  923. v2.normalize();
  924. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  925. cross.normalize();
  926. if (Vector3.Dot(u1, cross) < 0) {
  927. sign = 1.0;
  928. }
  929. dot = Vector3.Dot(w, w2);
  930. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  931. pitch = Math.acos(dot) * sign;
  932. if (Vector3.Dot(v2, Y) < 0) {
  933. pitch = Math.PI + pitch;
  934. v2 = v2.scaleInPlace(-1);
  935. w2 = w2.scaleInPlace(-1);
  936. nbRevert++;
  937. }
  938. // step 3 : rotate around v2
  939. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  940. sign = -1;
  941. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(cross, Y) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(u1, X);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  949. if (dot < 0 && nbRevert < 2) {
  950. yaw = Math.PI + yaw;
  951. }
  952. ref.x = pitch;
  953. ref.y = yaw;
  954. ref.z = roll;
  955. };
  956. return Vector3;
  957. })();
  958. BABYLON.Vector3 = Vector3;
  959. //Vector4 class created for EulerAngle class conversion to Quaternion
  960. var Vector4 = (function () {
  961. function Vector4(x, y, z, w) {
  962. this.x = x;
  963. this.y = y;
  964. this.z = z;
  965. this.w = w;
  966. }
  967. Vector4.prototype.toString = function () {
  968. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  969. };
  970. // Operators
  971. Vector4.prototype.asArray = function () {
  972. var result = [];
  973. this.toArray(result, 0);
  974. return result;
  975. };
  976. Vector4.prototype.toArray = function (array, index) {
  977. if (index === undefined) {
  978. index = 0;
  979. }
  980. array[index] = this.x;
  981. array[index + 1] = this.y;
  982. array[index + 2] = this.z;
  983. array[index + 3] = this.w;
  984. return this;
  985. };
  986. Vector4.prototype.addInPlace = function (otherVector) {
  987. this.x += otherVector.x;
  988. this.y += otherVector.y;
  989. this.z += otherVector.z;
  990. this.w += otherVector.w;
  991. return this;
  992. };
  993. Vector4.prototype.add = function (otherVector) {
  994. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  995. };
  996. Vector4.prototype.addToRef = function (otherVector, result) {
  997. result.x = this.x + otherVector.x;
  998. result.y = this.y + otherVector.y;
  999. result.z = this.z + otherVector.z;
  1000. result.w = this.w + otherVector.w;
  1001. return this;
  1002. };
  1003. Vector4.prototype.subtractInPlace = function (otherVector) {
  1004. this.x -= otherVector.x;
  1005. this.y -= otherVector.y;
  1006. this.z -= otherVector.z;
  1007. this.w -= otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.subtract = function (otherVector) {
  1011. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1012. };
  1013. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1014. result.x = this.x - otherVector.x;
  1015. result.y = this.y - otherVector.y;
  1016. result.z = this.z - otherVector.z;
  1017. result.w = this.w - otherVector.w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1021. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1022. };
  1023. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1024. result.x = this.x - x;
  1025. result.y = this.y - y;
  1026. result.z = this.z - z;
  1027. result.w = this.w - w;
  1028. return this;
  1029. };
  1030. Vector4.prototype.negate = function () {
  1031. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1032. };
  1033. Vector4.prototype.scaleInPlace = function (scale) {
  1034. this.x *= scale;
  1035. this.y *= scale;
  1036. this.z *= scale;
  1037. this.w *= scale;
  1038. return this;
  1039. };
  1040. Vector4.prototype.scale = function (scale) {
  1041. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1042. };
  1043. Vector4.prototype.scaleToRef = function (scale, result) {
  1044. result.x = this.x * scale;
  1045. result.y = this.y * scale;
  1046. result.z = this.z * scale;
  1047. result.w = this.w * scale;
  1048. };
  1049. Vector4.prototype.equals = function (otherVector) {
  1050. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1051. };
  1052. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1053. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1054. return otherVector
  1055. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1056. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1057. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1058. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1059. };
  1060. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1061. return this.x === x && this.y === y && this.z === z && this.w === w;
  1062. };
  1063. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1064. this.x *= otherVector.x;
  1065. this.y *= otherVector.y;
  1066. this.z *= otherVector.z;
  1067. this.w *= otherVector.w;
  1068. return this;
  1069. };
  1070. Vector4.prototype.multiply = function (otherVector) {
  1071. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1072. };
  1073. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1074. result.x = this.x * otherVector.x;
  1075. result.y = this.y * otherVector.y;
  1076. result.z = this.z * otherVector.z;
  1077. result.w = this.w * otherVector.w;
  1078. return this;
  1079. };
  1080. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1081. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1082. };
  1083. Vector4.prototype.divide = function (otherVector) {
  1084. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1085. };
  1086. Vector4.prototype.divideToRef = function (otherVector, result) {
  1087. result.x = this.x / otherVector.x;
  1088. result.y = this.y / otherVector.y;
  1089. result.z = this.z / otherVector.z;
  1090. result.w = this.w / otherVector.w;
  1091. return this;
  1092. };
  1093. Vector4.prototype.MinimizeInPlace = function (other) {
  1094. if (other.x < this.x)
  1095. this.x = other.x;
  1096. if (other.y < this.y)
  1097. this.y = other.y;
  1098. if (other.z < this.z)
  1099. this.z = other.z;
  1100. if (other.w < this.w)
  1101. this.w = other.w;
  1102. return this;
  1103. };
  1104. Vector4.prototype.MaximizeInPlace = function (other) {
  1105. if (other.x > this.x)
  1106. this.x = other.x;
  1107. if (other.y > this.y)
  1108. this.y = other.y;
  1109. if (other.z > this.z)
  1110. this.z = other.z;
  1111. if (other.w > this.w)
  1112. this.w = other.w;
  1113. return this;
  1114. };
  1115. // Properties
  1116. Vector4.prototype.length = function () {
  1117. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1118. };
  1119. Vector4.prototype.lengthSquared = function () {
  1120. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1121. };
  1122. // Methods
  1123. Vector4.prototype.normalize = function () {
  1124. var len = this.length();
  1125. if (len === 0)
  1126. return this;
  1127. var num = 1.0 / len;
  1128. this.x *= num;
  1129. this.y *= num;
  1130. this.z *= num;
  1131. this.w *= num;
  1132. return this;
  1133. };
  1134. Vector4.prototype.clone = function () {
  1135. return new Vector4(this.x, this.y, this.z, this.w);
  1136. };
  1137. Vector4.prototype.copyFrom = function (source) {
  1138. this.x = source.x;
  1139. this.y = source.y;
  1140. this.z = source.z;
  1141. this.w = source.w;
  1142. return this;
  1143. };
  1144. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1145. this.x = x;
  1146. this.y = y;
  1147. this.z = z;
  1148. this.w = w;
  1149. return this;
  1150. };
  1151. // Statics
  1152. Vector4.FromArray = function (array, offset) {
  1153. if (!offset) {
  1154. offset = 0;
  1155. }
  1156. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1157. };
  1158. Vector4.FromArrayToRef = function (array, offset, result) {
  1159. result.x = array[offset];
  1160. result.y = array[offset + 1];
  1161. result.z = array[offset + 2];
  1162. result.w = array[offset + 3];
  1163. };
  1164. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1165. result.x = array[offset];
  1166. result.y = array[offset + 1];
  1167. result.z = array[offset + 2];
  1168. result.w = array[offset + 3];
  1169. };
  1170. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1171. result.x = x;
  1172. result.y = y;
  1173. result.z = z;
  1174. result.w = w;
  1175. };
  1176. Vector4.Zero = function () {
  1177. return new Vector4(0, 0, 0, 0);
  1178. };
  1179. Vector4.Normalize = function (vector) {
  1180. var result = Vector4.Zero();
  1181. Vector4.NormalizeToRef(vector, result);
  1182. return result;
  1183. };
  1184. Vector4.NormalizeToRef = function (vector, result) {
  1185. result.copyFrom(vector);
  1186. result.normalize();
  1187. };
  1188. Vector4.Minimize = function (left, right) {
  1189. var min = left.clone();
  1190. min.MinimizeInPlace(right);
  1191. return min;
  1192. };
  1193. Vector4.Maximize = function (left, right) {
  1194. var max = left.clone();
  1195. max.MaximizeInPlace(right);
  1196. return max;
  1197. };
  1198. Vector4.Distance = function (value1, value2) {
  1199. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1200. };
  1201. Vector4.DistanceSquared = function (value1, value2) {
  1202. var x = value1.x - value2.x;
  1203. var y = value1.y - value2.y;
  1204. var z = value1.z - value2.z;
  1205. var w = value1.w - value2.w;
  1206. return (x * x) + (y * y) + (z * z) + (w * w);
  1207. };
  1208. Vector4.Center = function (value1, value2) {
  1209. var center = value1.add(value2);
  1210. center.scaleInPlace(0.5);
  1211. return center;
  1212. };
  1213. return Vector4;
  1214. })();
  1215. BABYLON.Vector4 = Vector4;
  1216. var Quaternion = (function () {
  1217. function Quaternion(x, y, z, w) {
  1218. if (x === void 0) { x = 0; }
  1219. if (y === void 0) { y = 0; }
  1220. if (z === void 0) { z = 0; }
  1221. if (w === void 0) { w = 1; }
  1222. this.x = x;
  1223. this.y = y;
  1224. this.z = z;
  1225. this.w = w;
  1226. }
  1227. Quaternion.prototype.toString = function () {
  1228. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1229. };
  1230. Quaternion.prototype.asArray = function () {
  1231. return [this.x, this.y, this.z, this.w];
  1232. };
  1233. Quaternion.prototype.equals = function (otherQuaternion) {
  1234. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1235. };
  1236. Quaternion.prototype.clone = function () {
  1237. return new Quaternion(this.x, this.y, this.z, this.w);
  1238. };
  1239. Quaternion.prototype.copyFrom = function (other) {
  1240. this.x = other.x;
  1241. this.y = other.y;
  1242. this.z = other.z;
  1243. this.w = other.w;
  1244. return this;
  1245. };
  1246. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1247. this.x = x;
  1248. this.y = y;
  1249. this.z = z;
  1250. this.w = w;
  1251. return this;
  1252. };
  1253. Quaternion.prototype.add = function (other) {
  1254. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1255. };
  1256. Quaternion.prototype.subtract = function (other) {
  1257. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1258. };
  1259. Quaternion.prototype.scale = function (value) {
  1260. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1261. };
  1262. Quaternion.prototype.multiply = function (q1) {
  1263. var result = new Quaternion(0, 0, 0, 1.0);
  1264. this.multiplyToRef(q1, result);
  1265. return result;
  1266. };
  1267. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1268. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1269. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1270. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1271. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1272. result.copyFromFloats(x, y, z, w);
  1273. return this;
  1274. };
  1275. Quaternion.prototype.length = function () {
  1276. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1277. };
  1278. Quaternion.prototype.normalize = function () {
  1279. var length = 1.0 / this.length();
  1280. this.x *= length;
  1281. this.y *= length;
  1282. this.z *= length;
  1283. this.w *= length;
  1284. return this;
  1285. };
  1286. Quaternion.prototype.toEulerAngles = function () {
  1287. var result = Vector3.Zero();
  1288. this.toEulerAnglesToRef(result);
  1289. return result;
  1290. };
  1291. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1292. //result is an EulerAngles in the in the z-x-z convention
  1293. var qx = this.x;
  1294. var qy = this.y;
  1295. var qz = this.z;
  1296. var qw = this.w;
  1297. var qxy = qx * qy;
  1298. var qxz = qx * qz;
  1299. var qwy = qw * qy;
  1300. var qwz = qw * qz;
  1301. var qwx = qw * qx;
  1302. var qyz = qy * qz;
  1303. var sqx = qx * qx;
  1304. var sqy = qy * qy;
  1305. var determinant = sqx + sqy;
  1306. if (determinant !== 0.000 && determinant !== 1.000) {
  1307. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1308. result.y = Math.acos(1 - 2 * determinant);
  1309. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1310. }
  1311. else {
  1312. if (determinant === 0.0) {
  1313. result.x = 0.0;
  1314. result.y = 0.0;
  1315. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1316. }
  1317. else {
  1318. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1319. result.y = Math.PI;
  1320. result.z = 0.0;
  1321. }
  1322. }
  1323. return this;
  1324. };
  1325. Quaternion.prototype.toRotationMatrix = function (result) {
  1326. var xx = this.x * this.x;
  1327. var yy = this.y * this.y;
  1328. var zz = this.z * this.z;
  1329. var xy = this.x * this.y;
  1330. var zw = this.z * this.w;
  1331. var zx = this.z * this.x;
  1332. var yw = this.y * this.w;
  1333. var yz = this.y * this.z;
  1334. var xw = this.x * this.w;
  1335. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1336. result.m[1] = 2.0 * (xy + zw);
  1337. result.m[2] = 2.0 * (zx - yw);
  1338. result.m[3] = 0;
  1339. result.m[4] = 2.0 * (xy - zw);
  1340. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1341. result.m[6] = 2.0 * (yz + xw);
  1342. result.m[7] = 0;
  1343. result.m[8] = 2.0 * (zx + yw);
  1344. result.m[9] = 2.0 * (yz - xw);
  1345. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1346. result.m[11] = 0;
  1347. result.m[12] = 0;
  1348. result.m[13] = 0;
  1349. result.m[14] = 0;
  1350. result.m[15] = 1.0;
  1351. return this;
  1352. };
  1353. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1354. Quaternion.FromRotationMatrixToRef(matrix, this);
  1355. return this;
  1356. };
  1357. // Statics
  1358. Quaternion.FromRotationMatrix = function (matrix) {
  1359. var result = new Quaternion();
  1360. Quaternion.FromRotationMatrixToRef(matrix, result);
  1361. return result;
  1362. };
  1363. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1364. var data = matrix.m;
  1365. var m11 = data[0], m12 = data[4], m13 = data[8];
  1366. var m21 = data[1], m22 = data[5], m23 = data[9];
  1367. var m31 = data[2], m32 = data[6], m33 = data[10];
  1368. var trace = m11 + m22 + m33;
  1369. var s;
  1370. if (trace > 0) {
  1371. s = 0.5 / Math.sqrt(trace + 1.0);
  1372. result.w = 0.25 / s;
  1373. result.x = (m32 - m23) * s;
  1374. result.y = (m13 - m31) * s;
  1375. result.z = (m21 - m12) * s;
  1376. }
  1377. else if (m11 > m22 && m11 > m33) {
  1378. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1379. result.w = (m32 - m23) / s;
  1380. result.x = 0.25 * s;
  1381. result.y = (m12 + m21) / s;
  1382. result.z = (m13 + m31) / s;
  1383. }
  1384. else if (m22 > m33) {
  1385. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1386. result.w = (m13 - m31) / s;
  1387. result.x = (m12 + m21) / s;
  1388. result.y = 0.25 * s;
  1389. result.z = (m23 + m32) / s;
  1390. }
  1391. else {
  1392. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1393. result.w = (m21 - m12) / s;
  1394. result.x = (m13 + m31) / s;
  1395. result.y = (m23 + m32) / s;
  1396. result.z = 0.25 * s;
  1397. }
  1398. };
  1399. Quaternion.Inverse = function (q) {
  1400. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1401. };
  1402. Quaternion.Identity = function () {
  1403. return new Quaternion(0, 0, 0, 1);
  1404. };
  1405. Quaternion.RotationAxis = function (axis, angle) {
  1406. var result = new Quaternion();
  1407. var sin = Math.sin(angle / 2);
  1408. axis.normalize();
  1409. result.w = Math.cos(angle / 2);
  1410. result.x = axis.x * sin;
  1411. result.y = axis.y * sin;
  1412. result.z = axis.z * sin;
  1413. return result;
  1414. };
  1415. Quaternion.FromArray = function (array, offset) {
  1416. if (!offset) {
  1417. offset = 0;
  1418. }
  1419. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1420. };
  1421. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1422. var result = new Quaternion();
  1423. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1424. return result;
  1425. };
  1426. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1427. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1428. var halfRoll = roll * 0.5;
  1429. var halfPitch = pitch * 0.5;
  1430. var halfYaw = yaw * 0.5;
  1431. var sinRoll = Math.sin(halfRoll);
  1432. var cosRoll = Math.cos(halfRoll);
  1433. var sinPitch = Math.sin(halfPitch);
  1434. var cosPitch = Math.cos(halfPitch);
  1435. var sinYaw = Math.sin(halfYaw);
  1436. var cosYaw = Math.cos(halfYaw);
  1437. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1438. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1439. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1440. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1441. };
  1442. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1448. // Produces a quaternion from Euler angles in the z-x-z orientation
  1449. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1450. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1451. var halfBeta = beta * 0.5;
  1452. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1453. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1454. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1455. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1456. };
  1457. Quaternion.Slerp = function (left, right, amount) {
  1458. var num2;
  1459. var num3;
  1460. var num = amount;
  1461. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1462. var flag = false;
  1463. if (num4 < 0) {
  1464. flag = true;
  1465. num4 = -num4;
  1466. }
  1467. if (num4 > 0.999999) {
  1468. num3 = 1 - num;
  1469. num2 = flag ? -num : num;
  1470. }
  1471. else {
  1472. var num5 = Math.acos(num4);
  1473. var num6 = (1.0 / Math.sin(num5));
  1474. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1475. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1476. }
  1477. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1478. };
  1479. return Quaternion;
  1480. })();
  1481. BABYLON.Quaternion = Quaternion;
  1482. var Matrix = (function () {
  1483. function Matrix() {
  1484. this.m = new Float32Array(16);
  1485. }
  1486. // Properties
  1487. Matrix.prototype.isIdentity = function () {
  1488. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1489. return false;
  1490. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1491. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1492. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1493. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1494. return false;
  1495. return true;
  1496. };
  1497. Matrix.prototype.determinant = function () {
  1498. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1499. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1500. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1501. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1502. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1503. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1504. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1505. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1506. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1507. };
  1508. // Methods
  1509. Matrix.prototype.toArray = function () {
  1510. return this.m;
  1511. };
  1512. Matrix.prototype.asArray = function () {
  1513. return this.toArray();
  1514. };
  1515. Matrix.prototype.invert = function () {
  1516. this.invertToRef(this);
  1517. return this;
  1518. };
  1519. Matrix.prototype.reset = function () {
  1520. for (var index = 0; index < 16; index++) {
  1521. this.m[index] = 0;
  1522. }
  1523. return this;
  1524. };
  1525. Matrix.prototype.add = function (other) {
  1526. var result = new Matrix();
  1527. this.addToRef(other, result);
  1528. return result;
  1529. };
  1530. Matrix.prototype.addToRef = function (other, result) {
  1531. for (var index = 0; index < 16; index++) {
  1532. result.m[index] = this.m[index] + other.m[index];
  1533. }
  1534. return this;
  1535. };
  1536. Matrix.prototype.addToSelf = function (other) {
  1537. for (var index = 0; index < 16; index++) {
  1538. this.m[index] += other.m[index];
  1539. }
  1540. return this;
  1541. };
  1542. Matrix.prototype.invertToRef = function (other) {
  1543. var l1 = this.m[0];
  1544. var l2 = this.m[1];
  1545. var l3 = this.m[2];
  1546. var l4 = this.m[3];
  1547. var l5 = this.m[4];
  1548. var l6 = this.m[5];
  1549. var l7 = this.m[6];
  1550. var l8 = this.m[7];
  1551. var l9 = this.m[8];
  1552. var l10 = this.m[9];
  1553. var l11 = this.m[10];
  1554. var l12 = this.m[11];
  1555. var l13 = this.m[12];
  1556. var l14 = this.m[13];
  1557. var l15 = this.m[14];
  1558. var l16 = this.m[15];
  1559. var l17 = (l11 * l16) - (l12 * l15);
  1560. var l18 = (l10 * l16) - (l12 * l14);
  1561. var l19 = (l10 * l15) - (l11 * l14);
  1562. var l20 = (l9 * l16) - (l12 * l13);
  1563. var l21 = (l9 * l15) - (l11 * l13);
  1564. var l22 = (l9 * l14) - (l10 * l13);
  1565. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1566. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1567. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1568. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1569. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1570. var l28 = (l7 * l16) - (l8 * l15);
  1571. var l29 = (l6 * l16) - (l8 * l14);
  1572. var l30 = (l6 * l15) - (l7 * l14);
  1573. var l31 = (l5 * l16) - (l8 * l13);
  1574. var l32 = (l5 * l15) - (l7 * l13);
  1575. var l33 = (l5 * l14) - (l6 * l13);
  1576. var l34 = (l7 * l12) - (l8 * l11);
  1577. var l35 = (l6 * l12) - (l8 * l10);
  1578. var l36 = (l6 * l11) - (l7 * l10);
  1579. var l37 = (l5 * l12) - (l8 * l9);
  1580. var l38 = (l5 * l11) - (l7 * l9);
  1581. var l39 = (l5 * l10) - (l6 * l9);
  1582. other.m[0] = l23 * l27;
  1583. other.m[4] = l24 * l27;
  1584. other.m[8] = l25 * l27;
  1585. other.m[12] = l26 * l27;
  1586. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1587. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1588. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1589. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1590. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1591. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1592. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1593. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1594. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1595. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1596. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1597. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1598. return this;
  1599. };
  1600. Matrix.prototype.invertToRefSIMD = function (other) {
  1601. var src = this.m;
  1602. var dest = other.m;
  1603. var row0, row1, row2, row3;
  1604. var tmp1;
  1605. var minor0, minor1, minor2, minor3;
  1606. var det;
  1607. // Load the 4 rows
  1608. var src0 = SIMD.float32x4.load(src, 0);
  1609. var src1 = SIMD.float32x4.load(src, 4);
  1610. var src2 = SIMD.float32x4.load(src, 8);
  1611. var src3 = SIMD.float32x4.load(src, 12);
  1612. // Transpose the source matrix. Sort of. Not a true transpose operation
  1613. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1614. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1615. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1616. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1617. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1618. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1619. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1620. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1621. // This is a true transposition, but it will lead to an incorrect result
  1622. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1623. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1624. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1625. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1626. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1627. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1628. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1629. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1630. // ----
  1631. tmp1 = SIMD.float32x4.mul(row2, row3);
  1632. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1633. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1634. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1635. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1636. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1637. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1638. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1639. // ----
  1640. tmp1 = SIMD.float32x4.mul(row1, row2);
  1641. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1642. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1643. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1644. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1645. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1646. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1647. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1648. // ----
  1649. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1650. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1651. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1652. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1653. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1654. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1655. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1656. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1657. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1658. // ----
  1659. tmp1 = SIMD.float32x4.mul(row0, row1);
  1660. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1661. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1662. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1663. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1664. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1665. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1666. // ----
  1667. tmp1 = SIMD.float32x4.mul(row0, row3);
  1668. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1669. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1670. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1671. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1672. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1673. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1674. // ----
  1675. tmp1 = SIMD.float32x4.mul(row0, row2);
  1676. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1677. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1678. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1679. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1680. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1681. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1682. // Compute determinant
  1683. det = SIMD.float32x4.mul(row0, minor0);
  1684. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1685. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1686. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1687. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1688. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1689. // These shuffles aren't necessary if the faulty transposition is done
  1690. // up at the top of this function.
  1691. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1692. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1693. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1694. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1695. // Compute final values by multiplying with 1/det
  1696. minor0 = SIMD.float32x4.mul(det, minor0);
  1697. minor1 = SIMD.float32x4.mul(det, minor1);
  1698. minor2 = SIMD.float32x4.mul(det, minor2);
  1699. minor3 = SIMD.float32x4.mul(det, minor3);
  1700. SIMD.float32x4.store(dest, 0, minor0);
  1701. SIMD.float32x4.store(dest, 4, minor1);
  1702. SIMD.float32x4.store(dest, 8, minor2);
  1703. SIMD.float32x4.store(dest, 12, minor3);
  1704. return this;
  1705. };
  1706. Matrix.prototype.setTranslation = function (vector3) {
  1707. this.m[12] = vector3.x;
  1708. this.m[13] = vector3.y;
  1709. this.m[14] = vector3.z;
  1710. return this;
  1711. };
  1712. Matrix.prototype.multiply = function (other) {
  1713. var result = new Matrix();
  1714. this.multiplyToRef(other, result);
  1715. return result;
  1716. };
  1717. Matrix.prototype.copyFrom = function (other) {
  1718. for (var index = 0; index < 16; index++) {
  1719. this.m[index] = other.m[index];
  1720. }
  1721. return this;
  1722. };
  1723. Matrix.prototype.copyToArray = function (array, offset) {
  1724. if (offset === void 0) { offset = 0; }
  1725. for (var index = 0; index < 16; index++) {
  1726. array[offset + index] = this.m[index];
  1727. }
  1728. return this;
  1729. };
  1730. Matrix.prototype.multiplyToRef = function (other, result) {
  1731. this.multiplyToArray(other, result.m, 0);
  1732. return this;
  1733. };
  1734. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1735. var tm0 = this.m[0];
  1736. var tm1 = this.m[1];
  1737. var tm2 = this.m[2];
  1738. var tm3 = this.m[3];
  1739. var tm4 = this.m[4];
  1740. var tm5 = this.m[5];
  1741. var tm6 = this.m[6];
  1742. var tm7 = this.m[7];
  1743. var tm8 = this.m[8];
  1744. var tm9 = this.m[9];
  1745. var tm10 = this.m[10];
  1746. var tm11 = this.m[11];
  1747. var tm12 = this.m[12];
  1748. var tm13 = this.m[13];
  1749. var tm14 = this.m[14];
  1750. var tm15 = this.m[15];
  1751. var om0 = other.m[0];
  1752. var om1 = other.m[1];
  1753. var om2 = other.m[2];
  1754. var om3 = other.m[3];
  1755. var om4 = other.m[4];
  1756. var om5 = other.m[5];
  1757. var om6 = other.m[6];
  1758. var om7 = other.m[7];
  1759. var om8 = other.m[8];
  1760. var om9 = other.m[9];
  1761. var om10 = other.m[10];
  1762. var om11 = other.m[11];
  1763. var om12 = other.m[12];
  1764. var om13 = other.m[13];
  1765. var om14 = other.m[14];
  1766. var om15 = other.m[15];
  1767. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1768. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1769. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1770. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1771. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1772. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1773. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1774. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1775. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1776. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1777. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1778. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1779. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1780. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1781. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1782. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1783. return this;
  1784. };
  1785. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1786. if (offset === void 0) { offset = 0; }
  1787. var tm = this.m;
  1788. var om = other.m;
  1789. var om0 = SIMD.float32x4.load(om, 0);
  1790. var om1 = SIMD.float32x4.load(om, 4);
  1791. var om2 = SIMD.float32x4.load(om, 8);
  1792. var om3 = SIMD.float32x4.load(om, 12);
  1793. var tm0 = SIMD.float32x4.load(tm, 0);
  1794. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1795. var tm1 = SIMD.float32x4.load(tm, 4);
  1796. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1797. var tm2 = SIMD.float32x4.load(tm, 8);
  1798. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1799. var tm3 = SIMD.float32x4.load(tm, 12);
  1800. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1801. };
  1802. Matrix.prototype.equals = function (value) {
  1803. return value &&
  1804. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1805. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1806. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1807. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1808. };
  1809. Matrix.prototype.clone = function () {
  1810. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1811. };
  1812. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1813. translation.x = this.m[12];
  1814. translation.y = this.m[13];
  1815. translation.z = this.m[14];
  1816. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1817. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1818. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1819. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1820. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1821. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1822. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1823. rotation.x = 0;
  1824. rotation.y = 0;
  1825. rotation.z = 0;
  1826. rotation.w = 1;
  1827. return false;
  1828. }
  1829. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1830. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1831. return true;
  1832. };
  1833. // Statics
  1834. Matrix.FromArray = function (array, offset) {
  1835. var result = new Matrix();
  1836. if (!offset) {
  1837. offset = 0;
  1838. }
  1839. Matrix.FromArrayToRef(array, offset, result);
  1840. return result;
  1841. };
  1842. Matrix.FromArrayToRef = function (array, offset, result) {
  1843. for (var index = 0; index < 16; index++) {
  1844. result.m[index] = array[index + offset];
  1845. }
  1846. };
  1847. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1848. for (var index = 0; index < 16; index++) {
  1849. result.m[index] = array[index + offset] * scale;
  1850. }
  1851. };
  1852. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1853. result.m[0] = initialM11;
  1854. result.m[1] = initialM12;
  1855. result.m[2] = initialM13;
  1856. result.m[3] = initialM14;
  1857. result.m[4] = initialM21;
  1858. result.m[5] = initialM22;
  1859. result.m[6] = initialM23;
  1860. result.m[7] = initialM24;
  1861. result.m[8] = initialM31;
  1862. result.m[9] = initialM32;
  1863. result.m[10] = initialM33;
  1864. result.m[11] = initialM34;
  1865. result.m[12] = initialM41;
  1866. result.m[13] = initialM42;
  1867. result.m[14] = initialM43;
  1868. result.m[15] = initialM44;
  1869. };
  1870. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1871. var result = new Matrix();
  1872. result.m[0] = initialM11;
  1873. result.m[1] = initialM12;
  1874. result.m[2] = initialM13;
  1875. result.m[3] = initialM14;
  1876. result.m[4] = initialM21;
  1877. result.m[5] = initialM22;
  1878. result.m[6] = initialM23;
  1879. result.m[7] = initialM24;
  1880. result.m[8] = initialM31;
  1881. result.m[9] = initialM32;
  1882. result.m[10] = initialM33;
  1883. result.m[11] = initialM34;
  1884. result.m[12] = initialM41;
  1885. result.m[13] = initialM42;
  1886. result.m[14] = initialM43;
  1887. result.m[15] = initialM44;
  1888. return result;
  1889. };
  1890. Matrix.Compose = function (scale, rotation, translation) {
  1891. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1892. var rotationMatrix = Matrix.Identity();
  1893. rotation.toRotationMatrix(rotationMatrix);
  1894. result = result.multiply(rotationMatrix);
  1895. result.setTranslation(translation);
  1896. return result;
  1897. };
  1898. Matrix.Identity = function () {
  1899. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1900. };
  1901. Matrix.IdentityToRef = function (result) {
  1902. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1903. };
  1904. Matrix.Zero = function () {
  1905. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1906. };
  1907. Matrix.RotationX = function (angle) {
  1908. var result = new Matrix();
  1909. Matrix.RotationXToRef(angle, result);
  1910. return result;
  1911. };
  1912. Matrix.Invert = function (source) {
  1913. var result = new Matrix();
  1914. source.invertToRef(result);
  1915. return result;
  1916. };
  1917. Matrix.RotationXToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[0] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[5] = c;
  1923. result.m[10] = c;
  1924. result.m[9] = -s;
  1925. result.m[6] = s;
  1926. result.m[1] = 0;
  1927. result.m[2] = 0;
  1928. result.m[3] = 0;
  1929. result.m[4] = 0;
  1930. result.m[7] = 0;
  1931. result.m[8] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationY = function (angle) {
  1938. var result = new Matrix();
  1939. Matrix.RotationYToRef(angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationYToRef = function (angle, result) {
  1943. var s = Math.sin(angle);
  1944. var c = Math.cos(angle);
  1945. result.m[5] = 1.0;
  1946. result.m[15] = 1.0;
  1947. result.m[0] = c;
  1948. result.m[2] = -s;
  1949. result.m[8] = s;
  1950. result.m[10] = c;
  1951. result.m[1] = 0;
  1952. result.m[3] = 0;
  1953. result.m[4] = 0;
  1954. result.m[6] = 0;
  1955. result.m[7] = 0;
  1956. result.m[9] = 0;
  1957. result.m[11] = 0;
  1958. result.m[12] = 0;
  1959. result.m[13] = 0;
  1960. result.m[14] = 0;
  1961. };
  1962. Matrix.RotationZ = function (angle) {
  1963. var result = new Matrix();
  1964. Matrix.RotationZToRef(angle, result);
  1965. return result;
  1966. };
  1967. Matrix.RotationZToRef = function (angle, result) {
  1968. var s = Math.sin(angle);
  1969. var c = Math.cos(angle);
  1970. result.m[10] = 1.0;
  1971. result.m[15] = 1.0;
  1972. result.m[0] = c;
  1973. result.m[1] = s;
  1974. result.m[4] = -s;
  1975. result.m[5] = c;
  1976. result.m[2] = 0;
  1977. result.m[3] = 0;
  1978. result.m[6] = 0;
  1979. result.m[7] = 0;
  1980. result.m[8] = 0;
  1981. result.m[9] = 0;
  1982. result.m[11] = 0;
  1983. result.m[12] = 0;
  1984. result.m[13] = 0;
  1985. result.m[14] = 0;
  1986. };
  1987. Matrix.RotationAxis = function (axis, angle) {
  1988. var result = Matrix.Zero();
  1989. Matrix.RotationAxisToRef(axis, angle, result);
  1990. return result;
  1991. };
  1992. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1993. var s = Math.sin(-angle);
  1994. var c = Math.cos(-angle);
  1995. var c1 = 1 - c;
  1996. axis.normalize();
  1997. result.m[0] = (axis.x * axis.x) * c1 + c;
  1998. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1999. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2000. result.m[3] = 0.0;
  2001. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2002. result.m[5] = (axis.y * axis.y) * c1 + c;
  2003. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2004. result.m[7] = 0.0;
  2005. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2006. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2007. result.m[10] = (axis.z * axis.z) * c1 + c;
  2008. result.m[11] = 0.0;
  2009. result.m[15] = 1.0;
  2010. };
  2011. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2012. var result = new Matrix();
  2013. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2014. return result;
  2015. };
  2016. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2017. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2018. this._tempQuaternion.toRotationMatrix(result);
  2019. };
  2020. Matrix.Scaling = function (x, y, z) {
  2021. var result = Matrix.Zero();
  2022. Matrix.ScalingToRef(x, y, z, result);
  2023. return result;
  2024. };
  2025. Matrix.ScalingToRef = function (x, y, z, result) {
  2026. result.m[0] = x;
  2027. result.m[1] = 0;
  2028. result.m[2] = 0;
  2029. result.m[3] = 0;
  2030. result.m[4] = 0;
  2031. result.m[5] = y;
  2032. result.m[6] = 0;
  2033. result.m[7] = 0;
  2034. result.m[8] = 0;
  2035. result.m[9] = 0;
  2036. result.m[10] = z;
  2037. result.m[11] = 0;
  2038. result.m[12] = 0;
  2039. result.m[13] = 0;
  2040. result.m[14] = 0;
  2041. result.m[15] = 1.0;
  2042. };
  2043. Matrix.Translation = function (x, y, z) {
  2044. var result = Matrix.Identity();
  2045. Matrix.TranslationToRef(x, y, z, result);
  2046. return result;
  2047. };
  2048. Matrix.TranslationToRef = function (x, y, z, result) {
  2049. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2050. };
  2051. Matrix.LookAtLH = function (eye, target, up) {
  2052. var result = Matrix.Zero();
  2053. Matrix.LookAtLHToRef(eye, target, up, result);
  2054. return result;
  2055. };
  2056. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2057. // Z axis
  2058. target.subtractToRef(eye, this._zAxis);
  2059. this._zAxis.normalize();
  2060. // X axis
  2061. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2062. if (this._xAxis.lengthSquared() === 0) {
  2063. this._xAxis.x = 1.0;
  2064. }
  2065. else {
  2066. this._xAxis.normalize();
  2067. }
  2068. // Y axis
  2069. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2070. this._yAxis.normalize();
  2071. // Eye angles
  2072. var ex = -Vector3.Dot(this._xAxis, eye);
  2073. var ey = -Vector3.Dot(this._yAxis, eye);
  2074. var ez = -Vector3.Dot(this._zAxis, eye);
  2075. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2076. };
  2077. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2078. var out = result.m;
  2079. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2080. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2081. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2082. // cc.kmVec3Subtract(f, pCenter, pEye);
  2083. var f = SIMD.float32x4.sub(center, eye);
  2084. // cc.kmVec3Normalize(f, f);
  2085. var tmp = SIMD.float32x4.mul(f, f);
  2086. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2087. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2088. // cc.kmVec3Assign(up, pUp);
  2089. // cc.kmVec3Normalize(up, up);
  2090. tmp = SIMD.float32x4.mul(up, up);
  2091. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2092. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2093. // cc.kmVec3Cross(s, f, up);
  2094. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  2095. // cc.kmVec3Normalize(s, s);
  2096. tmp = SIMD.float32x4.mul(s, s);
  2097. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2098. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2099. // cc.kmVec3Cross(u, s, f);
  2100. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  2101. // cc.kmVec3Normalize(s, s);
  2102. tmp = SIMD.float32x4.mul(s, s);
  2103. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2104. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2105. var zero = SIMD.float32x4.splat(0.0);
  2106. s = SIMD.float32x4.neg(s);
  2107. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2108. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2109. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2110. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2111. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2112. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2113. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2114. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2115. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2116. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2117. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2118. var b3 = SIMD.float32x4.neg(eye);
  2119. b3 = SIMD.float32x4.withW(b3, 1.0);
  2120. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  2121. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  2122. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  2123. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  2124. };
  2125. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2126. var matrix = Matrix.Zero();
  2127. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2128. return matrix;
  2129. };
  2130. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2131. var hw = 2.0 / width;
  2132. var hh = 2.0 / height;
  2133. var id = 1.0 / (zfar - znear);
  2134. var nid = znear / (znear - zfar);
  2135. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2136. };
  2137. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2138. var matrix = Matrix.Zero();
  2139. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2140. return matrix;
  2141. };
  2142. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2143. result.m[0] = 2.0 / (right - left);
  2144. result.m[1] = result.m[2] = result.m[3] = 0;
  2145. result.m[5] = 2.0 / (top - bottom);
  2146. result.m[4] = result.m[6] = result.m[7] = 0;
  2147. result.m[10] = -1.0 / (znear - zfar);
  2148. result.m[8] = result.m[9] = result.m[11] = 0;
  2149. result.m[12] = (left + right) / (left - right);
  2150. result.m[13] = (top + bottom) / (bottom - top);
  2151. result.m[14] = znear / (znear - zfar);
  2152. result.m[15] = 1.0;
  2153. };
  2154. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2155. var matrix = Matrix.Zero();
  2156. matrix.m[0] = (2.0 * znear) / width;
  2157. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2158. matrix.m[5] = (2.0 * znear) / height;
  2159. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2160. matrix.m[10] = -zfar / (znear - zfar);
  2161. matrix.m[8] = matrix.m[9] = 0.0;
  2162. matrix.m[11] = 1.0;
  2163. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2164. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2165. return matrix;
  2166. };
  2167. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2168. var matrix = Matrix.Zero();
  2169. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2170. return matrix;
  2171. };
  2172. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2173. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2174. var tan = 1.0 / (Math.tan(fov * 0.5));
  2175. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2176. if (v_fixed) {
  2177. result.m[0] = tan / aspect;
  2178. }
  2179. else {
  2180. result.m[0] = tan;
  2181. }
  2182. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2183. if (v_fixed) {
  2184. result.m[5] = tan;
  2185. }
  2186. else {
  2187. result.m[5] = tan * aspect;
  2188. }
  2189. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2190. result.m[8] = result.m[9] = 0.0;
  2191. result.m[10] = -zfar / (znear - zfar);
  2192. result.m[11] = 1.0;
  2193. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2194. result.m[14] = (znear * zfar) / (znear - zfar);
  2195. };
  2196. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2197. var cw = viewport.width;
  2198. var ch = viewport.height;
  2199. var cx = viewport.x;
  2200. var cy = viewport.y;
  2201. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2202. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2203. };
  2204. Matrix.GetAsMatrix2x2 = function (matrix) {
  2205. return new Float32Array([
  2206. matrix.m[0], matrix.m[1],
  2207. matrix.m[4], matrix.m[5]
  2208. ]);
  2209. };
  2210. Matrix.GetAsMatrix3x3 = function (matrix) {
  2211. return new Float32Array([
  2212. matrix.m[0], matrix.m[1], matrix.m[2],
  2213. matrix.m[4], matrix.m[5], matrix.m[6],
  2214. matrix.m[8], matrix.m[9], matrix.m[10]
  2215. ]);
  2216. };
  2217. Matrix.Transpose = function (matrix) {
  2218. var result = new Matrix();
  2219. result.m[0] = matrix.m[0];
  2220. result.m[1] = matrix.m[4];
  2221. result.m[2] = matrix.m[8];
  2222. result.m[3] = matrix.m[12];
  2223. result.m[4] = matrix.m[1];
  2224. result.m[5] = matrix.m[5];
  2225. result.m[6] = matrix.m[9];
  2226. result.m[7] = matrix.m[13];
  2227. result.m[8] = matrix.m[2];
  2228. result.m[9] = matrix.m[6];
  2229. result.m[10] = matrix.m[10];
  2230. result.m[11] = matrix.m[14];
  2231. result.m[12] = matrix.m[3];
  2232. result.m[13] = matrix.m[7];
  2233. result.m[14] = matrix.m[11];
  2234. result.m[15] = matrix.m[15];
  2235. return result;
  2236. };
  2237. Matrix.Reflection = function (plane) {
  2238. var matrix = new Matrix();
  2239. Matrix.ReflectionToRef(plane, matrix);
  2240. return matrix;
  2241. };
  2242. Matrix.ReflectionToRef = function (plane, result) {
  2243. plane.normalize();
  2244. var x = plane.normal.x;
  2245. var y = plane.normal.y;
  2246. var z = plane.normal.z;
  2247. var temp = -2 * x;
  2248. var temp2 = -2 * y;
  2249. var temp3 = -2 * z;
  2250. result.m[0] = (temp * x) + 1;
  2251. result.m[1] = temp2 * x;
  2252. result.m[2] = temp3 * x;
  2253. result.m[3] = 0.0;
  2254. result.m[4] = temp * y;
  2255. result.m[5] = (temp2 * y) + 1;
  2256. result.m[6] = temp3 * y;
  2257. result.m[7] = 0.0;
  2258. result.m[8] = temp * z;
  2259. result.m[9] = temp2 * z;
  2260. result.m[10] = (temp3 * z) + 1;
  2261. result.m[11] = 0.0;
  2262. result.m[12] = temp * plane.d;
  2263. result.m[13] = temp2 * plane.d;
  2264. result.m[14] = temp3 * plane.d;
  2265. result.m[15] = 1.0;
  2266. };
  2267. Matrix._tempQuaternion = new Quaternion();
  2268. Matrix._xAxis = Vector3.Zero();
  2269. Matrix._yAxis = Vector3.Zero();
  2270. Matrix._zAxis = Vector3.Zero();
  2271. return Matrix;
  2272. })();
  2273. BABYLON.Matrix = Matrix;
  2274. var Plane = (function () {
  2275. function Plane(a, b, c, d) {
  2276. this.normal = new Vector3(a, b, c);
  2277. this.d = d;
  2278. }
  2279. Plane.prototype.asArray = function () {
  2280. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2281. };
  2282. // Methods
  2283. Plane.prototype.clone = function () {
  2284. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2285. };
  2286. Plane.prototype.normalize = function () {
  2287. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2288. var magnitude = 0;
  2289. if (norm !== 0) {
  2290. magnitude = 1.0 / norm;
  2291. }
  2292. this.normal.x *= magnitude;
  2293. this.normal.y *= magnitude;
  2294. this.normal.z *= magnitude;
  2295. this.d *= magnitude;
  2296. return this;
  2297. };
  2298. Plane.prototype.transform = function (transformation) {
  2299. var transposedMatrix = Matrix.Transpose(transformation);
  2300. var x = this.normal.x;
  2301. var y = this.normal.y;
  2302. var z = this.normal.z;
  2303. var d = this.d;
  2304. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2305. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2306. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2307. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2308. return new Plane(normalX, normalY, normalZ, finalD);
  2309. };
  2310. Plane.prototype.dotCoordinate = function (point) {
  2311. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2312. };
  2313. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2314. var x1 = point2.x - point1.x;
  2315. var y1 = point2.y - point1.y;
  2316. var z1 = point2.z - point1.z;
  2317. var x2 = point3.x - point1.x;
  2318. var y2 = point3.y - point1.y;
  2319. var z2 = point3.z - point1.z;
  2320. var yz = (y1 * z2) - (z1 * y2);
  2321. var xz = (z1 * x2) - (x1 * z2);
  2322. var xy = (x1 * y2) - (y1 * x2);
  2323. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2324. var invPyth;
  2325. if (pyth !== 0) {
  2326. invPyth = 1.0 / pyth;
  2327. }
  2328. else {
  2329. invPyth = 0;
  2330. }
  2331. this.normal.x = yz * invPyth;
  2332. this.normal.y = xz * invPyth;
  2333. this.normal.z = xy * invPyth;
  2334. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2335. return this;
  2336. };
  2337. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2338. var dot = Vector3.Dot(this.normal, direction);
  2339. return (dot <= epsilon);
  2340. };
  2341. Plane.prototype.signedDistanceTo = function (point) {
  2342. return Vector3.Dot(point, this.normal) + this.d;
  2343. };
  2344. // Statics
  2345. Plane.FromArray = function (array) {
  2346. return new Plane(array[0], array[1], array[2], array[3]);
  2347. };
  2348. Plane.FromPoints = function (point1, point2, point3) {
  2349. var result = new Plane(0, 0, 0, 0);
  2350. result.copyFromPoints(point1, point2, point3);
  2351. return result;
  2352. };
  2353. Plane.FromPositionAndNormal = function (origin, normal) {
  2354. var result = new Plane(0, 0, 0, 0);
  2355. normal.normalize();
  2356. result.normal = normal;
  2357. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2358. return result;
  2359. };
  2360. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2361. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2362. return Vector3.Dot(point, normal) + d;
  2363. };
  2364. return Plane;
  2365. })();
  2366. BABYLON.Plane = Plane;
  2367. var Viewport = (function () {
  2368. function Viewport(x, y, width, height) {
  2369. this.x = x;
  2370. this.y = y;
  2371. this.width = width;
  2372. this.height = height;
  2373. }
  2374. Viewport.prototype.toGlobal = function (engine) {
  2375. var width = engine.getRenderWidth();
  2376. var height = engine.getRenderHeight();
  2377. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2378. };
  2379. return Viewport;
  2380. })();
  2381. BABYLON.Viewport = Viewport;
  2382. var Frustum = (function () {
  2383. function Frustum() {
  2384. }
  2385. Frustum.GetPlanes = function (transform) {
  2386. var frustumPlanes = [];
  2387. for (var index = 0; index < 6; index++) {
  2388. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2389. }
  2390. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2391. return frustumPlanes;
  2392. };
  2393. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2394. // Near
  2395. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2396. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2397. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2398. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2399. frustumPlanes[0].normalize();
  2400. // Far
  2401. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2402. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2403. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2404. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2405. frustumPlanes[1].normalize();
  2406. // Left
  2407. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2408. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2409. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2410. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2411. frustumPlanes[2].normalize();
  2412. // Right
  2413. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2414. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2415. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2416. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2417. frustumPlanes[3].normalize();
  2418. // Top
  2419. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2420. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2421. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2422. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2423. frustumPlanes[4].normalize();
  2424. // Bottom
  2425. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2426. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2427. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2428. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2429. frustumPlanes[5].normalize();
  2430. };
  2431. return Frustum;
  2432. })();
  2433. BABYLON.Frustum = Frustum;
  2434. var Ray = (function () {
  2435. function Ray(origin, direction, length) {
  2436. if (length === void 0) { length = Number.MAX_VALUE; }
  2437. this.origin = origin;
  2438. this.direction = direction;
  2439. this.length = length;
  2440. }
  2441. // Methods
  2442. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2443. var d = 0.0;
  2444. var maxValue = Number.MAX_VALUE;
  2445. var inv;
  2446. var min;
  2447. var max;
  2448. var temp;
  2449. if (Math.abs(this.direction.x) < 0.0000001) {
  2450. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2451. return false;
  2452. }
  2453. }
  2454. else {
  2455. inv = 1.0 / this.direction.x;
  2456. min = (minimum.x - this.origin.x) * inv;
  2457. max = (maximum.x - this.origin.x) * inv;
  2458. if (max === -Infinity) {
  2459. max = Infinity;
  2460. }
  2461. if (min > max) {
  2462. temp = min;
  2463. min = max;
  2464. max = temp;
  2465. }
  2466. d = Math.max(min, d);
  2467. maxValue = Math.min(max, maxValue);
  2468. if (d > maxValue) {
  2469. return false;
  2470. }
  2471. }
  2472. if (Math.abs(this.direction.y) < 0.0000001) {
  2473. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2474. return false;
  2475. }
  2476. }
  2477. else {
  2478. inv = 1.0 / this.direction.y;
  2479. min = (minimum.y - this.origin.y) * inv;
  2480. max = (maximum.y - this.origin.y) * inv;
  2481. if (max === -Infinity) {
  2482. max = Infinity;
  2483. }
  2484. if (min > max) {
  2485. temp = min;
  2486. min = max;
  2487. max = temp;
  2488. }
  2489. d = Math.max(min, d);
  2490. maxValue = Math.min(max, maxValue);
  2491. if (d > maxValue) {
  2492. return false;
  2493. }
  2494. }
  2495. if (Math.abs(this.direction.z) < 0.0000001) {
  2496. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2497. return false;
  2498. }
  2499. }
  2500. else {
  2501. inv = 1.0 / this.direction.z;
  2502. min = (minimum.z - this.origin.z) * inv;
  2503. max = (maximum.z - this.origin.z) * inv;
  2504. if (max === -Infinity) {
  2505. max = Infinity;
  2506. }
  2507. if (min > max) {
  2508. temp = min;
  2509. min = max;
  2510. max = temp;
  2511. }
  2512. d = Math.max(min, d);
  2513. maxValue = Math.min(max, maxValue);
  2514. if (d > maxValue) {
  2515. return false;
  2516. }
  2517. }
  2518. return true;
  2519. };
  2520. Ray.prototype.intersectsBox = function (box) {
  2521. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2522. };
  2523. Ray.prototype.intersectsSphere = function (sphere) {
  2524. var x = sphere.center.x - this.origin.x;
  2525. var y = sphere.center.y - this.origin.y;
  2526. var z = sphere.center.z - this.origin.z;
  2527. var pyth = (x * x) + (y * y) + (z * z);
  2528. var rr = sphere.radius * sphere.radius;
  2529. if (pyth <= rr) {
  2530. return true;
  2531. }
  2532. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2533. if (dot < 0.0) {
  2534. return false;
  2535. }
  2536. var temp = pyth - (dot * dot);
  2537. return temp <= rr;
  2538. };
  2539. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2540. if (!this._edge1) {
  2541. this._edge1 = Vector3.Zero();
  2542. this._edge2 = Vector3.Zero();
  2543. this._pvec = Vector3.Zero();
  2544. this._tvec = Vector3.Zero();
  2545. this._qvec = Vector3.Zero();
  2546. }
  2547. vertex1.subtractToRef(vertex0, this._edge1);
  2548. vertex2.subtractToRef(vertex0, this._edge2);
  2549. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2550. var det = Vector3.Dot(this._edge1, this._pvec);
  2551. if (det === 0) {
  2552. return null;
  2553. }
  2554. var invdet = 1 / det;
  2555. this.origin.subtractToRef(vertex0, this._tvec);
  2556. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2557. if (bu < 0 || bu > 1.0) {
  2558. return null;
  2559. }
  2560. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2561. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2562. if (bv < 0 || bu + bv > 1.0) {
  2563. return null;
  2564. }
  2565. //check if the distance is longer than the predefined length.
  2566. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2567. if (distance > this.length) {
  2568. return null;
  2569. }
  2570. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2571. };
  2572. // Statics
  2573. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2574. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2575. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2576. var direction = end.subtract(start);
  2577. direction.normalize();
  2578. return new Ray(start, direction);
  2579. };
  2580. /**
  2581. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2582. * transformed to the given world matrix.
  2583. * @param origin The origin point
  2584. * @param end The end point
  2585. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2586. */
  2587. Ray.CreateNewFromTo = function (origin, end, world) {
  2588. if (world === void 0) { world = Matrix.Identity(); }
  2589. var direction = end.subtract(origin);
  2590. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2591. direction.normalize();
  2592. return Ray.Transform(new Ray(origin, direction, length), world);
  2593. };
  2594. Ray.Transform = function (ray, matrix) {
  2595. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2596. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2597. return new Ray(newOrigin, newDirection, ray.length);
  2598. };
  2599. return Ray;
  2600. })();
  2601. BABYLON.Ray = Ray;
  2602. (function (Space) {
  2603. Space[Space["LOCAL"] = 0] = "LOCAL";
  2604. Space[Space["WORLD"] = 1] = "WORLD";
  2605. })(BABYLON.Space || (BABYLON.Space = {}));
  2606. var Space = BABYLON.Space;
  2607. var Axis = (function () {
  2608. function Axis() {
  2609. }
  2610. Axis.X = new Vector3(1, 0, 0);
  2611. Axis.Y = new Vector3(0, 1, 0);
  2612. Axis.Z = new Vector3(0, 0, 1);
  2613. return Axis;
  2614. })();
  2615. BABYLON.Axis = Axis;
  2616. ;
  2617. var BezierCurve = (function () {
  2618. function BezierCurve() {
  2619. }
  2620. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2621. // Extract X (which is equal to time here)
  2622. var f0 = 1 - 3 * x2 + 3 * x1;
  2623. var f1 = 3 * x2 - 6 * x1;
  2624. var f2 = 3 * x1;
  2625. var refinedT = t;
  2626. for (var i = 0; i < 5; i++) {
  2627. var refinedT2 = refinedT * refinedT;
  2628. var refinedT3 = refinedT2 * refinedT;
  2629. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2630. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2631. refinedT -= (x - t) * slope;
  2632. refinedT = Math.min(1, Math.max(0, refinedT));
  2633. }
  2634. // Resolve cubic bezier for the given x
  2635. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2636. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2637. Math.pow(refinedT, 3);
  2638. };
  2639. return BezierCurve;
  2640. })();
  2641. BABYLON.BezierCurve = BezierCurve;
  2642. (function (Orientation) {
  2643. Orientation[Orientation["CW"] = 0] = "CW";
  2644. Orientation[Orientation["CCW"] = 1] = "CCW";
  2645. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2646. var Orientation = BABYLON.Orientation;
  2647. var Angle = (function () {
  2648. function Angle(radians) {
  2649. var _this = this;
  2650. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2651. this.radians = function () { return _this._radians; };
  2652. this._radians = radians;
  2653. if (this._radians < 0)
  2654. this._radians += (2 * Math.PI);
  2655. }
  2656. Angle.BetweenTwoPoints = function (a, b) {
  2657. var delta = b.subtract(a);
  2658. var theta = Math.atan2(delta.y, delta.x);
  2659. return new Angle(theta);
  2660. };
  2661. Angle.FromRadians = function (radians) {
  2662. return new Angle(radians);
  2663. };
  2664. Angle.FromDegrees = function (degrees) {
  2665. return new Angle(degrees * Math.PI / 180);
  2666. };
  2667. return Angle;
  2668. })();
  2669. BABYLON.Angle = Angle;
  2670. var Arc2 = (function () {
  2671. function Arc2(startPoint, midPoint, endPoint) {
  2672. this.startPoint = startPoint;
  2673. this.midPoint = midPoint;
  2674. this.endPoint = endPoint;
  2675. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2676. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2677. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2678. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2679. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2680. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2681. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2682. var a1 = this.startAngle.degrees();
  2683. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2684. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2685. // angles correction
  2686. if (a2 - a1 > +180.0)
  2687. a2 -= 360.0;
  2688. if (a2 - a1 < -180.0)
  2689. a2 += 360.0;
  2690. if (a3 - a2 > +180.0)
  2691. a3 -= 360.0;
  2692. if (a3 - a2 < -180.0)
  2693. a3 += 360.0;
  2694. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2695. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2696. }
  2697. return Arc2;
  2698. })();
  2699. BABYLON.Arc2 = Arc2;
  2700. var PathCursor = (function () {
  2701. function PathCursor(path) {
  2702. this.path = path;
  2703. this._onchange = new Array();
  2704. this.value = 0;
  2705. this.animations = new Array();
  2706. }
  2707. PathCursor.prototype.getPoint = function () {
  2708. var point = this.path.getPointAtLengthPosition(this.value);
  2709. return new Vector3(point.x, 0, point.y);
  2710. };
  2711. PathCursor.prototype.moveAhead = function (step) {
  2712. if (step === void 0) { step = 0.002; }
  2713. this.move(step);
  2714. return this;
  2715. };
  2716. PathCursor.prototype.moveBack = function (step) {
  2717. if (step === void 0) { step = 0.002; }
  2718. this.move(-step);
  2719. return this;
  2720. };
  2721. PathCursor.prototype.move = function (step) {
  2722. if (Math.abs(step) > 1) {
  2723. throw "step size should be less than 1.";
  2724. }
  2725. this.value += step;
  2726. this.ensureLimits();
  2727. this.raiseOnChange();
  2728. return this;
  2729. };
  2730. PathCursor.prototype.ensureLimits = function () {
  2731. while (this.value > 1) {
  2732. this.value -= 1;
  2733. }
  2734. while (this.value < 0) {
  2735. this.value += 1;
  2736. }
  2737. return this;
  2738. };
  2739. // used by animation engine
  2740. PathCursor.prototype.markAsDirty = function (propertyName) {
  2741. this.ensureLimits();
  2742. this.raiseOnChange();
  2743. return this;
  2744. };
  2745. PathCursor.prototype.raiseOnChange = function () {
  2746. var _this = this;
  2747. this._onchange.forEach(function (f) { return f(_this); });
  2748. return this;
  2749. };
  2750. PathCursor.prototype.onchange = function (f) {
  2751. this._onchange.push(f);
  2752. return this;
  2753. };
  2754. return PathCursor;
  2755. })();
  2756. BABYLON.PathCursor = PathCursor;
  2757. var Path2 = (function () {
  2758. function Path2(x, y) {
  2759. this._points = new Array();
  2760. this._length = 0;
  2761. this.closed = false;
  2762. this._points.push(new Vector2(x, y));
  2763. }
  2764. Path2.prototype.addLineTo = function (x, y) {
  2765. if (closed) {
  2766. BABYLON.Tools.Error("cannot add lines to closed paths");
  2767. return this;
  2768. }
  2769. var newPoint = new Vector2(x, y);
  2770. var previousPoint = this._points[this._points.length - 1];
  2771. this._points.push(newPoint);
  2772. this._length += newPoint.subtract(previousPoint).length();
  2773. return this;
  2774. };
  2775. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2776. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2777. if (closed) {
  2778. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2779. return this;
  2780. }
  2781. var startPoint = this._points[this._points.length - 1];
  2782. var midPoint = new Vector2(midX, midY);
  2783. var endPoint = new Vector2(endX, endY);
  2784. var arc = new Arc2(startPoint, midPoint, endPoint);
  2785. var increment = arc.angle.radians() / numberOfSegments;
  2786. if (arc.orientation === Orientation.CW)
  2787. increment *= -1;
  2788. var currentAngle = arc.startAngle.radians() + increment;
  2789. for (var i = 0; i < numberOfSegments; i++) {
  2790. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2791. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2792. this.addLineTo(x, y);
  2793. currentAngle += increment;
  2794. }
  2795. return this;
  2796. };
  2797. Path2.prototype.close = function () {
  2798. this.closed = true;
  2799. return this;
  2800. };
  2801. Path2.prototype.length = function () {
  2802. var result = this._length;
  2803. if (!this.closed) {
  2804. var lastPoint = this._points[this._points.length - 1];
  2805. var firstPoint = this._points[0];
  2806. result += (firstPoint.subtract(lastPoint).length());
  2807. }
  2808. return result;
  2809. };
  2810. Path2.prototype.getPoints = function () {
  2811. return this._points;
  2812. };
  2813. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2814. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2815. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2816. return Vector2.Zero();
  2817. }
  2818. var lengthPosition = normalizedLengthPosition * this.length();
  2819. var previousOffset = 0;
  2820. for (var i = 0; i < this._points.length; i++) {
  2821. var j = (i + 1) % this._points.length;
  2822. var a = this._points[i];
  2823. var b = this._points[j];
  2824. var bToA = b.subtract(a);
  2825. var nextOffset = (bToA.length() + previousOffset);
  2826. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2827. var dir = bToA.normalize();
  2828. var localOffset = lengthPosition - previousOffset;
  2829. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2830. }
  2831. previousOffset = nextOffset;
  2832. }
  2833. BABYLON.Tools.Error("internal error");
  2834. return Vector2.Zero();
  2835. };
  2836. Path2.StartingAt = function (x, y) {
  2837. return new Path2(x, y);
  2838. };
  2839. return Path2;
  2840. })();
  2841. BABYLON.Path2 = Path2;
  2842. var Path3D = (function () {
  2843. /**
  2844. * new Path3D(path, normal, raw)
  2845. * path : an array of Vector3, the curve axis of the Path3D
  2846. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2847. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2848. */
  2849. function Path3D(path, firstNormal, raw) {
  2850. this.path = path;
  2851. this._curve = new Array();
  2852. this._distances = new Array();
  2853. this._tangents = new Array();
  2854. this._normals = new Array();
  2855. this._binormals = new Array();
  2856. for (var p = 0; p < path.length; p++) {
  2857. this._curve[p] = path[p].clone(); // hard copy
  2858. }
  2859. this._raw = raw || false;
  2860. this._compute(firstNormal);
  2861. }
  2862. Path3D.prototype.getCurve = function () {
  2863. return this._curve;
  2864. };
  2865. Path3D.prototype.getTangents = function () {
  2866. return this._tangents;
  2867. };
  2868. Path3D.prototype.getNormals = function () {
  2869. return this._normals;
  2870. };
  2871. Path3D.prototype.getBinormals = function () {
  2872. return this._binormals;
  2873. };
  2874. Path3D.prototype.getDistances = function () {
  2875. return this._distances;
  2876. };
  2877. Path3D.prototype.update = function (path, firstNormal) {
  2878. for (var p = 0; p < path.length; p++) {
  2879. this._curve[p].x = path[p].x;
  2880. this._curve[p].y = path[p].y;
  2881. this._curve[p].z = path[p].z;
  2882. }
  2883. this._compute(firstNormal);
  2884. return this;
  2885. };
  2886. // private function compute() : computes tangents, normals and binormals
  2887. Path3D.prototype._compute = function (firstNormal) {
  2888. var l = this._curve.length;
  2889. // first and last tangents
  2890. this._tangents[0] = this._getFirstNonNullVector(0);
  2891. if (!this._raw) {
  2892. this._tangents[0].normalize();
  2893. }
  2894. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2895. if (!this._raw) {
  2896. this._tangents[l - 1].normalize();
  2897. }
  2898. // normals and binormals at first point : arbitrary vector with _normalVector()
  2899. var tg0 = this._tangents[0];
  2900. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2901. this._normals[0] = pp0;
  2902. if (!this._raw) {
  2903. this._normals[0].normalize();
  2904. }
  2905. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2906. if (!this._raw) {
  2907. this._binormals[0].normalize();
  2908. }
  2909. this._distances[0] = 0;
  2910. // normals and binormals : next points
  2911. var prev; // previous vector (segment)
  2912. var cur; // current vector (segment)
  2913. var curTang; // current tangent
  2914. // previous normal
  2915. var prevBinor; // previous binormal
  2916. for (var i = 1; i < l; i++) {
  2917. // tangents
  2918. prev = this._getLastNonNullVector(i);
  2919. if (i < l - 1) {
  2920. cur = this._getFirstNonNullVector(i);
  2921. this._tangents[i] = prev.add(cur);
  2922. this._tangents[i].normalize();
  2923. }
  2924. this._distances[i] = this._distances[i - 1] + prev.length();
  2925. // normals and binormals
  2926. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2927. curTang = this._tangents[i];
  2928. prevBinor = this._binormals[i - 1];
  2929. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2930. if (!this._raw) {
  2931. this._normals[i].normalize();
  2932. }
  2933. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2934. if (!this._raw) {
  2935. this._binormals[i].normalize();
  2936. }
  2937. }
  2938. };
  2939. // private function getFirstNonNullVector(index)
  2940. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2941. Path3D.prototype._getFirstNonNullVector = function (index) {
  2942. var i = 1;
  2943. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2944. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2945. i++;
  2946. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2947. }
  2948. return nNVector;
  2949. };
  2950. // private function getLastNonNullVector(index)
  2951. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2952. Path3D.prototype._getLastNonNullVector = function (index) {
  2953. var i = 1;
  2954. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2955. while (nLVector.length() === 0 && index > i + 1) {
  2956. i++;
  2957. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2958. }
  2959. return nLVector;
  2960. };
  2961. // private function normalVector(v0, vt, va) :
  2962. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2963. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2964. Path3D.prototype._normalVector = function (v0, vt, va) {
  2965. var normal0;
  2966. if (va === undefined || va === null) {
  2967. var point;
  2968. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2969. point = new Vector3(0, -1, 0);
  2970. }
  2971. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2972. point = new Vector3(1, 0, 0);
  2973. }
  2974. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2975. point = new Vector3(0, 0, 1);
  2976. }
  2977. normal0 = Vector3.Cross(vt, point);
  2978. }
  2979. else {
  2980. normal0 = Vector3.Cross(vt, va);
  2981. Vector3.CrossToRef(normal0, vt, normal0);
  2982. }
  2983. normal0.normalize();
  2984. return normal0;
  2985. };
  2986. return Path3D;
  2987. })();
  2988. BABYLON.Path3D = Path3D;
  2989. var Curve3 = (function () {
  2990. function Curve3(points) {
  2991. this._length = 0;
  2992. this._points = points;
  2993. this._length = this._computeLength(points);
  2994. }
  2995. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2996. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2997. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2998. var bez = new Array();
  2999. var equation = function (t, val0, val1, val2) {
  3000. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  3001. return res;
  3002. };
  3003. for (var i = 0; i <= nbPoints; i++) {
  3004. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  3005. }
  3006. return new Curve3(bez);
  3007. };
  3008. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  3009. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3010. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3011. var bez = new Array();
  3012. var equation = function (t, val0, val1, val2, val3) {
  3013. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  3014. return res;
  3015. };
  3016. for (var i = 0; i <= nbPoints; i++) {
  3017. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  3018. }
  3019. return new Curve3(bez);
  3020. };
  3021. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  3022. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3023. var hermite = new Array();
  3024. var step = 1 / nbPoints;
  3025. for (var i = 0; i <= nbPoints; i++) {
  3026. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3027. }
  3028. return new Curve3(hermite);
  3029. };
  3030. Curve3.prototype.getPoints = function () {
  3031. return this._points;
  3032. };
  3033. Curve3.prototype.length = function () {
  3034. return this._length;
  3035. };
  3036. Curve3.prototype.continue = function (curve) {
  3037. var lastPoint = this._points[this._points.length - 1];
  3038. var continuedPoints = this._points.slice();
  3039. var curvePoints = curve.getPoints();
  3040. for (var i = 1; i < curvePoints.length; i++) {
  3041. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3042. }
  3043. var continuedCurve = new Curve3(continuedPoints);
  3044. return continuedCurve;
  3045. };
  3046. Curve3.prototype._computeLength = function (path) {
  3047. var l = 0;
  3048. for (var i = 1; i < path.length; i++) {
  3049. l += (path[i].subtract(path[i - 1])).length();
  3050. }
  3051. return l;
  3052. };
  3053. return Curve3;
  3054. })();
  3055. BABYLON.Curve3 = Curve3;
  3056. // Vertex formats
  3057. var PositionNormalVertex = (function () {
  3058. function PositionNormalVertex(position, normal) {
  3059. if (position === void 0) { position = Vector3.Zero(); }
  3060. if (normal === void 0) { normal = Vector3.Up(); }
  3061. this.position = position;
  3062. this.normal = normal;
  3063. }
  3064. PositionNormalVertex.prototype.clone = function () {
  3065. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3066. };
  3067. return PositionNormalVertex;
  3068. })();
  3069. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3070. var PositionNormalTextureVertex = (function () {
  3071. function PositionNormalTextureVertex(position, normal, uv) {
  3072. if (position === void 0) { position = Vector3.Zero(); }
  3073. if (normal === void 0) { normal = Vector3.Up(); }
  3074. if (uv === void 0) { uv = Vector2.Zero(); }
  3075. this.position = position;
  3076. this.normal = normal;
  3077. this.uv = uv;
  3078. }
  3079. PositionNormalTextureVertex.prototype.clone = function () {
  3080. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3081. };
  3082. return PositionNormalTextureVertex;
  3083. })();
  3084. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3085. // SIMD
  3086. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3087. var previousInvertToRef = Matrix.prototype.invertToRef;
  3088. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3089. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3090. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3091. var SIMDHelper = (function () {
  3092. function SIMDHelper() {
  3093. }
  3094. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3095. get: function () {
  3096. return SIMDHelper._isEnabled;
  3097. },
  3098. enumerable: true,
  3099. configurable: true
  3100. });
  3101. SIMDHelper.DisableSIMD = function () {
  3102. // Replace functions
  3103. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3104. Matrix.prototype.invertToRef = previousInvertToRef;
  3105. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3106. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3107. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3108. SIMDHelper._isEnabled = false;
  3109. };
  3110. SIMDHelper.EnableSIMD = function () {
  3111. if (window.SIMD === undefined) {
  3112. return;
  3113. }
  3114. // Replace functions
  3115. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3116. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3117. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3118. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3119. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3120. Object.defineProperty(Vector3.prototype, "x", {
  3121. get: function () { return this._data[0]; },
  3122. set: function (value) {
  3123. if (!this._data) {
  3124. this._data = new Float32Array(3);
  3125. }
  3126. this._data[0] = value;
  3127. }
  3128. });
  3129. Object.defineProperty(Vector3.prototype, "y", {
  3130. get: function () { return this._data[1]; },
  3131. set: function (value) {
  3132. this._data[1] = value;
  3133. }
  3134. });
  3135. Object.defineProperty(Vector3.prototype, "z", {
  3136. get: function () { return this._data[2]; },
  3137. set: function (value) {
  3138. this._data[2] = value;
  3139. }
  3140. });
  3141. SIMDHelper._isEnabled = true;
  3142. };
  3143. SIMDHelper._isEnabled = false;
  3144. return SIMDHelper;
  3145. })();
  3146. BABYLON.SIMDHelper = SIMDHelper;
  3147. })(BABYLON || (BABYLON = {}));
  3148. var BABYLON;
  3149. (function (BABYLON) {
  3150. var Database = (function () {
  3151. function Database(urlToScene, callbackManifestChecked) {
  3152. // Handling various flavors of prefixed version of IndexedDB
  3153. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3154. this.callbackManifestChecked = callbackManifestChecked;
  3155. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3156. this.db = null;
  3157. this.enableSceneOffline = false;
  3158. this.enableTexturesOffline = false;
  3159. this.manifestVersionFound = 0;
  3160. this.mustUpdateRessources = false;
  3161. this.hasReachedQuota = false;
  3162. if (!Database.IDBStorageEnabled) {
  3163. this.callbackManifestChecked(true);
  3164. }
  3165. else {
  3166. this.checkManifestFile();
  3167. }
  3168. }
  3169. Database.prototype.checkManifestFile = function () {
  3170. var _this = this;
  3171. function noManifestFile() {
  3172. that.enableSceneOffline = false;
  3173. that.enableTexturesOffline = false;
  3174. that.callbackManifestChecked(false);
  3175. }
  3176. var that = this;
  3177. var manifestURL = this.currentSceneUrl + ".manifest";
  3178. var xhr = new XMLHttpRequest();
  3179. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3180. xhr.open("GET", manifestURLTimeStamped, true);
  3181. xhr.addEventListener("load", function () {
  3182. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3183. try {
  3184. var manifestFile = JSON.parse(xhr.response);
  3185. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3186. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3187. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3188. _this.manifestVersionFound = manifestFile.version;
  3189. }
  3190. if (_this.callbackManifestChecked) {
  3191. _this.callbackManifestChecked(true);
  3192. }
  3193. }
  3194. catch (ex) {
  3195. noManifestFile();
  3196. }
  3197. }
  3198. else {
  3199. noManifestFile();
  3200. }
  3201. }, false);
  3202. xhr.addEventListener("error", function (event) {
  3203. noManifestFile();
  3204. }, false);
  3205. try {
  3206. xhr.send();
  3207. }
  3208. catch (ex) {
  3209. BABYLON.Tools.Error("Error on XHR send request.");
  3210. that.callbackManifestChecked(false);
  3211. }
  3212. };
  3213. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3214. var _this = this;
  3215. function handleError() {
  3216. that.isSupported = false;
  3217. if (errorCallback)
  3218. errorCallback();
  3219. }
  3220. var that = this;
  3221. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3222. // Your browser doesn't support IndexedDB
  3223. this.isSupported = false;
  3224. if (errorCallback)
  3225. errorCallback();
  3226. }
  3227. else {
  3228. // If the DB hasn't been opened or created yet
  3229. if (!this.db) {
  3230. this.hasReachedQuota = false;
  3231. this.isSupported = true;
  3232. var request = this.idbFactory.open("babylonjs", 1);
  3233. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3234. request.onerror = function (event) {
  3235. handleError();
  3236. };
  3237. // executes when a version change transaction cannot complete due to other active transactions
  3238. request.onblocked = function (event) {
  3239. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3240. handleError();
  3241. };
  3242. // DB has been opened successfully
  3243. request.onsuccess = function (event) {
  3244. _this.db = request.result;
  3245. successCallback();
  3246. };
  3247. // Initialization of the DB. Creating Scenes & Textures stores
  3248. request.onupgradeneeded = function (event) {
  3249. _this.db = (event.target).result;
  3250. try {
  3251. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3252. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3253. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3254. }
  3255. catch (ex) {
  3256. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3257. handleError();
  3258. }
  3259. };
  3260. }
  3261. else {
  3262. if (successCallback)
  3263. successCallback();
  3264. }
  3265. }
  3266. };
  3267. Database.prototype.loadImageFromDB = function (url, image) {
  3268. var _this = this;
  3269. var completeURL = Database.ReturnFullUrlLocation(url);
  3270. var saveAndLoadImage = function () {
  3271. if (!_this.hasReachedQuota && _this.db !== null) {
  3272. // the texture is not yet in the DB, let's try to save it
  3273. _this._saveImageIntoDBAsync(completeURL, image);
  3274. }
  3275. else {
  3276. image.src = url;
  3277. }
  3278. };
  3279. if (!this.mustUpdateRessources) {
  3280. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3281. }
  3282. else {
  3283. saveAndLoadImage();
  3284. }
  3285. };
  3286. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3287. if (this.isSupported && this.db !== null) {
  3288. var texture;
  3289. var transaction = this.db.transaction(["textures"]);
  3290. transaction.onabort = function (event) {
  3291. image.src = url;
  3292. };
  3293. transaction.oncomplete = function (event) {
  3294. var blobTextureURL;
  3295. if (texture) {
  3296. var URL = window.URL || window.webkitURL;
  3297. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3298. image.onerror = function () {
  3299. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3300. image.src = url;
  3301. };
  3302. image.src = blobTextureURL;
  3303. }
  3304. else {
  3305. notInDBCallback();
  3306. }
  3307. };
  3308. var getRequest = transaction.objectStore("textures").get(url);
  3309. getRequest.onsuccess = function (event) {
  3310. texture = (event.target).result;
  3311. };
  3312. getRequest.onerror = function (event) {
  3313. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3314. image.src = url;
  3315. };
  3316. }
  3317. else {
  3318. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3319. image.src = url;
  3320. }
  3321. };
  3322. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3323. var _this = this;
  3324. if (this.isSupported) {
  3325. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3326. var generateBlobUrl = function () {
  3327. var blobTextureURL;
  3328. if (blob) {
  3329. var URL = window.URL || window.webkitURL;
  3330. try {
  3331. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3332. }
  3333. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3334. catch (ex) {
  3335. blobTextureURL = URL.createObjectURL(blob);
  3336. }
  3337. }
  3338. image.src = blobTextureURL;
  3339. };
  3340. if (Database.IsUASupportingBlobStorage) {
  3341. var xhr = new XMLHttpRequest(), blob;
  3342. xhr.open("GET", url, true);
  3343. xhr.responseType = "blob";
  3344. xhr.addEventListener("load", function () {
  3345. if (xhr.status === 200) {
  3346. // Blob as response (XHR2)
  3347. blob = xhr.response;
  3348. var transaction = _this.db.transaction(["textures"], "readwrite");
  3349. // the transaction could abort because of a QuotaExceededError error
  3350. transaction.onabort = function (event) {
  3351. try {
  3352. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3353. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3354. this.hasReachedQuota = true;
  3355. }
  3356. }
  3357. catch (ex) { }
  3358. generateBlobUrl();
  3359. };
  3360. transaction.oncomplete = function (event) {
  3361. generateBlobUrl();
  3362. };
  3363. var newTexture = { textureUrl: url, data: blob };
  3364. try {
  3365. // Put the blob into the dabase
  3366. var addRequest = transaction.objectStore("textures").put(newTexture);
  3367. addRequest.onsuccess = function (event) {
  3368. };
  3369. addRequest.onerror = function (event) {
  3370. generateBlobUrl();
  3371. };
  3372. }
  3373. catch (ex) {
  3374. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3375. if (ex.code === 25) {
  3376. Database.IsUASupportingBlobStorage = false;
  3377. }
  3378. image.src = url;
  3379. }
  3380. }
  3381. else {
  3382. image.src = url;
  3383. }
  3384. }, false);
  3385. xhr.addEventListener("error", function (event) {
  3386. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3387. image.src = url;
  3388. }, false);
  3389. xhr.send();
  3390. }
  3391. else {
  3392. image.src = url;
  3393. }
  3394. }
  3395. else {
  3396. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3397. image.src = url;
  3398. }
  3399. };
  3400. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3401. var _this = this;
  3402. var updateVersion = function (event) {
  3403. // the version is not yet in the DB or we need to update it
  3404. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3405. };
  3406. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3407. };
  3408. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3409. var _this = this;
  3410. if (this.isSupported) {
  3411. var version;
  3412. try {
  3413. var transaction = this.db.transaction(["versions"]);
  3414. transaction.oncomplete = function (event) {
  3415. if (version) {
  3416. // If the version in the JSON file is > than the version in DB
  3417. if (_this.manifestVersionFound > version.data) {
  3418. _this.mustUpdateRessources = true;
  3419. updateInDBCallback();
  3420. }
  3421. else {
  3422. callback(version.data);
  3423. }
  3424. }
  3425. else {
  3426. _this.mustUpdateRessources = true;
  3427. updateInDBCallback();
  3428. }
  3429. };
  3430. transaction.onabort = function (event) {
  3431. callback(-1);
  3432. };
  3433. var getRequest = transaction.objectStore("versions").get(url);
  3434. getRequest.onsuccess = function (event) {
  3435. version = (event.target).result;
  3436. };
  3437. getRequest.onerror = function (event) {
  3438. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3439. callback(-1);
  3440. };
  3441. }
  3442. catch (ex) {
  3443. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3444. callback(-1);
  3445. }
  3446. }
  3447. else {
  3448. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3449. callback(-1);
  3450. }
  3451. };
  3452. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3453. var _this = this;
  3454. if (this.isSupported && !this.hasReachedQuota) {
  3455. try {
  3456. // Open a transaction to the database
  3457. var transaction = this.db.transaction(["versions"], "readwrite");
  3458. // the transaction could abort because of a QuotaExceededError error
  3459. transaction.onabort = function (event) {
  3460. try {
  3461. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3462. _this.hasReachedQuota = true;
  3463. }
  3464. }
  3465. catch (ex) { }
  3466. callback(-1);
  3467. };
  3468. transaction.oncomplete = function (event) {
  3469. callback(_this.manifestVersionFound);
  3470. };
  3471. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3472. // Put the scene into the database
  3473. var addRequest = transaction.objectStore("versions").put(newVersion);
  3474. addRequest.onsuccess = function (event) {
  3475. };
  3476. addRequest.onerror = function (event) {
  3477. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3478. };
  3479. }
  3480. catch (ex) {
  3481. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3482. callback(-1);
  3483. }
  3484. }
  3485. else {
  3486. callback(-1);
  3487. }
  3488. };
  3489. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3490. var _this = this;
  3491. var completeUrl = Database.ReturnFullUrlLocation(url);
  3492. var saveAndLoadFile = function (event) {
  3493. // the scene is not yet in the DB, let's try to save it
  3494. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3495. };
  3496. this._checkVersionFromDB(completeUrl, function (version) {
  3497. if (version !== -1) {
  3498. if (!_this.mustUpdateRessources) {
  3499. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3500. }
  3501. else {
  3502. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3503. }
  3504. }
  3505. else {
  3506. errorCallback();
  3507. }
  3508. });
  3509. };
  3510. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3511. if (this.isSupported) {
  3512. var targetStore;
  3513. if (url.indexOf(".babylon") !== -1) {
  3514. targetStore = "scenes";
  3515. }
  3516. else {
  3517. targetStore = "textures";
  3518. }
  3519. var file;
  3520. var transaction = this.db.transaction([targetStore]);
  3521. transaction.oncomplete = function (event) {
  3522. if (file) {
  3523. callback(file.data);
  3524. }
  3525. else {
  3526. notInDBCallback();
  3527. }
  3528. };
  3529. transaction.onabort = function (event) {
  3530. notInDBCallback();
  3531. };
  3532. var getRequest = transaction.objectStore(targetStore).get(url);
  3533. getRequest.onsuccess = function (event) {
  3534. file = (event.target).result;
  3535. };
  3536. getRequest.onerror = function (event) {
  3537. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3538. notInDBCallback();
  3539. };
  3540. }
  3541. else {
  3542. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3543. callback();
  3544. }
  3545. };
  3546. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3547. var _this = this;
  3548. if (this.isSupported) {
  3549. var targetStore;
  3550. if (url.indexOf(".babylon") !== -1) {
  3551. targetStore = "scenes";
  3552. }
  3553. else {
  3554. targetStore = "textures";
  3555. }
  3556. // Create XHR
  3557. var xhr = new XMLHttpRequest(), fileData;
  3558. xhr.open("GET", url, true);
  3559. if (useArrayBuffer) {
  3560. xhr.responseType = "arraybuffer";
  3561. }
  3562. xhr.onprogress = progressCallback;
  3563. xhr.addEventListener("load", function () {
  3564. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3565. // Blob as response (XHR2)
  3566. //fileData = xhr.responseText;
  3567. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3568. if (!_this.hasReachedQuota) {
  3569. // Open a transaction to the database
  3570. var transaction = _this.db.transaction([targetStore], "readwrite");
  3571. // the transaction could abort because of a QuotaExceededError error
  3572. transaction.onabort = function (event) {
  3573. try {
  3574. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3575. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3576. this.hasReachedQuota = true;
  3577. }
  3578. }
  3579. catch (ex) { }
  3580. callback(fileData);
  3581. };
  3582. transaction.oncomplete = function (event) {
  3583. callback(fileData);
  3584. };
  3585. var newFile;
  3586. if (targetStore === "scenes") {
  3587. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3588. }
  3589. else {
  3590. newFile = { textureUrl: url, data: fileData };
  3591. }
  3592. try {
  3593. // Put the scene into the database
  3594. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3595. addRequest.onsuccess = function (event) {
  3596. };
  3597. addRequest.onerror = function (event) {
  3598. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3599. };
  3600. }
  3601. catch (ex) {
  3602. callback(fileData);
  3603. }
  3604. }
  3605. else {
  3606. callback(fileData);
  3607. }
  3608. }
  3609. else {
  3610. callback();
  3611. }
  3612. }, false);
  3613. xhr.addEventListener("error", function (event) {
  3614. BABYLON.Tools.Error("error on XHR request.");
  3615. callback();
  3616. }, false);
  3617. xhr.send();
  3618. }
  3619. else {
  3620. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3621. callback();
  3622. }
  3623. };
  3624. Database.IsUASupportingBlobStorage = true;
  3625. Database.IDBStorageEnabled = true;
  3626. Database.parseURL = function (url) {
  3627. var a = document.createElement('a');
  3628. a.href = url;
  3629. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3630. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3631. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3632. return absLocation;
  3633. };
  3634. Database.ReturnFullUrlLocation = function (url) {
  3635. if (url.indexOf("http:/") === -1) {
  3636. return (Database.parseURL(window.location.href) + url);
  3637. }
  3638. else {
  3639. return url;
  3640. }
  3641. };
  3642. return Database;
  3643. })();
  3644. BABYLON.Database = Database;
  3645. })(BABYLON || (BABYLON = {}));
  3646. var BABYLON;
  3647. (function (BABYLON) {
  3648. var Internals;
  3649. (function (Internals) {
  3650. /*
  3651. * Based on jsTGALoader - Javascript loader for TGA file
  3652. * By Vincent Thibault
  3653. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3654. */
  3655. var TGATools = (function () {
  3656. function TGATools() {
  3657. }
  3658. TGATools.GetTGAHeader = function (data) {
  3659. var offset = 0;
  3660. var header = {
  3661. id_length: data[offset++],
  3662. colormap_type: data[offset++],
  3663. image_type: data[offset++],
  3664. colormap_index: data[offset++] | data[offset++] << 8,
  3665. colormap_length: data[offset++] | data[offset++] << 8,
  3666. colormap_size: data[offset++],
  3667. origin: [
  3668. data[offset++] | data[offset++] << 8,
  3669. data[offset++] | data[offset++] << 8
  3670. ],
  3671. width: data[offset++] | data[offset++] << 8,
  3672. height: data[offset++] | data[offset++] << 8,
  3673. pixel_size: data[offset++],
  3674. flags: data[offset++]
  3675. };
  3676. return header;
  3677. };
  3678. TGATools.UploadContent = function (gl, data) {
  3679. // Not enough data to contain header ?
  3680. if (data.length < 19) {
  3681. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3682. return;
  3683. }
  3684. // Read Header
  3685. var offset = 18;
  3686. var header = TGATools.GetTGAHeader(data);
  3687. // Assume it's a valid Targa file.
  3688. if (header.id_length + offset > data.length) {
  3689. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3690. return;
  3691. }
  3692. // Skip not needed data
  3693. offset += header.id_length;
  3694. var use_rle = false;
  3695. var use_pal = false;
  3696. var use_rgb = false;
  3697. var use_grey = false;
  3698. // Get some informations.
  3699. switch (header.image_type) {
  3700. case TGATools._TYPE_RLE_INDEXED:
  3701. use_rle = true;
  3702. case TGATools._TYPE_INDEXED:
  3703. use_pal = true;
  3704. break;
  3705. case TGATools._TYPE_RLE_RGB:
  3706. use_rle = true;
  3707. case TGATools._TYPE_RGB:
  3708. use_rgb = true;
  3709. break;
  3710. case TGATools._TYPE_RLE_GREY:
  3711. use_rle = true;
  3712. case TGATools._TYPE_GREY:
  3713. use_grey = true;
  3714. break;
  3715. }
  3716. var pixel_data;
  3717. var numAlphaBits = header.flags & 0xf;
  3718. var pixel_size = header.pixel_size >> 3;
  3719. var pixel_total = header.width * header.height * pixel_size;
  3720. // Read palettes
  3721. var palettes;
  3722. if (use_pal) {
  3723. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3724. }
  3725. // Read LRE
  3726. if (use_rle) {
  3727. pixel_data = new Uint8Array(pixel_total);
  3728. var c, count, i;
  3729. var localOffset = 0;
  3730. var pixels = new Uint8Array(pixel_size);
  3731. while (offset < pixel_total && localOffset < pixel_total) {
  3732. c = data[offset++];
  3733. count = (c & 0x7f) + 1;
  3734. // RLE pixels
  3735. if (c & 0x80) {
  3736. // Bind pixel tmp array
  3737. for (i = 0; i < pixel_size; ++i) {
  3738. pixels[i] = data[offset++];
  3739. }
  3740. // Copy pixel array
  3741. for (i = 0; i < count; ++i) {
  3742. pixel_data.set(pixels, localOffset + i * pixel_size);
  3743. }
  3744. localOffset += pixel_size * count;
  3745. }
  3746. else {
  3747. count *= pixel_size;
  3748. for (i = 0; i < count; ++i) {
  3749. pixel_data[localOffset + i] = data[offset++];
  3750. }
  3751. localOffset += count;
  3752. }
  3753. }
  3754. }
  3755. else {
  3756. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3757. }
  3758. // Load to texture
  3759. var x_start, y_start, x_step, y_step, y_end, x_end;
  3760. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3761. default:
  3762. case TGATools._ORIGIN_UL:
  3763. x_start = 0;
  3764. x_step = 1;
  3765. x_end = header.width;
  3766. y_start = 0;
  3767. y_step = 1;
  3768. y_end = header.height;
  3769. break;
  3770. case TGATools._ORIGIN_BL:
  3771. x_start = 0;
  3772. x_step = 1;
  3773. x_end = header.width;
  3774. y_start = header.height - 1;
  3775. y_step = -1;
  3776. y_end = -1;
  3777. break;
  3778. case TGATools._ORIGIN_UR:
  3779. x_start = header.width - 1;
  3780. x_step = -1;
  3781. x_end = -1;
  3782. y_start = 0;
  3783. y_step = 1;
  3784. y_end = header.height;
  3785. break;
  3786. case TGATools._ORIGIN_BR:
  3787. x_start = header.width - 1;
  3788. x_step = -1;
  3789. x_end = -1;
  3790. y_start = header.height - 1;
  3791. y_step = -1;
  3792. y_end = -1;
  3793. break;
  3794. }
  3795. // Load the specify method
  3796. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3797. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3798. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3799. };
  3800. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3801. var image = pixel_data, colormap = palettes;
  3802. var width = header.width, height = header.height;
  3803. var color, i = 0, x, y;
  3804. var imageData = new Uint8Array(width * height * 4);
  3805. for (y = y_start; y !== y_end; y += y_step) {
  3806. for (x = x_start; x !== x_end; x += x_step, i++) {
  3807. color = image[i];
  3808. imageData[(x + width * y) * 4 + 3] = 255;
  3809. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3810. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3811. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3812. }
  3813. }
  3814. return imageData;
  3815. };
  3816. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3817. var image = pixel_data;
  3818. var width = header.width, height = header.height;
  3819. var color, i = 0, x, y;
  3820. var imageData = new Uint8Array(width * height * 4);
  3821. for (y = y_start; y !== y_end; y += y_step) {
  3822. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3823. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3824. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3825. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3826. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3827. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3828. }
  3829. }
  3830. return imageData;
  3831. };
  3832. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3833. var image = pixel_data;
  3834. var width = header.width, height = header.height;
  3835. var i = 0, x, y;
  3836. var imageData = new Uint8Array(width * height * 4);
  3837. for (y = y_start; y !== y_end; y += y_step) {
  3838. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3839. imageData[(x + width * y) * 4 + 3] = 255;
  3840. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3841. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3842. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3843. }
  3844. }
  3845. return imageData;
  3846. };
  3847. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3848. var image = pixel_data;
  3849. var width = header.width, height = header.height;
  3850. var i = 0, x, y;
  3851. var imageData = new Uint8Array(width * height * 4);
  3852. for (y = y_start; y !== y_end; y += y_step) {
  3853. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3854. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3855. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3856. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3857. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3858. }
  3859. }
  3860. return imageData;
  3861. };
  3862. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3863. var image = pixel_data;
  3864. var width = header.width, height = header.height;
  3865. var color, i = 0, x, y;
  3866. var imageData = new Uint8Array(width * height * 4);
  3867. for (y = y_start; y !== y_end; y += y_step) {
  3868. for (x = x_start; x !== x_end; x += x_step, i++) {
  3869. color = image[i];
  3870. imageData[(x + width * y) * 4 + 0] = color;
  3871. imageData[(x + width * y) * 4 + 1] = color;
  3872. imageData[(x + width * y) * 4 + 2] = color;
  3873. imageData[(x + width * y) * 4 + 3] = 255;
  3874. }
  3875. }
  3876. return imageData;
  3877. };
  3878. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3879. var image = pixel_data;
  3880. var width = header.width, height = header.height;
  3881. var i = 0, x, y;
  3882. var imageData = new Uint8Array(width * height * 4);
  3883. for (y = y_start; y !== y_end; y += y_step) {
  3884. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3885. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3886. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3887. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3888. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3889. }
  3890. }
  3891. return imageData;
  3892. };
  3893. TGATools._TYPE_NO_DATA = 0;
  3894. TGATools._TYPE_INDEXED = 1;
  3895. TGATools._TYPE_RGB = 2;
  3896. TGATools._TYPE_GREY = 3;
  3897. TGATools._TYPE_RLE_INDEXED = 9;
  3898. TGATools._TYPE_RLE_RGB = 10;
  3899. TGATools._TYPE_RLE_GREY = 11;
  3900. TGATools._ORIGIN_MASK = 0x30;
  3901. TGATools._ORIGIN_SHIFT = 0x04;
  3902. TGATools._ORIGIN_BL = 0x00;
  3903. TGATools._ORIGIN_BR = 0x01;
  3904. TGATools._ORIGIN_UL = 0x02;
  3905. TGATools._ORIGIN_UR = 0x03;
  3906. return TGATools;
  3907. })();
  3908. Internals.TGATools = TGATools;
  3909. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3910. })(BABYLON || (BABYLON = {}));
  3911. var BABYLON;
  3912. (function (BABYLON) {
  3913. var SmartArray = (function () {
  3914. function SmartArray(capacity) {
  3915. this.length = 0;
  3916. this._duplicateId = 0;
  3917. this.data = new Array(capacity);
  3918. this._id = SmartArray._GlobalId++;
  3919. }
  3920. SmartArray.prototype.push = function (value) {
  3921. this.data[this.length++] = value;
  3922. if (this.length > this.data.length) {
  3923. this.data.length *= 2;
  3924. }
  3925. if (!value.__smartArrayFlags) {
  3926. value.__smartArrayFlags = {};
  3927. }
  3928. value.__smartArrayFlags[this._id] = this._duplicateId;
  3929. };
  3930. SmartArray.prototype.pushNoDuplicate = function (value) {
  3931. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3932. return;
  3933. }
  3934. this.push(value);
  3935. };
  3936. SmartArray.prototype.sort = function (compareFn) {
  3937. this.data.sort(compareFn);
  3938. };
  3939. SmartArray.prototype.reset = function () {
  3940. this.length = 0;
  3941. this._duplicateId++;
  3942. };
  3943. SmartArray.prototype.concat = function (array) {
  3944. if (array.length === 0) {
  3945. return;
  3946. }
  3947. if (this.length + array.length > this.data.length) {
  3948. this.data.length = (this.length + array.length) * 2;
  3949. }
  3950. for (var index = 0; index < array.length; index++) {
  3951. this.data[this.length++] = (array.data || array)[index];
  3952. }
  3953. };
  3954. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3955. if (array.length === 0) {
  3956. return;
  3957. }
  3958. if (this.length + array.length > this.data.length) {
  3959. this.data.length = (this.length + array.length) * 2;
  3960. }
  3961. for (var index = 0; index < array.length; index++) {
  3962. var item = (array.data || array)[index];
  3963. this.pushNoDuplicate(item);
  3964. }
  3965. };
  3966. SmartArray.prototype.indexOf = function (value) {
  3967. var position = this.data.indexOf(value);
  3968. if (position >= this.length) {
  3969. return -1;
  3970. }
  3971. return position;
  3972. };
  3973. // Statics
  3974. SmartArray._GlobalId = 0;
  3975. return SmartArray;
  3976. })();
  3977. BABYLON.SmartArray = SmartArray;
  3978. })(BABYLON || (BABYLON = {}));
  3979. var BABYLON;
  3980. (function (BABYLON) {
  3981. var SmartCollection = (function () {
  3982. function SmartCollection(capacity) {
  3983. if (capacity === void 0) { capacity = 10; }
  3984. this.count = 0;
  3985. this._initialCapacity = capacity;
  3986. this.items = {};
  3987. this._keys = new Array(this._initialCapacity);
  3988. }
  3989. SmartCollection.prototype.add = function (key, item) {
  3990. if (this.items[key] != undefined) {
  3991. return -1;
  3992. }
  3993. this.items[key] = item;
  3994. //literal keys are always strings, but we keep source type of key in _keys array
  3995. this._keys[this.count++] = key;
  3996. if (this.count > this._keys.length) {
  3997. this._keys.length *= 2;
  3998. }
  3999. return this.count;
  4000. };
  4001. SmartCollection.prototype.remove = function (key) {
  4002. if (this.items[key] == undefined) {
  4003. return -1;
  4004. }
  4005. return this.removeItemOfIndex(this.indexOf(key));
  4006. };
  4007. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4008. if (index < this.count && index > -1) {
  4009. delete this.items[this._keys[index]];
  4010. //here, shifting by hand is better optimised than .splice
  4011. while (index < this.count) {
  4012. this._keys[index] = this._keys[index + 1];
  4013. index++;
  4014. }
  4015. }
  4016. else {
  4017. return -1;
  4018. }
  4019. return --this.count;
  4020. };
  4021. SmartCollection.prototype.indexOf = function (key) {
  4022. for (var i = 0; i !== this.count; i++) {
  4023. if (this._keys[i] === key) {
  4024. return i;
  4025. }
  4026. }
  4027. return -1;
  4028. };
  4029. SmartCollection.prototype.item = function (key) {
  4030. return this.items[key];
  4031. };
  4032. SmartCollection.prototype.getAllKeys = function () {
  4033. if (this.count > 0) {
  4034. var keys = new Array(this.count);
  4035. for (var i = 0; i < this.count; i++) {
  4036. keys[i] = this._keys[i];
  4037. }
  4038. return keys;
  4039. }
  4040. else {
  4041. return undefined;
  4042. }
  4043. };
  4044. SmartCollection.prototype.getKeyByIndex = function (index) {
  4045. if (index < this.count && index > -1) {
  4046. return this._keys[index];
  4047. }
  4048. else {
  4049. return undefined;
  4050. }
  4051. };
  4052. SmartCollection.prototype.getItemByIndex = function (index) {
  4053. if (index < this.count && index > -1) {
  4054. return this.items[this._keys[index]];
  4055. }
  4056. else {
  4057. return undefined;
  4058. }
  4059. };
  4060. SmartCollection.prototype.empty = function () {
  4061. if (this.count > 0) {
  4062. this.count = 0;
  4063. this.items = {};
  4064. this._keys = new Array(this._initialCapacity);
  4065. }
  4066. };
  4067. SmartCollection.prototype.forEach = function (block) {
  4068. var key;
  4069. for (key in this.items) {
  4070. if (this.items.hasOwnProperty(key)) {
  4071. block(this.items[key]);
  4072. }
  4073. }
  4074. };
  4075. return SmartCollection;
  4076. })();
  4077. BABYLON.SmartCollection = SmartCollection;
  4078. })(BABYLON || (BABYLON = {}));
  4079. var BABYLON;
  4080. (function (BABYLON) {
  4081. // Screenshots
  4082. var screenshotCanvas;
  4083. var cloneValue = function (source, destinationObject) {
  4084. if (!source)
  4085. return null;
  4086. if (source instanceof BABYLON.Mesh) {
  4087. return null;
  4088. }
  4089. if (source instanceof BABYLON.SubMesh) {
  4090. return source.clone(destinationObject);
  4091. }
  4092. else if (source.clone) {
  4093. return source.clone();
  4094. }
  4095. return null;
  4096. };
  4097. var Tools = (function () {
  4098. function Tools() {
  4099. }
  4100. Tools.ToHex = function (i) {
  4101. var str = i.toString(16);
  4102. if (i <= 15) {
  4103. return ("0" + str).toUpperCase();
  4104. }
  4105. return str.toUpperCase();
  4106. };
  4107. Tools.SetImmediate = function (action) {
  4108. if (window.setImmediate) {
  4109. window.setImmediate(action);
  4110. }
  4111. else {
  4112. setTimeout(action, 1);
  4113. }
  4114. };
  4115. Tools.IsExponentOfTwo = function (value) {
  4116. var count = 1;
  4117. do {
  4118. count *= 2;
  4119. } while (count < value);
  4120. return count === value;
  4121. };
  4122. Tools.GetExponentOfTwo = function (value, max) {
  4123. var count = 1;
  4124. do {
  4125. count *= 2;
  4126. } while (count < value);
  4127. if (count > max)
  4128. count = max;
  4129. return count;
  4130. };
  4131. Tools.GetFilename = function (path) {
  4132. var index = path.lastIndexOf("/");
  4133. if (index < 0)
  4134. return path;
  4135. return path.substring(index + 1);
  4136. };
  4137. Tools.GetDOMTextContent = function (element) {
  4138. var result = "";
  4139. var child = element.firstChild;
  4140. while (child) {
  4141. if (child.nodeType === 3) {
  4142. result += child.textContent;
  4143. }
  4144. child = child.nextSibling;
  4145. }
  4146. return result;
  4147. };
  4148. Tools.ToDegrees = function (angle) {
  4149. return angle * 180 / Math.PI;
  4150. };
  4151. Tools.ToRadians = function (angle) {
  4152. return angle * Math.PI / 180;
  4153. };
  4154. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4155. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4156. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4157. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4158. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4159. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4160. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4161. }
  4162. return {
  4163. minimum: minimum,
  4164. maximum: maximum
  4165. };
  4166. };
  4167. Tools.ExtractMinAndMax = function (positions, start, count) {
  4168. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4169. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4170. for (var index = start; index < start + count; index++) {
  4171. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4172. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4173. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4174. }
  4175. return {
  4176. minimum: minimum,
  4177. maximum: maximum
  4178. };
  4179. };
  4180. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4181. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4182. return undefined;
  4183. return Array.isArray(obj) ? obj : [obj];
  4184. };
  4185. // Misc.
  4186. Tools.GetPointerPrefix = function () {
  4187. var eventPrefix = "pointer";
  4188. // Check if hand.js is referenced or if the browser natively supports pointer events
  4189. if (!navigator.pointerEnabled) {
  4190. eventPrefix = "mouse";
  4191. }
  4192. return eventPrefix;
  4193. };
  4194. Tools.QueueNewFrame = function (func) {
  4195. if (window.requestAnimationFrame)
  4196. window.requestAnimationFrame(func);
  4197. else if (window.msRequestAnimationFrame)
  4198. window.msRequestAnimationFrame(func);
  4199. else if (window.webkitRequestAnimationFrame)
  4200. window.webkitRequestAnimationFrame(func);
  4201. else if (window.mozRequestAnimationFrame)
  4202. window.mozRequestAnimationFrame(func);
  4203. else if (window.oRequestAnimationFrame)
  4204. window.oRequestAnimationFrame(func);
  4205. else {
  4206. window.setTimeout(func, 16);
  4207. }
  4208. };
  4209. Tools.RequestFullscreen = function (element) {
  4210. if (element.requestFullscreen)
  4211. element.requestFullscreen();
  4212. else if (element.msRequestFullscreen)
  4213. element.msRequestFullscreen();
  4214. else if (element.webkitRequestFullscreen)
  4215. element.webkitRequestFullscreen();
  4216. else if (element.mozRequestFullScreen)
  4217. element.mozRequestFullScreen();
  4218. };
  4219. Tools.ExitFullscreen = function () {
  4220. if (document.exitFullscreen) {
  4221. document.exitFullscreen();
  4222. }
  4223. else if (document.mozCancelFullScreen) {
  4224. document.mozCancelFullScreen();
  4225. }
  4226. else if (document.webkitCancelFullScreen) {
  4227. document.webkitCancelFullScreen();
  4228. }
  4229. else if (document.msCancelFullScreen) {
  4230. document.msCancelFullScreen();
  4231. }
  4232. };
  4233. // External files
  4234. Tools.CleanUrl = function (url) {
  4235. url = url.replace(/#/mg, "%23");
  4236. return url;
  4237. };
  4238. Tools.LoadImage = function (url, onload, onerror, database) {
  4239. url = Tools.CleanUrl(url);
  4240. var img = new Image();
  4241. if (url.substr(0, 5) !== "data:")
  4242. img.crossOrigin = 'anonymous';
  4243. img.onload = function () {
  4244. onload(img);
  4245. };
  4246. img.onerror = function (err) {
  4247. Tools.Error("Error while trying to load texture: " + url);
  4248. 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";
  4249. onload(img);
  4250. };
  4251. var noIndexedDB = function () {
  4252. img.src = url;
  4253. };
  4254. var loadFromIndexedDB = function () {
  4255. database.loadImageFromDB(url, img);
  4256. };
  4257. //ANY database to do!
  4258. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4259. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4260. }
  4261. else {
  4262. if (url.indexOf("file:") === -1) {
  4263. noIndexedDB();
  4264. }
  4265. else {
  4266. try {
  4267. var textureName = url.substring(5);
  4268. var blobURL;
  4269. try {
  4270. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4271. }
  4272. catch (ex) {
  4273. // Chrome doesn't support oneTimeOnly parameter
  4274. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4275. }
  4276. img.src = blobURL;
  4277. }
  4278. catch (e) {
  4279. img.src = null;
  4280. }
  4281. }
  4282. }
  4283. return img;
  4284. };
  4285. //ANY
  4286. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4287. url = Tools.CleanUrl(url);
  4288. var noIndexedDB = function () {
  4289. var request = new XMLHttpRequest();
  4290. var loadUrl = Tools.BaseUrl + url;
  4291. request.open('GET', loadUrl, true);
  4292. if (useArrayBuffer) {
  4293. request.responseType = "arraybuffer";
  4294. }
  4295. request.onprogress = progressCallBack;
  4296. request.onreadystatechange = function () {
  4297. if (request.readyState === 4) {
  4298. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4299. callback(!useArrayBuffer ? request.responseText : request.response);
  4300. }
  4301. else {
  4302. if (onError) {
  4303. onError();
  4304. }
  4305. else {
  4306. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4307. }
  4308. }
  4309. }
  4310. };
  4311. request.send(null);
  4312. };
  4313. var loadFromIndexedDB = function () {
  4314. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4315. };
  4316. if (url.indexOf("file:") !== -1) {
  4317. var fileName = url.substring(5);
  4318. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4319. }
  4320. else {
  4321. // Caching all files
  4322. if (database && database.enableSceneOffline) {
  4323. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4324. }
  4325. else {
  4326. noIndexedDB();
  4327. }
  4328. }
  4329. };
  4330. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4331. var reader = new FileReader();
  4332. reader.onload = function (e) {
  4333. //target doesn't have result from ts 1.3
  4334. callback(e.target['result']);
  4335. };
  4336. reader.onprogress = progressCallback;
  4337. reader.readAsDataURL(fileToLoad);
  4338. };
  4339. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4340. var reader = new FileReader();
  4341. reader.onerror = function (e) {
  4342. Tools.Log("Error while reading file: " + fileToLoad.name);
  4343. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4344. };
  4345. reader.onload = function (e) {
  4346. //target doesn't have result from ts 1.3
  4347. callback(e.target['result']);
  4348. };
  4349. reader.onprogress = progressCallBack;
  4350. if (!useArrayBuffer) {
  4351. // Asynchronous read
  4352. reader.readAsText(fileToLoad);
  4353. }
  4354. else {
  4355. reader.readAsArrayBuffer(fileToLoad);
  4356. }
  4357. };
  4358. //returns a downloadable url to a file content.
  4359. Tools.FileAsURL = function (content) {
  4360. var fileBlob = new Blob([content]);
  4361. var url = window.URL || window.webkitURL;
  4362. var link = url.createObjectURL(fileBlob);
  4363. return link;
  4364. };
  4365. // Misc.
  4366. Tools.Clamp = function (value, min, max) {
  4367. if (min === void 0) { min = 0; }
  4368. if (max === void 0) { max = 1; }
  4369. return Math.min(max, Math.max(min, value));
  4370. };
  4371. // Returns -1 when value is a negative number and
  4372. // +1 when value is a positive number.
  4373. Tools.Sign = function (value) {
  4374. value = +value; // convert to a number
  4375. if (value === 0 || isNaN(value))
  4376. return value;
  4377. return value > 0 ? 1 : -1;
  4378. };
  4379. Tools.Format = function (value, decimals) {
  4380. if (decimals === void 0) { decimals = 2; }
  4381. return value.toFixed(decimals);
  4382. };
  4383. Tools.CheckExtends = function (v, min, max) {
  4384. if (v.x < min.x)
  4385. min.x = v.x;
  4386. if (v.y < min.y)
  4387. min.y = v.y;
  4388. if (v.z < min.z)
  4389. min.z = v.z;
  4390. if (v.x > max.x)
  4391. max.x = v.x;
  4392. if (v.y > max.y)
  4393. max.y = v.y;
  4394. if (v.z > max.z)
  4395. max.z = v.z;
  4396. };
  4397. Tools.WithinEpsilon = function (a, b, epsilon) {
  4398. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4399. var num = a - b;
  4400. return -epsilon <= num && num <= epsilon;
  4401. };
  4402. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4403. for (var prop in source) {
  4404. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4405. continue;
  4406. }
  4407. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4408. continue;
  4409. }
  4410. var sourceValue = source[prop];
  4411. var typeOfSourceValue = typeof sourceValue;
  4412. if (typeOfSourceValue === "function") {
  4413. continue;
  4414. }
  4415. if (typeOfSourceValue === "object") {
  4416. if (sourceValue instanceof Array) {
  4417. destination[prop] = [];
  4418. if (sourceValue.length > 0) {
  4419. if (typeof sourceValue[0] == "object") {
  4420. for (var index = 0; index < sourceValue.length; index++) {
  4421. var clonedValue = cloneValue(sourceValue[index], destination);
  4422. if (destination[prop].indexOf(clonedValue) === -1) {
  4423. destination[prop].push(clonedValue);
  4424. }
  4425. }
  4426. }
  4427. else {
  4428. destination[prop] = sourceValue.slice(0);
  4429. }
  4430. }
  4431. }
  4432. else {
  4433. destination[prop] = cloneValue(sourceValue, destination);
  4434. }
  4435. }
  4436. else {
  4437. destination[prop] = sourceValue;
  4438. }
  4439. }
  4440. };
  4441. Tools.IsEmpty = function (obj) {
  4442. for (var i in obj) {
  4443. return false;
  4444. }
  4445. return true;
  4446. };
  4447. Tools.RegisterTopRootEvents = function (events) {
  4448. for (var index = 0; index < events.length; index++) {
  4449. var event = events[index];
  4450. window.addEventListener(event.name, event.handler, false);
  4451. try {
  4452. if (window.parent) {
  4453. window.parent.addEventListener(event.name, event.handler, false);
  4454. }
  4455. }
  4456. catch (e) {
  4457. }
  4458. }
  4459. };
  4460. Tools.UnregisterTopRootEvents = function (events) {
  4461. for (var index = 0; index < events.length; index++) {
  4462. var event = events[index];
  4463. window.removeEventListener(event.name, event.handler);
  4464. try {
  4465. if (window.parent) {
  4466. window.parent.removeEventListener(event.name, event.handler);
  4467. }
  4468. }
  4469. catch (e) {
  4470. }
  4471. }
  4472. };
  4473. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4474. // Read the contents of the framebuffer
  4475. var numberOfChannelsByLine = width * 4;
  4476. var halfHeight = height / 2;
  4477. //Reading datas from WebGL
  4478. var data = engine.readPixels(0, 0, width, height);
  4479. //To flip image on Y axis.
  4480. for (var i = 0; i < halfHeight; i++) {
  4481. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4482. var currentCell = j + i * numberOfChannelsByLine;
  4483. var targetLine = height - i - 1;
  4484. var targetCell = j + targetLine * numberOfChannelsByLine;
  4485. var temp = data[currentCell];
  4486. data[currentCell] = data[targetCell];
  4487. data[targetCell] = temp;
  4488. }
  4489. }
  4490. // Create a 2D canvas to store the result
  4491. if (!screenshotCanvas) {
  4492. screenshotCanvas = document.createElement('canvas');
  4493. }
  4494. screenshotCanvas.width = width;
  4495. screenshotCanvas.height = height;
  4496. var context = screenshotCanvas.getContext('2d');
  4497. // Copy the pixels to a 2D canvas
  4498. var imageData = context.createImageData(width, height);
  4499. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4500. var castData = imageData.data;
  4501. castData.set(data);
  4502. context.putImageData(imageData, 0, 0);
  4503. var base64Image = screenshotCanvas.toDataURL();
  4504. if (successCallback) {
  4505. successCallback(base64Image);
  4506. }
  4507. else {
  4508. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4509. if (("download" in document.createElement("a"))) {
  4510. var a = window.document.createElement("a");
  4511. a.href = base64Image;
  4512. var date = new Date();
  4513. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4514. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4515. window.document.body.appendChild(a);
  4516. a.addEventListener("click", function () {
  4517. a.parentElement.removeChild(a);
  4518. });
  4519. a.click();
  4520. }
  4521. else {
  4522. var newWindow = window.open("");
  4523. var img = newWindow.document.createElement("img");
  4524. img.src = base64Image;
  4525. newWindow.document.body.appendChild(img);
  4526. }
  4527. }
  4528. };
  4529. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4530. var width;
  4531. var height;
  4532. //If a precision value is specified
  4533. if (size.precision) {
  4534. width = Math.round(engine.getRenderWidth() * size.precision);
  4535. height = Math.round(width / engine.getAspectRatio(camera));
  4536. size = { width: width, height: height };
  4537. }
  4538. else if (size.width && size.height) {
  4539. width = size.width;
  4540. height = size.height;
  4541. }
  4542. else if (size.width && !size.height) {
  4543. width = size.width;
  4544. height = Math.round(width / engine.getAspectRatio(camera));
  4545. size = { width: width, height: height };
  4546. }
  4547. else if (size.height && !size.width) {
  4548. height = size.height;
  4549. width = Math.round(height * engine.getAspectRatio(camera));
  4550. size = { width: width, height: height };
  4551. }
  4552. else if (!isNaN(size)) {
  4553. height = size;
  4554. width = size;
  4555. }
  4556. else {
  4557. Tools.Error("Invalid 'size' parameter !");
  4558. return;
  4559. }
  4560. var scene = camera.getScene();
  4561. var previousCamera = null;
  4562. if (scene.activeCamera !== camera) {
  4563. previousCamera = scene.activeCamera;
  4564. scene.activeCamera = camera;
  4565. }
  4566. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4567. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4568. texture.renderList = scene.meshes;
  4569. texture.onAfterRender = function () {
  4570. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4571. };
  4572. scene.incrementRenderId();
  4573. texture.render(true);
  4574. texture.dispose();
  4575. if (previousCamera) {
  4576. scene.activeCamera = previousCamera;
  4577. }
  4578. };
  4579. // XHR response validator for local file scenario
  4580. Tools.ValidateXHRData = function (xhr, dataType) {
  4581. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4582. if (dataType === void 0) { dataType = 7; }
  4583. try {
  4584. if (dataType & 1) {
  4585. if (xhr.responseText && xhr.responseText.length > 0) {
  4586. return true;
  4587. }
  4588. else if (dataType === 1) {
  4589. return false;
  4590. }
  4591. }
  4592. if (dataType & 2) {
  4593. // Check header width and height since there is no "TGA" magic number
  4594. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4595. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4596. return true;
  4597. }
  4598. else if (dataType === 2) {
  4599. return false;
  4600. }
  4601. }
  4602. if (dataType & 4) {
  4603. // Check for the "DDS" magic number
  4604. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4605. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4606. return true;
  4607. }
  4608. else {
  4609. return false;
  4610. }
  4611. }
  4612. }
  4613. catch (e) {
  4614. }
  4615. return false;
  4616. };
  4617. Object.defineProperty(Tools, "NoneLogLevel", {
  4618. get: function () {
  4619. return Tools._NoneLogLevel;
  4620. },
  4621. enumerable: true,
  4622. configurable: true
  4623. });
  4624. Object.defineProperty(Tools, "MessageLogLevel", {
  4625. get: function () {
  4626. return Tools._MessageLogLevel;
  4627. },
  4628. enumerable: true,
  4629. configurable: true
  4630. });
  4631. Object.defineProperty(Tools, "WarningLogLevel", {
  4632. get: function () {
  4633. return Tools._WarningLogLevel;
  4634. },
  4635. enumerable: true,
  4636. configurable: true
  4637. });
  4638. Object.defineProperty(Tools, "ErrorLogLevel", {
  4639. get: function () {
  4640. return Tools._ErrorLogLevel;
  4641. },
  4642. enumerable: true,
  4643. configurable: true
  4644. });
  4645. Object.defineProperty(Tools, "AllLogLevel", {
  4646. get: function () {
  4647. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4648. },
  4649. enumerable: true,
  4650. configurable: true
  4651. });
  4652. Tools._AddLogEntry = function (entry) {
  4653. Tools._LogCache = entry + Tools._LogCache;
  4654. if (Tools.OnNewCacheEntry) {
  4655. Tools.OnNewCacheEntry(entry);
  4656. }
  4657. };
  4658. Tools._FormatMessage = function (message) {
  4659. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4660. var date = new Date();
  4661. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4662. };
  4663. Tools._LogDisabled = function (message) {
  4664. // nothing to do
  4665. };
  4666. Tools._LogEnabled = function (message) {
  4667. var formattedMessage = Tools._FormatMessage(message);
  4668. console.log("BJS - " + formattedMessage);
  4669. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4670. Tools._AddLogEntry(entry);
  4671. };
  4672. Tools._WarnDisabled = function (message) {
  4673. // nothing to do
  4674. };
  4675. Tools._WarnEnabled = function (message) {
  4676. var formattedMessage = Tools._FormatMessage(message);
  4677. console.warn("BJS - " + formattedMessage);
  4678. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4679. Tools._AddLogEntry(entry);
  4680. };
  4681. Tools._ErrorDisabled = function (message) {
  4682. // nothing to do
  4683. };
  4684. Tools._ErrorEnabled = function (message) {
  4685. Tools.errorsCount++;
  4686. var formattedMessage = Tools._FormatMessage(message);
  4687. console.error("BJS - " + formattedMessage);
  4688. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4689. Tools._AddLogEntry(entry);
  4690. };
  4691. Object.defineProperty(Tools, "LogCache", {
  4692. get: function () {
  4693. return Tools._LogCache;
  4694. },
  4695. enumerable: true,
  4696. configurable: true
  4697. });
  4698. Tools.ClearLogCache = function () {
  4699. Tools._LogCache = "";
  4700. Tools.errorsCount = 0;
  4701. };
  4702. Object.defineProperty(Tools, "LogLevels", {
  4703. set: function (level) {
  4704. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4705. Tools.Log = Tools._LogEnabled;
  4706. }
  4707. else {
  4708. Tools.Log = Tools._LogDisabled;
  4709. }
  4710. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4711. Tools.Warn = Tools._WarnEnabled;
  4712. }
  4713. else {
  4714. Tools.Warn = Tools._WarnDisabled;
  4715. }
  4716. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4717. Tools.Error = Tools._ErrorEnabled;
  4718. }
  4719. else {
  4720. Tools.Error = Tools._ErrorDisabled;
  4721. }
  4722. },
  4723. enumerable: true,
  4724. configurable: true
  4725. });
  4726. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4727. get: function () {
  4728. return Tools._PerformanceNoneLogLevel;
  4729. },
  4730. enumerable: true,
  4731. configurable: true
  4732. });
  4733. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4734. get: function () {
  4735. return Tools._PerformanceUserMarkLogLevel;
  4736. },
  4737. enumerable: true,
  4738. configurable: true
  4739. });
  4740. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4741. get: function () {
  4742. return Tools._PerformanceConsoleLogLevel;
  4743. },
  4744. enumerable: true,
  4745. configurable: true
  4746. });
  4747. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4748. set: function (level) {
  4749. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4750. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4751. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4752. return;
  4753. }
  4754. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4755. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4756. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4757. return;
  4758. }
  4759. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4760. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4761. },
  4762. enumerable: true,
  4763. configurable: true
  4764. });
  4765. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4766. };
  4767. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4768. };
  4769. Tools._StartUserMark = function (counterName, condition) {
  4770. if (condition === void 0) { condition = true; }
  4771. if (!condition || !Tools._performance.mark) {
  4772. return;
  4773. }
  4774. Tools._performance.mark(counterName + "-Begin");
  4775. };
  4776. Tools._EndUserMark = function (counterName, condition) {
  4777. if (condition === void 0) { condition = true; }
  4778. if (!condition || !Tools._performance.mark) {
  4779. return;
  4780. }
  4781. Tools._performance.mark(counterName + "-End");
  4782. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4783. };
  4784. Tools._StartPerformanceConsole = function (counterName, condition) {
  4785. if (condition === void 0) { condition = true; }
  4786. if (!condition) {
  4787. return;
  4788. }
  4789. Tools._StartUserMark(counterName, condition);
  4790. if (console.time) {
  4791. console.time(counterName);
  4792. }
  4793. };
  4794. Tools._EndPerformanceConsole = function (counterName, condition) {
  4795. if (condition === void 0) { condition = true; }
  4796. if (!condition) {
  4797. return;
  4798. }
  4799. Tools._EndUserMark(counterName, condition);
  4800. if (console.time) {
  4801. console.timeEnd(counterName);
  4802. }
  4803. };
  4804. Object.defineProperty(Tools, "Now", {
  4805. get: function () {
  4806. if (window.performance && window.performance.now) {
  4807. return window.performance.now();
  4808. }
  4809. return new Date().getTime();
  4810. },
  4811. enumerable: true,
  4812. configurable: true
  4813. });
  4814. Tools.BaseUrl = "";
  4815. // Logs
  4816. Tools._NoneLogLevel = 0;
  4817. Tools._MessageLogLevel = 1;
  4818. Tools._WarningLogLevel = 2;
  4819. Tools._ErrorLogLevel = 4;
  4820. Tools._LogCache = "";
  4821. Tools.errorsCount = 0;
  4822. Tools.Log = Tools._LogEnabled;
  4823. Tools.Warn = Tools._WarnEnabled;
  4824. Tools.Error = Tools._ErrorEnabled;
  4825. // Performances
  4826. Tools._PerformanceNoneLogLevel = 0;
  4827. Tools._PerformanceUserMarkLogLevel = 1;
  4828. Tools._PerformanceConsoleLogLevel = 2;
  4829. Tools._performance = window.performance;
  4830. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4831. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4832. return Tools;
  4833. })();
  4834. BABYLON.Tools = Tools;
  4835. /**
  4836. * An implementation of a loop for asynchronous functions.
  4837. */
  4838. var AsyncLoop = (function () {
  4839. /**
  4840. * Constroctor.
  4841. * @param iterations the number of iterations.
  4842. * @param _fn the function to run each iteration
  4843. * @param _successCallback the callback that will be called upon succesful execution
  4844. * @param offset starting offset.
  4845. */
  4846. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4847. if (offset === void 0) { offset = 0; }
  4848. this.iterations = iterations;
  4849. this._fn = _fn;
  4850. this._successCallback = _successCallback;
  4851. this.index = offset - 1;
  4852. this._done = false;
  4853. }
  4854. /**
  4855. * Execute the next iteration. Must be called after the last iteration was finished.
  4856. */
  4857. AsyncLoop.prototype.executeNext = function () {
  4858. if (!this._done) {
  4859. if (this.index + 1 < this.iterations) {
  4860. ++this.index;
  4861. this._fn(this);
  4862. }
  4863. else {
  4864. this.breakLoop();
  4865. }
  4866. }
  4867. };
  4868. /**
  4869. * Break the loop and run the success callback.
  4870. */
  4871. AsyncLoop.prototype.breakLoop = function () {
  4872. this._done = true;
  4873. this._successCallback();
  4874. };
  4875. /**
  4876. * Helper function
  4877. */
  4878. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4879. if (offset === void 0) { offset = 0; }
  4880. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4881. loop.executeNext();
  4882. return loop;
  4883. };
  4884. /**
  4885. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4886. * @param iterations total number of iterations
  4887. * @param syncedIterations number of synchronous iterations in each async iteration.
  4888. * @param fn the function to call each iteration.
  4889. * @param callback a success call back that will be called when iterating stops.
  4890. * @param breakFunction a break condition (optional)
  4891. * @param timeout timeout settings for the setTimeout function. default - 0.
  4892. * @constructor
  4893. */
  4894. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4895. if (timeout === void 0) { timeout = 0; }
  4896. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4897. if (breakFunction && breakFunction())
  4898. loop.breakLoop();
  4899. else {
  4900. setTimeout(function () {
  4901. for (var i = 0; i < syncedIterations; ++i) {
  4902. var iteration = (loop.index * syncedIterations) + i;
  4903. if (iteration >= iterations)
  4904. break;
  4905. fn(iteration);
  4906. if (breakFunction && breakFunction()) {
  4907. loop.breakLoop();
  4908. break;
  4909. }
  4910. }
  4911. loop.executeNext();
  4912. }, timeout);
  4913. }
  4914. }, callback);
  4915. };
  4916. return AsyncLoop;
  4917. })();
  4918. BABYLON.AsyncLoop = AsyncLoop;
  4919. })(BABYLON || (BABYLON = {}));
  4920. var BABYLON;
  4921. (function (BABYLON) {
  4922. var _DepthCullingState = (function () {
  4923. function _DepthCullingState() {
  4924. this._isDepthTestDirty = false;
  4925. this._isDepthMaskDirty = false;
  4926. this._isDepthFuncDirty = false;
  4927. this._isCullFaceDirty = false;
  4928. this._isCullDirty = false;
  4929. this._isZOffsetDirty = false;
  4930. }
  4931. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4932. get: function () {
  4933. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4934. },
  4935. enumerable: true,
  4936. configurable: true
  4937. });
  4938. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4939. get: function () {
  4940. return this._zOffset;
  4941. },
  4942. set: function (value) {
  4943. if (this._zOffset === value) {
  4944. return;
  4945. }
  4946. this._zOffset = value;
  4947. this._isZOffsetDirty = true;
  4948. },
  4949. enumerable: true,
  4950. configurable: true
  4951. });
  4952. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4953. get: function () {
  4954. return this._cullFace;
  4955. },
  4956. set: function (value) {
  4957. if (this._cullFace === value) {
  4958. return;
  4959. }
  4960. this._cullFace = value;
  4961. this._isCullFaceDirty = true;
  4962. },
  4963. enumerable: true,
  4964. configurable: true
  4965. });
  4966. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4967. get: function () {
  4968. return this._cull;
  4969. },
  4970. set: function (value) {
  4971. if (this._cull === value) {
  4972. return;
  4973. }
  4974. this._cull = value;
  4975. this._isCullDirty = true;
  4976. },
  4977. enumerable: true,
  4978. configurable: true
  4979. });
  4980. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4981. get: function () {
  4982. return this._depthFunc;
  4983. },
  4984. set: function (value) {
  4985. if (this._depthFunc === value) {
  4986. return;
  4987. }
  4988. this._depthFunc = value;
  4989. this._isDepthFuncDirty = true;
  4990. },
  4991. enumerable: true,
  4992. configurable: true
  4993. });
  4994. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4995. get: function () {
  4996. return this._depthMask;
  4997. },
  4998. set: function (value) {
  4999. if (this._depthMask === value) {
  5000. return;
  5001. }
  5002. this._depthMask = value;
  5003. this._isDepthMaskDirty = true;
  5004. },
  5005. enumerable: true,
  5006. configurable: true
  5007. });
  5008. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5009. get: function () {
  5010. return this._depthTest;
  5011. },
  5012. set: function (value) {
  5013. if (this._depthTest === value) {
  5014. return;
  5015. }
  5016. this._depthTest = value;
  5017. this._isDepthTestDirty = true;
  5018. },
  5019. enumerable: true,
  5020. configurable: true
  5021. });
  5022. _DepthCullingState.prototype.reset = function () {
  5023. this._depthMask = true;
  5024. this._depthTest = true;
  5025. this._depthFunc = null;
  5026. this._cull = null;
  5027. this._cullFace = null;
  5028. this._zOffset = 0;
  5029. this._isDepthTestDirty = true;
  5030. this._isDepthMaskDirty = true;
  5031. this._isDepthFuncDirty = false;
  5032. this._isCullFaceDirty = false;
  5033. this._isCullDirty = false;
  5034. this._isZOffsetDirty = false;
  5035. };
  5036. _DepthCullingState.prototype.apply = function (gl) {
  5037. if (!this.isDirty) {
  5038. return;
  5039. }
  5040. // Cull
  5041. if (this._isCullDirty) {
  5042. if (this.cull) {
  5043. gl.enable(gl.CULL_FACE);
  5044. }
  5045. else {
  5046. gl.disable(gl.CULL_FACE);
  5047. }
  5048. this._isCullDirty = false;
  5049. }
  5050. // Cull face
  5051. if (this._isCullFaceDirty) {
  5052. gl.cullFace(this.cullFace);
  5053. this._isCullFaceDirty = false;
  5054. }
  5055. // Depth mask
  5056. if (this._isDepthMaskDirty) {
  5057. gl.depthMask(this.depthMask);
  5058. this._isDepthMaskDirty = false;
  5059. }
  5060. // Depth test
  5061. if (this._isDepthTestDirty) {
  5062. if (this.depthTest) {
  5063. gl.enable(gl.DEPTH_TEST);
  5064. }
  5065. else {
  5066. gl.disable(gl.DEPTH_TEST);
  5067. }
  5068. this._isDepthTestDirty = false;
  5069. }
  5070. // Depth func
  5071. if (this._isDepthFuncDirty) {
  5072. gl.depthFunc(this.depthFunc);
  5073. this._isDepthFuncDirty = false;
  5074. }
  5075. // zOffset
  5076. if (this._isZOffsetDirty) {
  5077. if (this.zOffset) {
  5078. gl.enable(gl.POLYGON_OFFSET_FILL);
  5079. gl.polygonOffset(this.zOffset, 0);
  5080. }
  5081. else {
  5082. gl.disable(gl.POLYGON_OFFSET_FILL);
  5083. }
  5084. this._isZOffsetDirty = false;
  5085. }
  5086. };
  5087. return _DepthCullingState;
  5088. })();
  5089. BABYLON._DepthCullingState = _DepthCullingState;
  5090. var _AlphaState = (function () {
  5091. function _AlphaState() {
  5092. this._isAlphaBlendDirty = false;
  5093. this._isBlendFunctionParametersDirty = false;
  5094. this._alphaBlend = false;
  5095. this._blendFunctionParameters = new Array(4);
  5096. }
  5097. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5098. get: function () {
  5099. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5100. },
  5101. enumerable: true,
  5102. configurable: true
  5103. });
  5104. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5105. get: function () {
  5106. return this._alphaBlend;
  5107. },
  5108. set: function (value) {
  5109. if (this._alphaBlend === value) {
  5110. return;
  5111. }
  5112. this._alphaBlend = value;
  5113. this._isAlphaBlendDirty = true;
  5114. },
  5115. enumerable: true,
  5116. configurable: true
  5117. });
  5118. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5119. if (this._blendFunctionParameters[0] === value0 &&
  5120. this._blendFunctionParameters[1] === value1 &&
  5121. this._blendFunctionParameters[2] === value2 &&
  5122. this._blendFunctionParameters[3] === value3) {
  5123. return;
  5124. }
  5125. this._blendFunctionParameters[0] = value0;
  5126. this._blendFunctionParameters[1] = value1;
  5127. this._blendFunctionParameters[2] = value2;
  5128. this._blendFunctionParameters[3] = value3;
  5129. this._isBlendFunctionParametersDirty = true;
  5130. };
  5131. _AlphaState.prototype.reset = function () {
  5132. this._alphaBlend = false;
  5133. this._blendFunctionParameters[0] = null;
  5134. this._blendFunctionParameters[1] = null;
  5135. this._blendFunctionParameters[2] = null;
  5136. this._blendFunctionParameters[3] = null;
  5137. this._isAlphaBlendDirty = true;
  5138. this._isBlendFunctionParametersDirty = false;
  5139. };
  5140. _AlphaState.prototype.apply = function (gl) {
  5141. if (!this.isDirty) {
  5142. return;
  5143. }
  5144. // Alpha blend
  5145. if (this._isAlphaBlendDirty) {
  5146. if (this._alphaBlend) {
  5147. gl.enable(gl.BLEND);
  5148. }
  5149. else {
  5150. gl.disable(gl.BLEND);
  5151. }
  5152. this._isAlphaBlendDirty = false;
  5153. }
  5154. // Alpha function
  5155. if (this._isBlendFunctionParametersDirty) {
  5156. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5157. this._isBlendFunctionParametersDirty = false;
  5158. }
  5159. };
  5160. return _AlphaState;
  5161. })();
  5162. BABYLON._AlphaState = _AlphaState;
  5163. var compileShader = function (gl, source, type, defines) {
  5164. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5165. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5166. gl.compileShader(shader);
  5167. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5168. throw new Error(gl.getShaderInfoLog(shader));
  5169. }
  5170. return shader;
  5171. };
  5172. var getWebGLTextureType = function (gl, type) {
  5173. var textureType = gl.UNSIGNED_BYTE;
  5174. if (type === Engine.TEXTURETYPE_FLOAT)
  5175. textureType = gl.FLOAT;
  5176. return textureType;
  5177. };
  5178. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5179. var magFilter = gl.NEAREST;
  5180. var minFilter = gl.NEAREST;
  5181. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5182. magFilter = gl.LINEAR;
  5183. if (generateMipMaps) {
  5184. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5185. }
  5186. else {
  5187. minFilter = gl.LINEAR;
  5188. }
  5189. }
  5190. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5191. magFilter = gl.LINEAR;
  5192. if (generateMipMaps) {
  5193. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5194. }
  5195. else {
  5196. minFilter = gl.LINEAR;
  5197. }
  5198. }
  5199. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5200. magFilter = gl.NEAREST;
  5201. if (generateMipMaps) {
  5202. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5203. }
  5204. else {
  5205. minFilter = gl.NEAREST;
  5206. }
  5207. }
  5208. return {
  5209. min: minFilter,
  5210. mag: magFilter
  5211. };
  5212. };
  5213. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5214. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5215. var engine = scene.getEngine();
  5216. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5217. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5218. gl.bindTexture(gl.TEXTURE_2D, texture);
  5219. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5220. texture._baseWidth = width;
  5221. texture._baseHeight = height;
  5222. texture._width = potWidth;
  5223. texture._height = potHeight;
  5224. texture.isReady = true;
  5225. processFunction(potWidth, potHeight);
  5226. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5227. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5228. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5229. if (!noMipmap && !isCompressed) {
  5230. gl.generateMipmap(gl.TEXTURE_2D);
  5231. }
  5232. gl.bindTexture(gl.TEXTURE_2D, null);
  5233. engine._activeTexturesCache = [];
  5234. scene._removePendingData(texture);
  5235. };
  5236. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5237. var onload = function () {
  5238. loadedImages[index] = img;
  5239. loadedImages._internalCount++;
  5240. scene._removePendingData(img);
  5241. if (loadedImages._internalCount === 6) {
  5242. onfinish(loadedImages);
  5243. }
  5244. };
  5245. var onerror = function () {
  5246. scene._removePendingData(img);
  5247. };
  5248. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5249. scene._addPendingData(img);
  5250. };
  5251. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5252. var loadedImages = [];
  5253. loadedImages._internalCount = 0;
  5254. for (var index = 0; index < 6; index++) {
  5255. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5256. }
  5257. };
  5258. var EngineCapabilities = (function () {
  5259. function EngineCapabilities() {
  5260. }
  5261. return EngineCapabilities;
  5262. })();
  5263. BABYLON.EngineCapabilities = EngineCapabilities;
  5264. /**
  5265. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5266. */
  5267. var Engine = (function () {
  5268. /**
  5269. * @constructor
  5270. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5271. * @param {boolean} [antialias] - enable antialias
  5272. * @param options - further options to be sent to the getContext function
  5273. */
  5274. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5275. var _this = this;
  5276. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5277. // Public members
  5278. this.isFullscreen = false;
  5279. this.isPointerLock = false;
  5280. this.cullBackFaces = true;
  5281. this.renderEvenInBackground = true;
  5282. // To enable/disable IDB support and avoid XHR on .manifest
  5283. this.enableOfflineSupport = true;
  5284. this.scenes = new Array();
  5285. this._windowIsBackground = false;
  5286. this._drawCalls = 0;
  5287. this._renderingQueueLaunched = false;
  5288. this._activeRenderLoops = [];
  5289. // FPS
  5290. this.fpsRange = 60;
  5291. this.previousFramesDuration = [];
  5292. this.fps = 60;
  5293. this.deltaTime = 0;
  5294. // States
  5295. this._depthCullingState = new _DepthCullingState();
  5296. this._alphaState = new _AlphaState();
  5297. this._alphaMode = Engine.ALPHA_DISABLE;
  5298. // Cache
  5299. this._loadedTexturesCache = new Array();
  5300. this._activeTexturesCache = new Array();
  5301. this._compiledEffects = {};
  5302. this._uintIndicesCurrentlySet = false;
  5303. this._renderingCanvas = canvas;
  5304. options = options || {};
  5305. options.antialias = antialias;
  5306. if (options.preserveDrawingBuffer === undefined) {
  5307. options.preserveDrawingBuffer = false;
  5308. }
  5309. // GL
  5310. try {
  5311. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5312. }
  5313. catch (e) {
  5314. throw new Error("WebGL not supported");
  5315. }
  5316. if (!this._gl) {
  5317. throw new Error("WebGL not supported");
  5318. }
  5319. this._onBlur = function () {
  5320. _this._windowIsBackground = true;
  5321. };
  5322. this._onFocus = function () {
  5323. _this._windowIsBackground = false;
  5324. };
  5325. window.addEventListener("blur", this._onBlur);
  5326. window.addEventListener("focus", this._onFocus);
  5327. // Viewport
  5328. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5329. this.resize();
  5330. // Caps
  5331. this._caps = new EngineCapabilities();
  5332. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5333. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5334. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5335. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5336. // Infos
  5337. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5338. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5339. if (rendererInfo != null) {
  5340. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5341. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5342. }
  5343. if (!this._glVendor) {
  5344. this._glVendor = "Unknown vendor";
  5345. }
  5346. if (!this._glRenderer) {
  5347. this._glRenderer = "Unknown renderer";
  5348. }
  5349. // Extensions
  5350. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5351. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5352. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5353. 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');
  5354. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5355. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5356. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5357. this._caps.highPrecisionShaderSupported = true;
  5358. if (this._gl.getShaderPrecisionFormat) {
  5359. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5360. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5361. }
  5362. // Depth buffer
  5363. this.setDepthBuffer(true);
  5364. this.setDepthFunctionToLessOrEqual();
  5365. this.setDepthWrite(true);
  5366. // Fullscreen
  5367. this._onFullscreenChange = function () {
  5368. if (document.fullscreen !== undefined) {
  5369. _this.isFullscreen = document.fullscreen;
  5370. }
  5371. else if (document.mozFullScreen !== undefined) {
  5372. _this.isFullscreen = document.mozFullScreen;
  5373. }
  5374. else if (document.webkitIsFullScreen !== undefined) {
  5375. _this.isFullscreen = document.webkitIsFullScreen;
  5376. }
  5377. else if (document.msIsFullScreen !== undefined) {
  5378. _this.isFullscreen = document.msIsFullScreen;
  5379. }
  5380. // Pointer lock
  5381. if (_this.isFullscreen && _this._pointerLockRequested) {
  5382. canvas.requestPointerLock = canvas.requestPointerLock ||
  5383. canvas.msRequestPointerLock ||
  5384. canvas.mozRequestPointerLock ||
  5385. canvas.webkitRequestPointerLock;
  5386. if (canvas.requestPointerLock) {
  5387. canvas.requestPointerLock();
  5388. }
  5389. }
  5390. };
  5391. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5392. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5393. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5394. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5395. // Pointer lock
  5396. this._onPointerLockChange = function () {
  5397. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5398. document.webkitPointerLockElement === canvas ||
  5399. document.msPointerLockElement === canvas ||
  5400. document.pointerLockElement === canvas);
  5401. };
  5402. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5403. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5404. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5405. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5406. if (!Engine.audioEngine) {
  5407. Engine.audioEngine = new BABYLON.AudioEngine();
  5408. }
  5409. //default loading screen
  5410. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5411. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5412. }
  5413. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5414. get: function () {
  5415. return Engine._ALPHA_DISABLE;
  5416. },
  5417. enumerable: true,
  5418. configurable: true
  5419. });
  5420. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5421. get: function () {
  5422. return Engine._ALPHA_ONEONE;
  5423. },
  5424. enumerable: true,
  5425. configurable: true
  5426. });
  5427. Object.defineProperty(Engine, "ALPHA_ADD", {
  5428. get: function () {
  5429. return Engine._ALPHA_ADD;
  5430. },
  5431. enumerable: true,
  5432. configurable: true
  5433. });
  5434. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5435. get: function () {
  5436. return Engine._ALPHA_COMBINE;
  5437. },
  5438. enumerable: true,
  5439. configurable: true
  5440. });
  5441. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5442. get: function () {
  5443. return Engine._ALPHA_SUBTRACT;
  5444. },
  5445. enumerable: true,
  5446. configurable: true
  5447. });
  5448. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5449. get: function () {
  5450. return Engine._ALPHA_MULTIPLY;
  5451. },
  5452. enumerable: true,
  5453. configurable: true
  5454. });
  5455. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5456. get: function () {
  5457. return Engine._ALPHA_MAXIMIZED;
  5458. },
  5459. enumerable: true,
  5460. configurable: true
  5461. });
  5462. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5463. get: function () {
  5464. return Engine._DELAYLOADSTATE_NONE;
  5465. },
  5466. enumerable: true,
  5467. configurable: true
  5468. });
  5469. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5470. get: function () {
  5471. return Engine._DELAYLOADSTATE_LOADED;
  5472. },
  5473. enumerable: true,
  5474. configurable: true
  5475. });
  5476. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5477. get: function () {
  5478. return Engine._DELAYLOADSTATE_LOADING;
  5479. },
  5480. enumerable: true,
  5481. configurable: true
  5482. });
  5483. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5484. get: function () {
  5485. return Engine._DELAYLOADSTATE_NOTLOADED;
  5486. },
  5487. enumerable: true,
  5488. configurable: true
  5489. });
  5490. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5491. get: function () {
  5492. return Engine._TEXTUREFORMAT_ALPHA;
  5493. },
  5494. enumerable: true,
  5495. configurable: true
  5496. });
  5497. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5498. get: function () {
  5499. return Engine._TEXTUREFORMAT_LUMINANCE;
  5500. },
  5501. enumerable: true,
  5502. configurable: true
  5503. });
  5504. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5505. get: function () {
  5506. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5507. },
  5508. enumerable: true,
  5509. configurable: true
  5510. });
  5511. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5512. get: function () {
  5513. return Engine._TEXTUREFORMAT_RGB;
  5514. },
  5515. enumerable: true,
  5516. configurable: true
  5517. });
  5518. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5519. get: function () {
  5520. return Engine._TEXTUREFORMAT_RGBA;
  5521. },
  5522. enumerable: true,
  5523. configurable: true
  5524. });
  5525. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5526. get: function () {
  5527. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5528. },
  5529. enumerable: true,
  5530. configurable: true
  5531. });
  5532. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5533. get: function () {
  5534. return Engine._TEXTURETYPE_FLOAT;
  5535. },
  5536. enumerable: true,
  5537. configurable: true
  5538. });
  5539. Object.defineProperty(Engine, "Version", {
  5540. get: function () {
  5541. return "2.3.0-alpha";
  5542. },
  5543. enumerable: true,
  5544. configurable: true
  5545. });
  5546. Engine.prototype._prepareWorkingCanvas = function () {
  5547. if (this._workingCanvas) {
  5548. return;
  5549. }
  5550. this._workingCanvas = document.createElement("canvas");
  5551. this._workingContext = this._workingCanvas.getContext("2d");
  5552. };
  5553. Engine.prototype.getGlInfo = function () {
  5554. return {
  5555. vendor: this._glVendor,
  5556. renderer: this._glRenderer,
  5557. version: this._glVersion
  5558. };
  5559. };
  5560. Engine.prototype.getAspectRatio = function (camera) {
  5561. var viewport = camera.viewport;
  5562. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5563. };
  5564. Engine.prototype.getRenderWidth = function () {
  5565. if (this._currentRenderTarget) {
  5566. return this._currentRenderTarget._width;
  5567. }
  5568. return this._renderingCanvas.width;
  5569. };
  5570. Engine.prototype.getRenderHeight = function () {
  5571. if (this._currentRenderTarget) {
  5572. return this._currentRenderTarget._height;
  5573. }
  5574. return this._renderingCanvas.height;
  5575. };
  5576. Engine.prototype.getRenderingCanvas = function () {
  5577. return this._renderingCanvas;
  5578. };
  5579. Engine.prototype.getRenderingCanvasClientRect = function () {
  5580. return this._renderingCanvas.getBoundingClientRect();
  5581. };
  5582. Engine.prototype.setHardwareScalingLevel = function (level) {
  5583. this._hardwareScalingLevel = level;
  5584. this.resize();
  5585. };
  5586. Engine.prototype.getHardwareScalingLevel = function () {
  5587. return this._hardwareScalingLevel;
  5588. };
  5589. Engine.prototype.getLoadedTexturesCache = function () {
  5590. return this._loadedTexturesCache;
  5591. };
  5592. Engine.prototype.getCaps = function () {
  5593. return this._caps;
  5594. };
  5595. Object.defineProperty(Engine.prototype, "drawCalls", {
  5596. get: function () {
  5597. return this._drawCalls;
  5598. },
  5599. enumerable: true,
  5600. configurable: true
  5601. });
  5602. // Methods
  5603. Engine.prototype.resetDrawCalls = function () {
  5604. this._drawCalls = 0;
  5605. };
  5606. Engine.prototype.setDepthFunctionToGreater = function () {
  5607. this._depthCullingState.depthFunc = this._gl.GREATER;
  5608. };
  5609. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5610. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5611. };
  5612. Engine.prototype.setDepthFunctionToLess = function () {
  5613. this._depthCullingState.depthFunc = this._gl.LESS;
  5614. };
  5615. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5616. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5617. };
  5618. /**
  5619. * stop executing a render loop function and remove it from the execution array
  5620. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5621. */
  5622. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5623. if (!renderFunction) {
  5624. this._activeRenderLoops = [];
  5625. return;
  5626. }
  5627. var index = this._activeRenderLoops.indexOf(renderFunction);
  5628. if (index >= 0) {
  5629. this._activeRenderLoops.splice(index, 1);
  5630. }
  5631. };
  5632. Engine.prototype._renderLoop = function () {
  5633. var _this = this;
  5634. var shouldRender = true;
  5635. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5636. shouldRender = false;
  5637. }
  5638. if (shouldRender) {
  5639. // Start new frame
  5640. this.beginFrame();
  5641. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5642. var renderFunction = this._activeRenderLoops[index];
  5643. renderFunction();
  5644. }
  5645. // Present
  5646. this.endFrame();
  5647. }
  5648. if (this._activeRenderLoops.length > 0) {
  5649. // Register new frame
  5650. BABYLON.Tools.QueueNewFrame(function () {
  5651. _this._renderLoop();
  5652. });
  5653. }
  5654. else {
  5655. this._renderingQueueLaunched = false;
  5656. }
  5657. };
  5658. /**
  5659. * Register and execute a render loop. The engine can have more than one render function.
  5660. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5661. * @example
  5662. * engine.runRenderLoop(function () {
  5663. * scene.render()
  5664. * })
  5665. */
  5666. Engine.prototype.runRenderLoop = function (renderFunction) {
  5667. var _this = this;
  5668. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5669. return;
  5670. }
  5671. this._activeRenderLoops.push(renderFunction);
  5672. if (!this._renderingQueueLaunched) {
  5673. this._renderingQueueLaunched = true;
  5674. BABYLON.Tools.QueueNewFrame(function () {
  5675. _this._renderLoop();
  5676. });
  5677. }
  5678. };
  5679. /**
  5680. * Toggle full screen mode.
  5681. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5682. */
  5683. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5684. if (this.isFullscreen) {
  5685. BABYLON.Tools.ExitFullscreen();
  5686. }
  5687. else {
  5688. this._pointerLockRequested = requestPointerLock;
  5689. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5690. }
  5691. };
  5692. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5693. this.applyStates();
  5694. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5695. if (this._depthCullingState.depthMask) {
  5696. this._gl.clearDepth(1.0);
  5697. }
  5698. var mode = 0;
  5699. if (backBuffer)
  5700. mode |= this._gl.COLOR_BUFFER_BIT;
  5701. if (depthStencil && this._depthCullingState.depthMask)
  5702. mode |= this._gl.DEPTH_BUFFER_BIT;
  5703. this._gl.clear(mode);
  5704. };
  5705. /**
  5706. * Set the WebGL's viewport
  5707. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5708. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5709. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5710. */
  5711. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5712. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5713. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5714. var x = viewport.x || 0;
  5715. var y = viewport.y || 0;
  5716. this._cachedViewport = viewport;
  5717. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5718. };
  5719. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5720. this._cachedViewport = null;
  5721. this._gl.viewport(x, y, width, height);
  5722. };
  5723. Engine.prototype.beginFrame = function () {
  5724. this._measureFps();
  5725. };
  5726. Engine.prototype.endFrame = function () {
  5727. //this.flushFramebuffer();
  5728. };
  5729. /**
  5730. * resize the view according to the canvas' size.
  5731. * @example
  5732. * window.addEventListener("resize", function () {
  5733. * engine.resize();
  5734. * });
  5735. */
  5736. Engine.prototype.resize = function () {
  5737. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5738. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5739. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5740. };
  5741. /**
  5742. * force a specific size of the canvas
  5743. * @param {number} width - the new canvas' width
  5744. * @param {number} height - the new canvas' height
  5745. */
  5746. Engine.prototype.setSize = function (width, height) {
  5747. this._renderingCanvas.width = width;
  5748. this._renderingCanvas.height = height;
  5749. for (var index = 0; index < this.scenes.length; index++) {
  5750. var scene = this.scenes[index];
  5751. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5752. var cam = scene.cameras[camIndex];
  5753. cam._currentRenderId = 0;
  5754. }
  5755. }
  5756. };
  5757. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5758. this._currentRenderTarget = texture;
  5759. var gl = this._gl;
  5760. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5761. if (texture.isCube) {
  5762. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5763. }
  5764. else {
  5765. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5766. }
  5767. this._gl.viewport(0, 0, texture._width, texture._height);
  5768. this.wipeCaches();
  5769. };
  5770. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5771. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5772. this._currentRenderTarget = null;
  5773. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5774. var gl = this._gl;
  5775. gl.bindTexture(gl.TEXTURE_2D, texture);
  5776. gl.generateMipmap(gl.TEXTURE_2D);
  5777. gl.bindTexture(gl.TEXTURE_2D, null);
  5778. }
  5779. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5780. };
  5781. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5782. if (texture.generateMipMaps) {
  5783. var gl = this._gl;
  5784. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5785. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5786. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5787. }
  5788. };
  5789. Engine.prototype.flushFramebuffer = function () {
  5790. this._gl.flush();
  5791. };
  5792. Engine.prototype.restoreDefaultFramebuffer = function () {
  5793. this._currentRenderTarget = null;
  5794. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5795. this.setViewport(this._cachedViewport);
  5796. this.wipeCaches();
  5797. };
  5798. // VBOs
  5799. Engine.prototype._resetVertexBufferBinding = function () {
  5800. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5801. this._cachedVertexBuffers = null;
  5802. };
  5803. Engine.prototype.createVertexBuffer = function (vertices) {
  5804. var vbo = this._gl.createBuffer();
  5805. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5806. if (vertices instanceof Float32Array) {
  5807. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5808. }
  5809. else {
  5810. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5811. }
  5812. this._resetVertexBufferBinding();
  5813. vbo.references = 1;
  5814. return vbo;
  5815. };
  5816. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5817. var vbo = this._gl.createBuffer();
  5818. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5819. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5820. this._resetVertexBufferBinding();
  5821. vbo.references = 1;
  5822. return vbo;
  5823. };
  5824. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5825. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5826. if (offset === undefined) {
  5827. offset = 0;
  5828. }
  5829. if (vertices instanceof Float32Array) {
  5830. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5831. }
  5832. else {
  5833. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5834. }
  5835. this._resetVertexBufferBinding();
  5836. };
  5837. Engine.prototype._resetIndexBufferBinding = function () {
  5838. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5839. this._cachedIndexBuffer = null;
  5840. };
  5841. Engine.prototype.createIndexBuffer = function (indices) {
  5842. var vbo = this._gl.createBuffer();
  5843. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5844. // Check for 32 bits indices
  5845. var arrayBuffer;
  5846. var need32Bits = false;
  5847. if (this._caps.uintIndices) {
  5848. for (var index = 0; index < indices.length; index++) {
  5849. if (indices[index] > 65535) {
  5850. need32Bits = true;
  5851. break;
  5852. }
  5853. }
  5854. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5855. }
  5856. else {
  5857. arrayBuffer = new Uint16Array(indices);
  5858. }
  5859. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5860. this._resetIndexBufferBinding();
  5861. vbo.references = 1;
  5862. vbo.is32Bits = need32Bits;
  5863. return vbo;
  5864. };
  5865. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5866. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5867. this._cachedVertexBuffers = vertexBuffer;
  5868. this._cachedEffectForVertexBuffers = effect;
  5869. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5870. var offset = 0;
  5871. for (var index = 0; index < vertexDeclaration.length; index++) {
  5872. var order = effect.getAttributeLocation(index);
  5873. if (order >= 0) {
  5874. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5875. }
  5876. offset += vertexDeclaration[index] * 4;
  5877. }
  5878. }
  5879. if (this._cachedIndexBuffer !== indexBuffer) {
  5880. this._cachedIndexBuffer = indexBuffer;
  5881. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5882. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5883. }
  5884. };
  5885. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5886. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5887. this._cachedVertexBuffers = vertexBuffers;
  5888. this._cachedEffectForVertexBuffers = effect;
  5889. var attributes = effect.getAttributesNames();
  5890. for (var index = 0; index < attributes.length; index++) {
  5891. var order = effect.getAttributeLocation(index);
  5892. if (order >= 0) {
  5893. var vertexBuffer = vertexBuffers[attributes[index]];
  5894. if (!vertexBuffer) {
  5895. continue;
  5896. }
  5897. var stride = vertexBuffer.getStrideSize();
  5898. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5899. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5900. }
  5901. }
  5902. }
  5903. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5904. this._cachedIndexBuffer = indexBuffer;
  5905. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5906. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5907. }
  5908. };
  5909. Engine.prototype._releaseBuffer = function (buffer) {
  5910. buffer.references--;
  5911. if (buffer.references === 0) {
  5912. this._gl.deleteBuffer(buffer);
  5913. return true;
  5914. }
  5915. return false;
  5916. };
  5917. Engine.prototype.createInstancesBuffer = function (capacity) {
  5918. var buffer = this._gl.createBuffer();
  5919. buffer.capacity = capacity;
  5920. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5921. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5922. return buffer;
  5923. };
  5924. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5925. this._gl.deleteBuffer(buffer);
  5926. };
  5927. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5928. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5929. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5930. for (var index = 0; index < 4; index++) {
  5931. var offsetLocation = offsetLocations[index];
  5932. this._gl.enableVertexAttribArray(offsetLocation);
  5933. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5934. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5935. }
  5936. };
  5937. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5938. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5939. for (var index = 0; index < 4; index++) {
  5940. var offsetLocation = offsetLocations[index];
  5941. this._gl.disableVertexAttribArray(offsetLocation);
  5942. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5943. }
  5944. };
  5945. Engine.prototype.applyStates = function () {
  5946. this._depthCullingState.apply(this._gl);
  5947. this._alphaState.apply(this._gl);
  5948. };
  5949. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5950. // Apply states
  5951. this.applyStates();
  5952. this._drawCalls++;
  5953. // Render
  5954. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5955. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5956. if (instancesCount) {
  5957. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5958. return;
  5959. }
  5960. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5961. };
  5962. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5963. // Apply states
  5964. this.applyStates();
  5965. this._drawCalls++;
  5966. if (instancesCount) {
  5967. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5968. return;
  5969. }
  5970. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5971. };
  5972. // Shaders
  5973. Engine.prototype._releaseEffect = function (effect) {
  5974. if (this._compiledEffects[effect._key]) {
  5975. delete this._compiledEffects[effect._key];
  5976. if (effect.getProgram()) {
  5977. this._gl.deleteProgram(effect.getProgram());
  5978. }
  5979. }
  5980. };
  5981. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5982. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5983. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5984. var name = vertex + "+" + fragment + "@" + defines;
  5985. if (this._compiledEffects[name]) {
  5986. return this._compiledEffects[name];
  5987. }
  5988. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5989. effect._key = name;
  5990. this._compiledEffects[name] = effect;
  5991. return effect;
  5992. };
  5993. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5994. if (uniformsNames === void 0) { uniformsNames = []; }
  5995. if (samplers === void 0) { samplers = []; }
  5996. if (defines === void 0) { defines = ""; }
  5997. return this.createEffect({
  5998. vertex: "particles",
  5999. fragmentElement: fragmentName
  6000. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6001. };
  6002. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6003. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6004. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6005. var shaderProgram = this._gl.createProgram();
  6006. this._gl.attachShader(shaderProgram, vertexShader);
  6007. this._gl.attachShader(shaderProgram, fragmentShader);
  6008. this._gl.linkProgram(shaderProgram);
  6009. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6010. if (!linked) {
  6011. var error = this._gl.getProgramInfoLog(shaderProgram);
  6012. if (error) {
  6013. throw new Error(error);
  6014. }
  6015. }
  6016. this._gl.deleteShader(vertexShader);
  6017. this._gl.deleteShader(fragmentShader);
  6018. return shaderProgram;
  6019. };
  6020. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6021. var results = [];
  6022. for (var index = 0; index < uniformsNames.length; index++) {
  6023. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6024. }
  6025. return results;
  6026. };
  6027. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6028. var results = [];
  6029. for (var index = 0; index < attributesNames.length; index++) {
  6030. try {
  6031. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6032. }
  6033. catch (e) {
  6034. results.push(-1);
  6035. }
  6036. }
  6037. return results;
  6038. };
  6039. Engine.prototype.enableEffect = function (effect) {
  6040. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6041. if (effect && effect.onBind) {
  6042. effect.onBind(effect);
  6043. }
  6044. return;
  6045. }
  6046. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6047. // Use program
  6048. this._gl.useProgram(effect.getProgram());
  6049. for (var i in this._vertexAttribArrays) {
  6050. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6051. continue;
  6052. }
  6053. this._vertexAttribArrays[i] = false;
  6054. this._gl.disableVertexAttribArray(i);
  6055. }
  6056. var attributesCount = effect.getAttributesCount();
  6057. for (var index = 0; index < attributesCount; index++) {
  6058. // Attributes
  6059. var order = effect.getAttributeLocation(index);
  6060. if (order >= 0) {
  6061. this._vertexAttribArrays[order] = true;
  6062. this._gl.enableVertexAttribArray(order);
  6063. }
  6064. }
  6065. this._currentEffect = effect;
  6066. if (effect.onBind) {
  6067. effect.onBind(effect);
  6068. }
  6069. };
  6070. Engine.prototype.setArray = function (uniform, array) {
  6071. if (!uniform)
  6072. return;
  6073. this._gl.uniform1fv(uniform, array);
  6074. };
  6075. Engine.prototype.setArray2 = function (uniform, array) {
  6076. if (!uniform || array.length % 2 !== 0)
  6077. return;
  6078. this._gl.uniform2fv(uniform, array);
  6079. };
  6080. Engine.prototype.setArray3 = function (uniform, array) {
  6081. if (!uniform || array.length % 3 !== 0)
  6082. return;
  6083. this._gl.uniform3fv(uniform, array);
  6084. };
  6085. Engine.prototype.setArray4 = function (uniform, array) {
  6086. if (!uniform || array.length % 4 !== 0)
  6087. return;
  6088. this._gl.uniform4fv(uniform, array);
  6089. };
  6090. Engine.prototype.setMatrices = function (uniform, matrices) {
  6091. if (!uniform)
  6092. return;
  6093. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6094. };
  6095. Engine.prototype.setMatrix = function (uniform, matrix) {
  6096. if (!uniform)
  6097. return;
  6098. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6099. };
  6100. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6101. if (!uniform)
  6102. return;
  6103. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6104. };
  6105. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6106. if (!uniform)
  6107. return;
  6108. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6109. };
  6110. Engine.prototype.setFloat = function (uniform, value) {
  6111. if (!uniform)
  6112. return;
  6113. this._gl.uniform1f(uniform, value);
  6114. };
  6115. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6116. if (!uniform)
  6117. return;
  6118. this._gl.uniform2f(uniform, x, y);
  6119. };
  6120. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6121. if (!uniform)
  6122. return;
  6123. this._gl.uniform3f(uniform, x, y, z);
  6124. };
  6125. Engine.prototype.setBool = function (uniform, bool) {
  6126. if (!uniform)
  6127. return;
  6128. this._gl.uniform1i(uniform, bool);
  6129. };
  6130. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6131. if (!uniform)
  6132. return;
  6133. this._gl.uniform4f(uniform, x, y, z, w);
  6134. };
  6135. Engine.prototype.setColor3 = function (uniform, color3) {
  6136. if (!uniform)
  6137. return;
  6138. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6139. };
  6140. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6141. if (!uniform)
  6142. return;
  6143. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6144. };
  6145. // States
  6146. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6147. if (zOffset === void 0) { zOffset = 0; }
  6148. if (reverseSide === void 0) { reverseSide = false; }
  6149. // Culling
  6150. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6151. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6152. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6153. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6154. if (culling) {
  6155. this._depthCullingState.cullFace = cullFace;
  6156. this._depthCullingState.cull = true;
  6157. }
  6158. else {
  6159. this._depthCullingState.cull = false;
  6160. }
  6161. }
  6162. // Z offset
  6163. this._depthCullingState.zOffset = zOffset;
  6164. };
  6165. Engine.prototype.setDepthBuffer = function (enable) {
  6166. this._depthCullingState.depthTest = enable;
  6167. };
  6168. Engine.prototype.getDepthWrite = function () {
  6169. return this._depthCullingState.depthMask;
  6170. };
  6171. Engine.prototype.setDepthWrite = function (enable) {
  6172. this._depthCullingState.depthMask = enable;
  6173. };
  6174. Engine.prototype.setColorWrite = function (enable) {
  6175. this._gl.colorMask(enable, enable, enable, enable);
  6176. };
  6177. Engine.prototype.setAlphaMode = function (mode) {
  6178. if (this._alphaMode === mode) {
  6179. return;
  6180. }
  6181. switch (mode) {
  6182. case Engine.ALPHA_DISABLE:
  6183. this.setDepthWrite(true);
  6184. this._alphaState.alphaBlend = false;
  6185. break;
  6186. case Engine.ALPHA_COMBINE:
  6187. this.setDepthWrite(false);
  6188. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6189. this._alphaState.alphaBlend = true;
  6190. break;
  6191. case Engine.ALPHA_ONEONE:
  6192. this.setDepthWrite(false);
  6193. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6194. this._alphaState.alphaBlend = true;
  6195. break;
  6196. case Engine.ALPHA_ADD:
  6197. this.setDepthWrite(false);
  6198. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6199. this._alphaState.alphaBlend = true;
  6200. break;
  6201. case Engine.ALPHA_SUBTRACT:
  6202. this.setDepthWrite(false);
  6203. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6204. this._alphaState.alphaBlend = true;
  6205. break;
  6206. case Engine.ALPHA_MULTIPLY:
  6207. this.setDepthWrite(false);
  6208. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6209. this._alphaState.alphaBlend = true;
  6210. break;
  6211. case Engine.ALPHA_MAXIMIZED:
  6212. this.setDepthWrite(false);
  6213. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6214. this._alphaState.alphaBlend = true;
  6215. break;
  6216. }
  6217. this._alphaMode = mode;
  6218. };
  6219. Engine.prototype.getAlphaMode = function () {
  6220. return this._alphaMode;
  6221. };
  6222. Engine.prototype.setAlphaTesting = function (enable) {
  6223. this._alphaTest = enable;
  6224. };
  6225. Engine.prototype.getAlphaTesting = function () {
  6226. return this._alphaTest;
  6227. };
  6228. // Textures
  6229. Engine.prototype.wipeCaches = function () {
  6230. this._activeTexturesCache = [];
  6231. this._currentEffect = null;
  6232. this._depthCullingState.reset();
  6233. this._alphaState.reset();
  6234. this._cachedVertexBuffers = null;
  6235. this._cachedIndexBuffer = null;
  6236. this._cachedEffectForVertexBuffers = null;
  6237. };
  6238. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6239. var gl = this._gl;
  6240. gl.bindTexture(gl.TEXTURE_2D, texture);
  6241. var magFilter = gl.NEAREST;
  6242. var minFilter = gl.NEAREST;
  6243. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6244. magFilter = gl.LINEAR;
  6245. minFilter = gl.LINEAR;
  6246. }
  6247. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6248. magFilter = gl.LINEAR;
  6249. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6250. }
  6251. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6253. gl.bindTexture(gl.TEXTURE_2D, null);
  6254. texture.samplingMode = samplingMode;
  6255. };
  6256. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6257. var _this = this;
  6258. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6259. if (onLoad === void 0) { onLoad = null; }
  6260. if (onError === void 0) { onError = null; }
  6261. if (buffer === void 0) { buffer = null; }
  6262. var texture = this._gl.createTexture();
  6263. var extension;
  6264. var fromData = false;
  6265. if (url.substr(0, 5) === "data:") {
  6266. fromData = true;
  6267. }
  6268. if (!fromData)
  6269. extension = url.substr(url.length - 4, 4).toLowerCase();
  6270. else {
  6271. var oldUrl = url;
  6272. fromData = oldUrl.split(':');
  6273. url = oldUrl;
  6274. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6275. }
  6276. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6277. var isTGA = (extension === ".tga");
  6278. scene._addPendingData(texture);
  6279. texture.url = url;
  6280. texture.noMipmap = noMipmap;
  6281. texture.references = 1;
  6282. texture.samplingMode = samplingMode;
  6283. this._loadedTexturesCache.push(texture);
  6284. var onerror = function () {
  6285. scene._removePendingData(texture);
  6286. if (onError) {
  6287. onError();
  6288. }
  6289. };
  6290. var callback;
  6291. if (isTGA) {
  6292. callback = function (arrayBuffer) {
  6293. var data = new Uint8Array(arrayBuffer);
  6294. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6295. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6296. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6297. if (onLoad) {
  6298. onLoad();
  6299. }
  6300. }, samplingMode);
  6301. };
  6302. if (!(fromData instanceof Array))
  6303. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6304. callback(arrayBuffer);
  6305. }, onerror, scene.database, true);
  6306. else
  6307. callback(buffer);
  6308. }
  6309. else if (isDDS) {
  6310. callback = function (data) {
  6311. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6312. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6313. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6314. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6315. if (onLoad) {
  6316. onLoad();
  6317. }
  6318. }, samplingMode);
  6319. };
  6320. if (!(fromData instanceof Array))
  6321. BABYLON.Tools.LoadFile(url, function (data) {
  6322. callback(data);
  6323. }, onerror, scene.database, true);
  6324. else
  6325. callback(buffer);
  6326. }
  6327. else {
  6328. var onload = function (img) {
  6329. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6330. var isPot = (img.width === potWidth && img.height === potHeight);
  6331. if (!isPot) {
  6332. _this._prepareWorkingCanvas();
  6333. _this._workingCanvas.width = potWidth;
  6334. _this._workingCanvas.height = potHeight;
  6335. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6336. _this._workingContext.imageSmoothingEnabled = false;
  6337. _this._workingContext.mozImageSmoothingEnabled = false;
  6338. _this._workingContext.oImageSmoothingEnabled = false;
  6339. _this._workingContext.webkitImageSmoothingEnabled = false;
  6340. _this._workingContext.msImageSmoothingEnabled = false;
  6341. }
  6342. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6343. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6344. _this._workingContext.imageSmoothingEnabled = true;
  6345. _this._workingContext.mozImageSmoothingEnabled = true;
  6346. _this._workingContext.oImageSmoothingEnabled = true;
  6347. _this._workingContext.webkitImageSmoothingEnabled = true;
  6348. _this._workingContext.msImageSmoothingEnabled = true;
  6349. }
  6350. }
  6351. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6352. if (onLoad) {
  6353. onLoad();
  6354. }
  6355. }, samplingMode);
  6356. };
  6357. if (!(fromData instanceof Array))
  6358. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6359. else
  6360. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6361. }
  6362. return texture;
  6363. };
  6364. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6365. if (compression === void 0) { compression = null; }
  6366. var internalFormat = this._gl.RGBA;
  6367. switch (format) {
  6368. case Engine.TEXTUREFORMAT_ALPHA:
  6369. internalFormat = this._gl.ALPHA;
  6370. break;
  6371. case Engine.TEXTUREFORMAT_LUMINANCE:
  6372. internalFormat = this._gl.LUMINANCE;
  6373. break;
  6374. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6375. internalFormat = this._gl.LUMINANCE_ALPHA;
  6376. break;
  6377. case Engine.TEXTUREFORMAT_RGB:
  6378. internalFormat = this._gl.RGB;
  6379. break;
  6380. case Engine.TEXTUREFORMAT_RGBA:
  6381. internalFormat = this._gl.RGBA;
  6382. break;
  6383. }
  6384. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6385. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6386. if (compression) {
  6387. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6388. }
  6389. else {
  6390. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6391. }
  6392. if (texture.generateMipMaps) {
  6393. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6394. }
  6395. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6396. this._activeTexturesCache = [];
  6397. texture.isReady = true;
  6398. };
  6399. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6400. if (compression === void 0) { compression = null; }
  6401. var texture = this._gl.createTexture();
  6402. texture._baseWidth = width;
  6403. texture._baseHeight = height;
  6404. texture._width = width;
  6405. texture._height = height;
  6406. texture.references = 1;
  6407. this.updateRawTexture(texture, data, format, invertY, compression);
  6408. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6409. // Filters
  6410. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6411. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6412. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6413. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6414. texture.samplingMode = samplingMode;
  6415. this._loadedTexturesCache.push(texture);
  6416. return texture;
  6417. };
  6418. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6419. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6420. var texture = this._gl.createTexture();
  6421. texture._baseWidth = width;
  6422. texture._baseHeight = height;
  6423. if (forceExponantOfTwo) {
  6424. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6425. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6426. }
  6427. this._activeTexturesCache = [];
  6428. texture._width = width;
  6429. texture._height = height;
  6430. texture.isReady = false;
  6431. texture.generateMipMaps = generateMipMaps;
  6432. texture.references = 1;
  6433. texture.samplingMode = samplingMode;
  6434. this.updateTextureSamplingMode(samplingMode, texture);
  6435. this._loadedTexturesCache.push(texture);
  6436. return texture;
  6437. };
  6438. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6439. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6440. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6441. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6442. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6443. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6444. };
  6445. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6446. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6447. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6448. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6449. if (texture.generateMipMaps) {
  6450. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6451. }
  6452. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6453. this._activeTexturesCache = [];
  6454. texture.isReady = true;
  6455. };
  6456. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6457. if (texture._isDisabled) {
  6458. return;
  6459. }
  6460. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6461. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6462. try {
  6463. // Testing video texture support
  6464. if (this._videoTextureSupported === undefined) {
  6465. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6466. if (this._gl.getError() !== 0) {
  6467. this._videoTextureSupported = false;
  6468. }
  6469. else {
  6470. this._videoTextureSupported = true;
  6471. }
  6472. }
  6473. // Copy video through the current working canvas if video texture is not supported
  6474. if (!this._videoTextureSupported) {
  6475. if (!texture._workingCanvas) {
  6476. texture._workingCanvas = document.createElement("canvas");
  6477. texture._workingContext = texture._workingCanvas.getContext("2d");
  6478. texture._workingCanvas.width = texture._width;
  6479. texture._workingCanvas.height = texture._height;
  6480. }
  6481. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6482. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6483. }
  6484. else {
  6485. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6486. }
  6487. if (texture.generateMipMaps) {
  6488. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6489. }
  6490. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6491. this._activeTexturesCache = [];
  6492. texture.isReady = true;
  6493. }
  6494. catch (ex) {
  6495. // Something unexpected
  6496. // Let's disable the texture
  6497. texture._isDisabled = true;
  6498. }
  6499. };
  6500. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6501. // old version had a "generateMipMaps" arg instead of options.
  6502. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6503. // in the same way, generateDepthBuffer is defaulted to true
  6504. var generateMipMaps = false;
  6505. var generateDepthBuffer = true;
  6506. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6507. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6508. if (options !== undefined) {
  6509. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6510. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6511. type = options.type === undefined ? type : options.type;
  6512. if (options.samplingMode !== undefined) {
  6513. samplingMode = options.samplingMode;
  6514. }
  6515. if (type === Engine.TEXTURETYPE_FLOAT) {
  6516. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6517. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6518. }
  6519. }
  6520. var gl = this._gl;
  6521. var texture = gl.createTexture();
  6522. gl.bindTexture(gl.TEXTURE_2D, texture);
  6523. var width = size.width || size;
  6524. var height = size.height || size;
  6525. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6526. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6527. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6528. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6529. }
  6530. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6531. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6532. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6533. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6534. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6535. var depthBuffer;
  6536. // Create the depth buffer
  6537. if (generateDepthBuffer) {
  6538. depthBuffer = gl.createRenderbuffer();
  6539. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6540. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6541. }
  6542. // Create the framebuffer
  6543. var framebuffer = gl.createFramebuffer();
  6544. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6545. if (generateDepthBuffer) {
  6546. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6547. }
  6548. if (generateMipMaps) {
  6549. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6550. }
  6551. // Unbind
  6552. gl.bindTexture(gl.TEXTURE_2D, null);
  6553. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6554. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6555. texture._framebuffer = framebuffer;
  6556. if (generateDepthBuffer) {
  6557. texture._depthBuffer = depthBuffer;
  6558. }
  6559. texture._width = width;
  6560. texture._height = height;
  6561. texture.isReady = true;
  6562. texture.generateMipMaps = generateMipMaps;
  6563. texture.references = 1;
  6564. texture.samplingMode = samplingMode;
  6565. this._activeTexturesCache = [];
  6566. this._loadedTexturesCache.push(texture);
  6567. return texture;
  6568. };
  6569. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6570. var gl = this._gl;
  6571. var texture = gl.createTexture();
  6572. var generateMipMaps = true;
  6573. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6574. if (options !== undefined) {
  6575. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6576. if (options.samplingMode !== undefined) {
  6577. samplingMode = options.samplingMode;
  6578. }
  6579. }
  6580. texture.isCube = true;
  6581. texture.references = 1;
  6582. texture.generateMipMaps = generateMipMaps;
  6583. texture.references = 1;
  6584. texture.samplingMode = samplingMode;
  6585. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6586. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6587. for (var face = 0; face < 6; face++) {
  6588. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6589. }
  6590. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6592. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6593. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6594. // Create the depth buffer
  6595. var depthBuffer = gl.createRenderbuffer();
  6596. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6597. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6598. // Create the framebuffer
  6599. var framebuffer = gl.createFramebuffer();
  6600. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6601. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6602. // Unbind
  6603. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6604. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6605. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6606. texture._framebuffer = framebuffer;
  6607. texture._depthBuffer = depthBuffer;
  6608. this._activeTexturesCache = [];
  6609. texture._width = size;
  6610. texture._height = size;
  6611. texture.isReady = true;
  6612. return texture;
  6613. };
  6614. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6615. var _this = this;
  6616. var gl = this._gl;
  6617. var texture = gl.createTexture();
  6618. texture.isCube = true;
  6619. texture.url = rootUrl;
  6620. texture.references = 1;
  6621. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6622. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6623. if (isDDS) {
  6624. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6625. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6626. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6627. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6628. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6629. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6630. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6631. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6632. }
  6633. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6634. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6635. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6636. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6637. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6638. _this._activeTexturesCache = [];
  6639. texture._width = info.width;
  6640. texture._height = info.height;
  6641. texture.isReady = true;
  6642. }, null, null, true);
  6643. }
  6644. else {
  6645. cascadeLoad(rootUrl, scene, function (imgs) {
  6646. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6647. var height = width;
  6648. _this._prepareWorkingCanvas();
  6649. _this._workingCanvas.width = width;
  6650. _this._workingCanvas.height = height;
  6651. var faces = [
  6652. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6653. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6654. ];
  6655. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6656. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6657. for (var index = 0; index < faces.length; index++) {
  6658. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6659. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6660. }
  6661. if (!noMipmap) {
  6662. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6663. }
  6664. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6668. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6669. _this._activeTexturesCache = [];
  6670. texture._width = width;
  6671. texture._height = height;
  6672. texture.isReady = true;
  6673. }, extensions);
  6674. }
  6675. return texture;
  6676. };
  6677. Engine.prototype._releaseTexture = function (texture) {
  6678. var gl = this._gl;
  6679. if (texture._framebuffer) {
  6680. gl.deleteFramebuffer(texture._framebuffer);
  6681. }
  6682. if (texture._depthBuffer) {
  6683. gl.deleteRenderbuffer(texture._depthBuffer);
  6684. }
  6685. gl.deleteTexture(texture);
  6686. // Unbind channels
  6687. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6688. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6689. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6690. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6691. this._activeTexturesCache[channel] = null;
  6692. }
  6693. var index = this._loadedTexturesCache.indexOf(texture);
  6694. if (index !== -1) {
  6695. this._loadedTexturesCache.splice(index, 1);
  6696. }
  6697. };
  6698. Engine.prototype.bindSamplers = function (effect) {
  6699. this._gl.useProgram(effect.getProgram());
  6700. var samplers = effect.getSamplers();
  6701. for (var index = 0; index < samplers.length; index++) {
  6702. var uniform = effect.getUniform(samplers[index]);
  6703. this._gl.uniform1i(uniform, index);
  6704. }
  6705. this._currentEffect = null;
  6706. };
  6707. Engine.prototype._bindTexture = function (channel, texture) {
  6708. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6709. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6710. this._activeTexturesCache[channel] = null;
  6711. };
  6712. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6713. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6714. };
  6715. Engine.prototype.setTexture = function (channel, texture) {
  6716. if (channel < 0) {
  6717. return;
  6718. }
  6719. // Not ready?
  6720. if (!texture || !texture.isReady()) {
  6721. if (this._activeTexturesCache[channel] != null) {
  6722. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6723. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6724. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6725. this._activeTexturesCache[channel] = null;
  6726. }
  6727. return;
  6728. }
  6729. // Video
  6730. if (texture instanceof BABYLON.VideoTexture) {
  6731. if (texture.update()) {
  6732. this._activeTexturesCache[channel] = null;
  6733. }
  6734. }
  6735. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6736. texture.delayLoad();
  6737. return;
  6738. }
  6739. if (this._activeTexturesCache[channel] === texture) {
  6740. return;
  6741. }
  6742. this._activeTexturesCache[channel] = texture;
  6743. var internalTexture = texture.getInternalTexture();
  6744. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6745. if (internalTexture.isCube) {
  6746. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6747. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6748. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6749. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6750. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6751. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6752. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6753. }
  6754. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6755. }
  6756. else {
  6757. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6758. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6759. internalTexture._cachedWrapU = texture.wrapU;
  6760. switch (texture.wrapU) {
  6761. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6762. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6763. break;
  6764. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6765. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6766. break;
  6767. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6768. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6769. break;
  6770. }
  6771. }
  6772. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6773. internalTexture._cachedWrapV = texture.wrapV;
  6774. switch (texture.wrapV) {
  6775. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6776. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6777. break;
  6778. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6779. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6780. break;
  6781. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6782. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6783. break;
  6784. }
  6785. }
  6786. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6787. }
  6788. };
  6789. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6790. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6791. var value = texture.anisotropicFilteringLevel;
  6792. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6793. value = 1;
  6794. }
  6795. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6796. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6797. texture._cachedAnisotropicFilteringLevel = value;
  6798. }
  6799. };
  6800. Engine.prototype.readPixels = function (x, y, width, height) {
  6801. var data = new Uint8Array(height * width * 4);
  6802. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6803. return data;
  6804. };
  6805. Engine.prototype.releaseInternalTexture = function (texture) {
  6806. if (!texture) {
  6807. return;
  6808. }
  6809. texture.references--;
  6810. // Final reference ?
  6811. if (texture.references === 0) {
  6812. var texturesCache = this.getLoadedTexturesCache();
  6813. var index = texturesCache.indexOf(texture);
  6814. if (index > -1) {
  6815. texturesCache.splice(index, 1);
  6816. }
  6817. this._releaseTexture(texture);
  6818. }
  6819. };
  6820. // Dispose
  6821. Engine.prototype.dispose = function () {
  6822. this.hideLoadingUI();
  6823. this.stopRenderLoop();
  6824. // Release scenes
  6825. while (this.scenes.length) {
  6826. this.scenes[0].dispose();
  6827. }
  6828. // Release audio engine
  6829. Engine.audioEngine.dispose();
  6830. // Release effects
  6831. for (var name in this._compiledEffects) {
  6832. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6833. }
  6834. // Unbind
  6835. for (var i in this._vertexAttribArrays) {
  6836. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6837. continue;
  6838. }
  6839. this._gl.disableVertexAttribArray(i);
  6840. }
  6841. this._gl = null;
  6842. // Events
  6843. window.removeEventListener("blur", this._onBlur);
  6844. window.removeEventListener("focus", this._onFocus);
  6845. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6846. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6847. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6848. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6849. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6850. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6851. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6852. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6853. };
  6854. // Loading screen
  6855. Engine.prototype.displayLoadingUI = function () {
  6856. this._loadingScreen.displayLoadingUI();
  6857. };
  6858. Engine.prototype.hideLoadingUI = function () {
  6859. this._loadingScreen.hideLoadingUI();
  6860. };
  6861. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6862. get: function () {
  6863. return this._loadingScreen;
  6864. },
  6865. set: function (loadingScreen) {
  6866. this._loadingScreen = loadingScreen;
  6867. },
  6868. enumerable: true,
  6869. configurable: true
  6870. });
  6871. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6872. set: function (text) {
  6873. this._loadingScreen.loadingUIText = text;
  6874. },
  6875. enumerable: true,
  6876. configurable: true
  6877. });
  6878. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6879. set: function (color) {
  6880. this._loadingScreen.loadingUIBackgroundColor = color;
  6881. },
  6882. enumerable: true,
  6883. configurable: true
  6884. });
  6885. // FPS
  6886. Engine.prototype.getFps = function () {
  6887. return this.fps;
  6888. };
  6889. Engine.prototype.getDeltaTime = function () {
  6890. return this.deltaTime;
  6891. };
  6892. Engine.prototype._measureFps = function () {
  6893. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6894. var length = this.previousFramesDuration.length;
  6895. if (length >= 2) {
  6896. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6897. }
  6898. if (length >= this.fpsRange) {
  6899. if (length > this.fpsRange) {
  6900. this.previousFramesDuration.splice(0, 1);
  6901. length = this.previousFramesDuration.length;
  6902. }
  6903. var sum = 0;
  6904. for (var id = 0; id < length - 1; id++) {
  6905. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6906. }
  6907. this.fps = 1000.0 / (sum / (length - 1));
  6908. }
  6909. };
  6910. // Statics
  6911. Engine.isSupported = function () {
  6912. try {
  6913. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6914. if (navigator.isCocoonJS) {
  6915. return true;
  6916. }
  6917. var tempcanvas = document.createElement("canvas");
  6918. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6919. return gl != null && !!window.WebGLRenderingContext;
  6920. }
  6921. catch (e) {
  6922. return false;
  6923. }
  6924. };
  6925. // Const statics
  6926. Engine._ALPHA_DISABLE = 0;
  6927. Engine._ALPHA_ADD = 1;
  6928. Engine._ALPHA_COMBINE = 2;
  6929. Engine._ALPHA_SUBTRACT = 3;
  6930. Engine._ALPHA_MULTIPLY = 4;
  6931. Engine._ALPHA_MAXIMIZED = 5;
  6932. Engine._ALPHA_ONEONE = 6;
  6933. Engine._DELAYLOADSTATE_NONE = 0;
  6934. Engine._DELAYLOADSTATE_LOADED = 1;
  6935. Engine._DELAYLOADSTATE_LOADING = 2;
  6936. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6937. Engine._TEXTUREFORMAT_ALPHA = 0;
  6938. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6939. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6940. Engine._TEXTUREFORMAT_RGB = 4;
  6941. Engine._TEXTUREFORMAT_RGBA = 5;
  6942. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6943. Engine._TEXTURETYPE_FLOAT = 1;
  6944. // Updatable statics so stick with vars here
  6945. Engine.Epsilon = 0.001;
  6946. Engine.CollisionsEpsilon = 0.001;
  6947. Engine.CodeRepository = "src/";
  6948. Engine.ShadersRepository = "src/Shaders/";
  6949. return Engine;
  6950. })();
  6951. BABYLON.Engine = Engine;
  6952. })(BABYLON || (BABYLON = {}));
  6953. var BABYLON;
  6954. (function (BABYLON) {
  6955. /**
  6956. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6957. */
  6958. var Node = (function () {
  6959. /**
  6960. * @constructor
  6961. * @param {string} name - the name and id to be given to this node
  6962. * @param {BABYLON.Scene} the scene this node will be added to
  6963. */
  6964. function Node(name, scene) {
  6965. this.state = "";
  6966. this.animations = new Array();
  6967. this._childrenFlag = -1;
  6968. this._isEnabled = true;
  6969. this._isReady = true;
  6970. this._currentRenderId = -1;
  6971. this._parentRenderId = -1;
  6972. this.name = name;
  6973. this.id = name;
  6974. this._scene = scene;
  6975. this._initCache();
  6976. }
  6977. Node.prototype.getScene = function () {
  6978. return this._scene;
  6979. };
  6980. Node.prototype.getEngine = function () {
  6981. return this._scene.getEngine();
  6982. };
  6983. // override it in derived class
  6984. Node.prototype.getWorldMatrix = function () {
  6985. return BABYLON.Matrix.Identity();
  6986. };
  6987. // override it in derived class if you add new variables to the cache
  6988. // and call the parent class method
  6989. Node.prototype._initCache = function () {
  6990. this._cache = {};
  6991. this._cache.parent = undefined;
  6992. };
  6993. Node.prototype.updateCache = function (force) {
  6994. if (!force && this.isSynchronized())
  6995. return;
  6996. this._cache.parent = this.parent;
  6997. this._updateCache();
  6998. };
  6999. // override it in derived class if you add new variables to the cache
  7000. // and call the parent class method if !ignoreParentClass
  7001. Node.prototype._updateCache = function (ignoreParentClass) {
  7002. };
  7003. // override it in derived class if you add new variables to the cache
  7004. Node.prototype._isSynchronized = function () {
  7005. return true;
  7006. };
  7007. Node.prototype._markSyncedWithParent = function () {
  7008. this._parentRenderId = this.parent._currentRenderId;
  7009. };
  7010. Node.prototype.isSynchronizedWithParent = function () {
  7011. if (!this.parent) {
  7012. return true;
  7013. }
  7014. if (this._parentRenderId !== this.parent._currentRenderId) {
  7015. return false;
  7016. }
  7017. return this.parent.isSynchronized();
  7018. };
  7019. Node.prototype.isSynchronized = function (updateCache) {
  7020. var check = this.hasNewParent();
  7021. check = check || !this.isSynchronizedWithParent();
  7022. check = check || !this._isSynchronized();
  7023. if (updateCache)
  7024. this.updateCache(true);
  7025. return !check;
  7026. };
  7027. Node.prototype.hasNewParent = function (update) {
  7028. if (this._cache.parent === this.parent)
  7029. return false;
  7030. if (update)
  7031. this._cache.parent = this.parent;
  7032. return true;
  7033. };
  7034. /**
  7035. * Is this node ready to be used/rendered
  7036. * @return {boolean} is it ready
  7037. */
  7038. Node.prototype.isReady = function () {
  7039. return this._isReady;
  7040. };
  7041. /**
  7042. * Is this node enabled.
  7043. * If the node has a parent and is enabled, the parent will be inspected as well.
  7044. * @return {boolean} whether this node (and its parent) is enabled.
  7045. * @see setEnabled
  7046. */
  7047. Node.prototype.isEnabled = function () {
  7048. if (!this._isEnabled) {
  7049. return false;
  7050. }
  7051. if (this.parent) {
  7052. return this.parent.isEnabled();
  7053. }
  7054. return true;
  7055. };
  7056. /**
  7057. * Set the enabled state of this node.
  7058. * @param {boolean} value - the new enabled state
  7059. * @see isEnabled
  7060. */
  7061. Node.prototype.setEnabled = function (value) {
  7062. this._isEnabled = value;
  7063. };
  7064. /**
  7065. * Is this node a descendant of the given node.
  7066. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7067. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7068. * @see parent
  7069. */
  7070. Node.prototype.isDescendantOf = function (ancestor) {
  7071. if (this.parent) {
  7072. if (this.parent === ancestor) {
  7073. return true;
  7074. }
  7075. return this.parent.isDescendantOf(ancestor);
  7076. }
  7077. return false;
  7078. };
  7079. Node.prototype._getDescendants = function (list, results) {
  7080. for (var index = 0; index < list.length; index++) {
  7081. var item = list[index];
  7082. if (item.isDescendantOf(this)) {
  7083. results.push(item);
  7084. }
  7085. }
  7086. };
  7087. /**
  7088. * Will return all nodes that have this node as parent.
  7089. * @return {BABYLON.Node[]} all children nodes of all types.
  7090. */
  7091. Node.prototype.getDescendants = function () {
  7092. var results = [];
  7093. this._getDescendants(this._scene.meshes, results);
  7094. this._getDescendants(this._scene.lights, results);
  7095. this._getDescendants(this._scene.cameras, results);
  7096. return results;
  7097. };
  7098. Node.prototype._setReady = function (state) {
  7099. if (state == this._isReady) {
  7100. return;
  7101. }
  7102. if (!state) {
  7103. this._isReady = false;
  7104. return;
  7105. }
  7106. this._isReady = true;
  7107. if (this.onReady) {
  7108. this.onReady(this);
  7109. }
  7110. };
  7111. return Node;
  7112. })();
  7113. BABYLON.Node = Node;
  7114. })(BABYLON || (BABYLON = {}));
  7115. var BABYLON;
  7116. (function (BABYLON) {
  7117. var FilesInput = (function () {
  7118. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7119. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7120. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7121. this._engine = p_engine;
  7122. this._canvas = p_canvas;
  7123. this._currentScene = p_scene;
  7124. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7125. this._progressCallback = p_progressCallback;
  7126. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7127. this._textureLoadingCallback = p_textureLoadingCallback;
  7128. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7129. }
  7130. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7131. var _this = this;
  7132. if (p_elementToMonitor) {
  7133. this._elementToMonitor = p_elementToMonitor;
  7134. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7135. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7136. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7137. }
  7138. };
  7139. FilesInput.prototype.renderFunction = function () {
  7140. if (this._additionnalRenderLoopLogicCallback) {
  7141. this._additionnalRenderLoopLogicCallback();
  7142. }
  7143. if (this._currentScene) {
  7144. if (this._textureLoadingCallback) {
  7145. var remaining = this._currentScene.getWaitingItemsCount();
  7146. if (remaining > 0) {
  7147. this._textureLoadingCallback(remaining);
  7148. }
  7149. }
  7150. this._currentScene.render();
  7151. }
  7152. };
  7153. FilesInput.prototype.drag = function (e) {
  7154. e.stopPropagation();
  7155. e.preventDefault();
  7156. };
  7157. FilesInput.prototype.drop = function (eventDrop) {
  7158. eventDrop.stopPropagation();
  7159. eventDrop.preventDefault();
  7160. this.loadFiles(eventDrop);
  7161. };
  7162. FilesInput.prototype.loadFiles = function (event) {
  7163. if (this._startingProcessingFilesCallback)
  7164. this._startingProcessingFilesCallback();
  7165. // Handling data transfer via drag'n'drop
  7166. if (event && event.dataTransfer && event.dataTransfer.files) {
  7167. this._filesToLoad = event.dataTransfer.files;
  7168. }
  7169. // Handling files from input files
  7170. if (event && event.target && event.target.files) {
  7171. this._filesToLoad = event.target.files;
  7172. }
  7173. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7174. for (var i = 0; i < this._filesToLoad.length; i++) {
  7175. switch (this._filesToLoad[i].type) {
  7176. case "image/jpeg":
  7177. case "image/png":
  7178. case "image/bmp":
  7179. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7180. break;
  7181. case "image/targa":
  7182. case "image/vnd.ms-dds":
  7183. case "audio/wav":
  7184. case "audio/x-wav":
  7185. case "audio/mp3":
  7186. case "audio/mpeg":
  7187. case "audio/mpeg3":
  7188. case "audio/x-mpeg-3":
  7189. case "audio/ogg":
  7190. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7191. break;
  7192. default:
  7193. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7194. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7195. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7196. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7197. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7198. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7199. this._sceneFileToLoad = this._filesToLoad[i];
  7200. }
  7201. break;
  7202. }
  7203. }
  7204. this.reload();
  7205. }
  7206. };
  7207. FilesInput.prototype.reload = function () {
  7208. var _this = this;
  7209. var that = this;
  7210. // If a ".babylon" file has been provided
  7211. if (this._sceneFileToLoad) {
  7212. if (this._currentScene) {
  7213. if (BABYLON.Tools.errorsCount > 0) {
  7214. BABYLON.Tools.ClearLogCache();
  7215. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7216. }
  7217. this._engine.stopRenderLoop();
  7218. this._currentScene.dispose();
  7219. }
  7220. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7221. that._currentScene = newScene;
  7222. // Wait for textures and shaders to be ready
  7223. that._currentScene.executeWhenReady(function () {
  7224. // Attach camera to canvas inputs
  7225. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7226. that._currentScene.createDefaultCameraOrLight();
  7227. }
  7228. that._currentScene.activeCamera.attachControl(that._canvas);
  7229. if (that._sceneLoadedCallback) {
  7230. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7231. }
  7232. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7233. });
  7234. }, function (progress) {
  7235. if (_this._progressCallback) {
  7236. _this._progressCallback(progress);
  7237. }
  7238. });
  7239. }
  7240. else {
  7241. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7242. }
  7243. };
  7244. FilesInput.FilesTextures = new Array();
  7245. FilesInput.FilesToLoad = new Array();
  7246. return FilesInput;
  7247. })();
  7248. BABYLON.FilesInput = FilesInput;
  7249. })(BABYLON || (BABYLON = {}));
  7250. var BABYLON;
  7251. (function (BABYLON) {
  7252. var IntersectionInfo = (function () {
  7253. function IntersectionInfo(bu, bv, distance) {
  7254. this.bu = bu;
  7255. this.bv = bv;
  7256. this.distance = distance;
  7257. this.faceId = 0;
  7258. this.subMeshId = 0;
  7259. }
  7260. return IntersectionInfo;
  7261. })();
  7262. BABYLON.IntersectionInfo = IntersectionInfo;
  7263. var PickingInfo = (function () {
  7264. function PickingInfo() {
  7265. this.hit = false;
  7266. this.distance = 0;
  7267. this.pickedPoint = null;
  7268. this.pickedMesh = null;
  7269. this.bu = 0;
  7270. this.bv = 0;
  7271. this.faceId = -1;
  7272. this.subMeshId = 0;
  7273. this.pickedSprite = null;
  7274. }
  7275. // Methods
  7276. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7277. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7278. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7279. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7280. return null;
  7281. }
  7282. var indices = this.pickedMesh.getIndices();
  7283. var result;
  7284. if (useVerticesNormals) {
  7285. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7286. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7287. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7288. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7289. normal0 = normal0.scale(this.bu);
  7290. normal1 = normal1.scale(this.bv);
  7291. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7292. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7293. }
  7294. else {
  7295. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7296. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7297. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7298. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7299. var p1p2 = vertex1.subtract(vertex2);
  7300. var p3p2 = vertex3.subtract(vertex2);
  7301. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7302. }
  7303. if (useWorldCoordinates) {
  7304. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7305. }
  7306. return BABYLON.Vector3.Normalize(result);
  7307. };
  7308. PickingInfo.prototype.getTextureCoordinates = function () {
  7309. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7310. return null;
  7311. }
  7312. var indices = this.pickedMesh.getIndices();
  7313. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7314. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7315. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7316. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7317. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7318. uv1 = uv1.scale(this.bu);
  7319. uv2 = uv2.scale(this.bv);
  7320. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7321. };
  7322. return PickingInfo;
  7323. })();
  7324. BABYLON.PickingInfo = PickingInfo;
  7325. })(BABYLON || (BABYLON = {}));
  7326. var BABYLON;
  7327. (function (BABYLON) {
  7328. var BoundingSphere = (function () {
  7329. function BoundingSphere(minimum, maximum) {
  7330. this.minimum = minimum;
  7331. this.maximum = maximum;
  7332. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7333. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7334. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7335. this.radius = distance * 0.5;
  7336. this.centerWorld = BABYLON.Vector3.Zero();
  7337. this._update(BABYLON.Matrix.Identity());
  7338. }
  7339. // Methods
  7340. BoundingSphere.prototype._update = function (world) {
  7341. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7342. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7343. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7344. };
  7345. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7346. for (var i = 0; i < 6; i++) {
  7347. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7348. return false;
  7349. }
  7350. return true;
  7351. };
  7352. BoundingSphere.prototype.intersectsPoint = function (point) {
  7353. var x = this.centerWorld.x - point.x;
  7354. var y = this.centerWorld.y - point.y;
  7355. var z = this.centerWorld.z - point.z;
  7356. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7357. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7358. return false;
  7359. return true;
  7360. };
  7361. // Statics
  7362. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7363. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7364. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7365. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7366. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7367. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7368. return false;
  7369. return true;
  7370. };
  7371. return BoundingSphere;
  7372. })();
  7373. BABYLON.BoundingSphere = BoundingSphere;
  7374. })(BABYLON || (BABYLON = {}));
  7375. var BABYLON;
  7376. (function (BABYLON) {
  7377. var BoundingBox = (function () {
  7378. function BoundingBox(minimum, maximum) {
  7379. this.minimum = minimum;
  7380. this.maximum = maximum;
  7381. this.vectors = new Array();
  7382. this.vectorsWorld = new Array();
  7383. // Bounding vectors
  7384. this.vectors.push(this.minimum.clone());
  7385. this.vectors.push(this.maximum.clone());
  7386. this.vectors.push(this.minimum.clone());
  7387. this.vectors[2].x = this.maximum.x;
  7388. this.vectors.push(this.minimum.clone());
  7389. this.vectors[3].y = this.maximum.y;
  7390. this.vectors.push(this.minimum.clone());
  7391. this.vectors[4].z = this.maximum.z;
  7392. this.vectors.push(this.maximum.clone());
  7393. this.vectors[5].z = this.minimum.z;
  7394. this.vectors.push(this.maximum.clone());
  7395. this.vectors[6].x = this.minimum.x;
  7396. this.vectors.push(this.maximum.clone());
  7397. this.vectors[7].y = this.minimum.y;
  7398. // OBB
  7399. this.center = this.maximum.add(this.minimum).scale(0.5);
  7400. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7401. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7402. // World
  7403. for (var index = 0; index < this.vectors.length; index++) {
  7404. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7405. }
  7406. this.minimumWorld = BABYLON.Vector3.Zero();
  7407. this.maximumWorld = BABYLON.Vector3.Zero();
  7408. this._update(BABYLON.Matrix.Identity());
  7409. }
  7410. // Methods
  7411. BoundingBox.prototype.getWorldMatrix = function () {
  7412. return this._worldMatrix;
  7413. };
  7414. BoundingBox.prototype._update = function (world) {
  7415. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7416. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7417. for (var index = 0; index < this.vectors.length; index++) {
  7418. var v = this.vectorsWorld[index];
  7419. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7420. if (v.x < this.minimumWorld.x)
  7421. this.minimumWorld.x = v.x;
  7422. if (v.y < this.minimumWorld.y)
  7423. this.minimumWorld.y = v.y;
  7424. if (v.z < this.minimumWorld.z)
  7425. this.minimumWorld.z = v.z;
  7426. if (v.x > this.maximumWorld.x)
  7427. this.maximumWorld.x = v.x;
  7428. if (v.y > this.maximumWorld.y)
  7429. this.maximumWorld.y = v.y;
  7430. if (v.z > this.maximumWorld.z)
  7431. this.maximumWorld.z = v.z;
  7432. }
  7433. // OBB
  7434. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7435. this.center.scaleInPlace(0.5);
  7436. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7437. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7438. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7439. this._worldMatrix = world;
  7440. };
  7441. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7442. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7443. };
  7444. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7445. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7446. };
  7447. BoundingBox.prototype.intersectsPoint = function (point) {
  7448. var delta = -BABYLON.Engine.Epsilon;
  7449. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7450. return false;
  7451. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7452. return false;
  7453. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7454. return false;
  7455. return true;
  7456. };
  7457. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7458. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7459. };
  7460. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7461. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7462. return false;
  7463. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7464. return false;
  7465. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7466. return false;
  7467. return true;
  7468. };
  7469. // Statics
  7470. BoundingBox.Intersects = function (box0, box1) {
  7471. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7472. return false;
  7473. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7474. return false;
  7475. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7476. return false;
  7477. return true;
  7478. };
  7479. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7480. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7481. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7482. return (num <= (sphereRadius * sphereRadius));
  7483. };
  7484. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7485. for (var p = 0; p < 6; p++) {
  7486. for (var i = 0; i < 8; i++) {
  7487. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7488. return false;
  7489. }
  7490. }
  7491. }
  7492. return true;
  7493. };
  7494. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7495. for (var p = 0; p < 6; p++) {
  7496. var inCount = 8;
  7497. for (var i = 0; i < 8; i++) {
  7498. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7499. --inCount;
  7500. }
  7501. else {
  7502. break;
  7503. }
  7504. }
  7505. if (inCount === 0)
  7506. return false;
  7507. }
  7508. return true;
  7509. };
  7510. return BoundingBox;
  7511. })();
  7512. BABYLON.BoundingBox = BoundingBox;
  7513. })(BABYLON || (BABYLON = {}));
  7514. var BABYLON;
  7515. (function (BABYLON) {
  7516. var computeBoxExtents = function (axis, box) {
  7517. var p = BABYLON.Vector3.Dot(box.center, axis);
  7518. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7519. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7520. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7521. var r = r0 + r1 + r2;
  7522. return {
  7523. min: p - r,
  7524. max: p + r
  7525. };
  7526. };
  7527. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7528. var axisOverlap = function (axis, box0, box1) {
  7529. var result0 = computeBoxExtents(axis, box0);
  7530. var result1 = computeBoxExtents(axis, box1);
  7531. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7532. };
  7533. var BoundingInfo = (function () {
  7534. function BoundingInfo(minimum, maximum) {
  7535. this.minimum = minimum;
  7536. this.maximum = maximum;
  7537. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7538. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7539. }
  7540. // Methods
  7541. BoundingInfo.prototype._update = function (world) {
  7542. this.boundingBox._update(world);
  7543. this.boundingSphere._update(world);
  7544. };
  7545. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7546. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7547. return false;
  7548. return this.boundingBox.isInFrustum(frustumPlanes);
  7549. };
  7550. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7551. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7552. };
  7553. BoundingInfo.prototype._checkCollision = function (collider) {
  7554. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7555. };
  7556. BoundingInfo.prototype.intersectsPoint = function (point) {
  7557. if (!this.boundingSphere.centerWorld) {
  7558. return false;
  7559. }
  7560. if (!this.boundingSphere.intersectsPoint(point)) {
  7561. return false;
  7562. }
  7563. if (!this.boundingBox.intersectsPoint(point)) {
  7564. return false;
  7565. }
  7566. return true;
  7567. };
  7568. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7569. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7570. return false;
  7571. }
  7572. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7573. return false;
  7574. }
  7575. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7576. return false;
  7577. }
  7578. if (!precise) {
  7579. return true;
  7580. }
  7581. var box0 = this.boundingBox;
  7582. var box1 = boundingInfo.boundingBox;
  7583. if (!axisOverlap(box0.directions[0], box0, box1))
  7584. return false;
  7585. if (!axisOverlap(box0.directions[1], box0, box1))
  7586. return false;
  7587. if (!axisOverlap(box0.directions[2], box0, box1))
  7588. return false;
  7589. if (!axisOverlap(box1.directions[0], box0, box1))
  7590. return false;
  7591. if (!axisOverlap(box1.directions[1], box0, box1))
  7592. return false;
  7593. if (!axisOverlap(box1.directions[2], box0, box1))
  7594. return false;
  7595. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7596. return false;
  7597. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7598. return false;
  7599. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7600. return false;
  7601. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7602. return false;
  7603. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7604. return false;
  7605. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7606. return false;
  7607. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7608. return false;
  7609. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7610. return false;
  7611. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7612. return false;
  7613. return true;
  7614. };
  7615. return BoundingInfo;
  7616. })();
  7617. BABYLON.BoundingInfo = BoundingInfo;
  7618. })(BABYLON || (BABYLON = {}));
  7619. var BABYLON;
  7620. (function (BABYLON) {
  7621. var AbstractMesh = (function (_super) {
  7622. __extends(AbstractMesh, _super);
  7623. function AbstractMesh(name, scene) {
  7624. var _this = this;
  7625. _super.call(this, name, scene);
  7626. // Properties
  7627. this.definedFacingForward = true; // orientation for POV movement & rotation
  7628. this.position = new BABYLON.Vector3(0, 0, 0);
  7629. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7630. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7631. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7632. this.visibility = 1.0;
  7633. this.alphaIndex = Number.MAX_VALUE;
  7634. this.infiniteDistance = false;
  7635. this.isVisible = true;
  7636. this.isPickable = true;
  7637. this.showBoundingBox = false;
  7638. this.showSubMeshesBoundingBox = false;
  7639. this.onDispose = null;
  7640. this.isBlocker = false;
  7641. this.renderingGroupId = 0;
  7642. this.receiveShadows = false;
  7643. this.renderOutline = false;
  7644. this.outlineColor = BABYLON.Color3.Red();
  7645. this.outlineWidth = 0.02;
  7646. this.renderOverlay = false;
  7647. this.overlayColor = BABYLON.Color3.Red();
  7648. this.overlayAlpha = 0.5;
  7649. this.hasVertexAlpha = false;
  7650. this.useVertexColors = true;
  7651. this.applyFog = true;
  7652. this.computeBonesUsingShaders = true;
  7653. this.scalingDeterminant = 1;
  7654. this.useOctreeForRenderingSelection = true;
  7655. this.useOctreeForPicking = true;
  7656. this.useOctreeForCollisions = true;
  7657. this.layerMask = 0x0FFFFFFF;
  7658. this.alwaysSelectAsActiveMesh = false;
  7659. // Physics
  7660. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7661. // Collisions
  7662. this._checkCollisions = false;
  7663. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7664. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7665. this._collider = new BABYLON.Collider();
  7666. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7667. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7668. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7669. // Edges
  7670. this.edgesWidth = 1;
  7671. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7672. // Cache
  7673. this._localScaling = BABYLON.Matrix.Zero();
  7674. this._localRotation = BABYLON.Matrix.Zero();
  7675. this._localTranslation = BABYLON.Matrix.Zero();
  7676. this._localBillboard = BABYLON.Matrix.Zero();
  7677. this._localPivotScaling = BABYLON.Matrix.Zero();
  7678. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7679. this._localWorld = BABYLON.Matrix.Zero();
  7680. this._worldMatrix = BABYLON.Matrix.Zero();
  7681. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7682. this._absolutePosition = BABYLON.Vector3.Zero();
  7683. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7684. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7685. this._isDirty = false;
  7686. this._pivotMatrix = BABYLON.Matrix.Identity();
  7687. this._isDisposed = false;
  7688. this._renderId = 0;
  7689. this._intersectionsInProgress = new Array();
  7690. this._onAfterWorldMatrixUpdate = new Array();
  7691. this._isWorldMatrixFrozen = false;
  7692. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7693. if (collidedMesh === void 0) { collidedMesh = null; }
  7694. //TODO move this to the collision coordinator!
  7695. if (_this.getScene().workerCollisions)
  7696. newPosition.multiplyInPlace(_this._collider.radius);
  7697. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7698. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7699. _this.position.addInPlace(_this._diffPositionForCollisions);
  7700. }
  7701. if (_this.onCollide && collidedMesh) {
  7702. _this.onCollide(collidedMesh);
  7703. }
  7704. };
  7705. scene.addMesh(this);
  7706. }
  7707. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7708. get: function () {
  7709. return AbstractMesh._BILLBOARDMODE_NONE;
  7710. },
  7711. enumerable: true,
  7712. configurable: true
  7713. });
  7714. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7715. get: function () {
  7716. return AbstractMesh._BILLBOARDMODE_X;
  7717. },
  7718. enumerable: true,
  7719. configurable: true
  7720. });
  7721. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7722. get: function () {
  7723. return AbstractMesh._BILLBOARDMODE_Y;
  7724. },
  7725. enumerable: true,
  7726. configurable: true
  7727. });
  7728. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7729. get: function () {
  7730. return AbstractMesh._BILLBOARDMODE_Z;
  7731. },
  7732. enumerable: true,
  7733. configurable: true
  7734. });
  7735. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7736. get: function () {
  7737. return AbstractMesh._BILLBOARDMODE_ALL;
  7738. },
  7739. enumerable: true,
  7740. configurable: true
  7741. });
  7742. // Methods
  7743. AbstractMesh.prototype.disableEdgesRendering = function () {
  7744. if (this._edgesRenderer !== undefined) {
  7745. this._edgesRenderer.dispose();
  7746. this._edgesRenderer = undefined;
  7747. }
  7748. };
  7749. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7750. if (epsilon === void 0) { epsilon = 0.95; }
  7751. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7752. this.disableEdgesRendering();
  7753. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7754. };
  7755. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7756. get: function () {
  7757. return false;
  7758. },
  7759. enumerable: true,
  7760. configurable: true
  7761. });
  7762. AbstractMesh.prototype.getLOD = function (camera) {
  7763. return this;
  7764. };
  7765. AbstractMesh.prototype.getTotalVertices = function () {
  7766. return 0;
  7767. };
  7768. AbstractMesh.prototype.getIndices = function () {
  7769. return null;
  7770. };
  7771. AbstractMesh.prototype.getVerticesData = function (kind) {
  7772. return null;
  7773. };
  7774. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7775. return false;
  7776. };
  7777. AbstractMesh.prototype.getBoundingInfo = function () {
  7778. if (this._masterMesh) {
  7779. return this._masterMesh.getBoundingInfo();
  7780. }
  7781. if (!this._boundingInfo) {
  7782. this._updateBoundingInfo();
  7783. }
  7784. return this._boundingInfo;
  7785. };
  7786. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7787. get: function () {
  7788. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7789. },
  7790. enumerable: true,
  7791. configurable: true
  7792. });
  7793. AbstractMesh.prototype._preActivate = function () {
  7794. };
  7795. AbstractMesh.prototype._activate = function (renderId) {
  7796. this._renderId = renderId;
  7797. };
  7798. AbstractMesh.prototype.getWorldMatrix = function () {
  7799. if (this._masterMesh) {
  7800. return this._masterMesh.getWorldMatrix();
  7801. }
  7802. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7803. this.computeWorldMatrix();
  7804. }
  7805. return this._worldMatrix;
  7806. };
  7807. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7808. get: function () {
  7809. return this._worldMatrix;
  7810. },
  7811. enumerable: true,
  7812. configurable: true
  7813. });
  7814. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7815. get: function () {
  7816. return this._absolutePosition;
  7817. },
  7818. enumerable: true,
  7819. configurable: true
  7820. });
  7821. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7822. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7823. this.computeWorldMatrix(true);
  7824. this._isWorldMatrixFrozen = true;
  7825. };
  7826. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7827. this._isWorldMatrixFrozen = false;
  7828. this.computeWorldMatrix(true);
  7829. };
  7830. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7831. get: function () {
  7832. return this._isWorldMatrixFrozen;
  7833. },
  7834. enumerable: true,
  7835. configurable: true
  7836. });
  7837. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7838. axis.normalize();
  7839. if (!this.rotationQuaternion) {
  7840. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7841. this.rotation = BABYLON.Vector3.Zero();
  7842. }
  7843. var rotationQuaternion;
  7844. if (!space || space === BABYLON.Space.LOCAL) {
  7845. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7846. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7847. }
  7848. else {
  7849. if (this.parent) {
  7850. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7851. invertParentWorldMatrix.invert();
  7852. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7853. }
  7854. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7855. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7856. }
  7857. };
  7858. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7859. var displacementVector = axis.scale(distance);
  7860. if (!space || space === BABYLON.Space.LOCAL) {
  7861. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7862. this.setPositionWithLocalVector(tempV3);
  7863. }
  7864. else {
  7865. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7866. }
  7867. };
  7868. AbstractMesh.prototype.getAbsolutePosition = function () {
  7869. this.computeWorldMatrix();
  7870. return this._absolutePosition;
  7871. };
  7872. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7873. if (!absolutePosition) {
  7874. return;
  7875. }
  7876. var absolutePositionX;
  7877. var absolutePositionY;
  7878. var absolutePositionZ;
  7879. if (absolutePosition.x === undefined) {
  7880. if (arguments.length < 3) {
  7881. return;
  7882. }
  7883. absolutePositionX = arguments[0];
  7884. absolutePositionY = arguments[1];
  7885. absolutePositionZ = arguments[2];
  7886. }
  7887. else {
  7888. absolutePositionX = absolutePosition.x;
  7889. absolutePositionY = absolutePosition.y;
  7890. absolutePositionZ = absolutePosition.z;
  7891. }
  7892. if (this.parent) {
  7893. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7894. invertParentWorldMatrix.invert();
  7895. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7896. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7897. }
  7898. else {
  7899. this.position.x = absolutePositionX;
  7900. this.position.y = absolutePositionY;
  7901. this.position.z = absolutePositionZ;
  7902. }
  7903. };
  7904. // ================================== Point of View Movement =================================
  7905. /**
  7906. * Perform relative position change from the point of view of behind the front of the mesh.
  7907. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7908. * Supports definition of mesh facing forward or backward.
  7909. * @param {number} amountRight
  7910. * @param {number} amountUp
  7911. * @param {number} amountForward
  7912. */
  7913. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7914. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7915. };
  7916. /**
  7917. * Calculate relative position change from the point of view of behind the front of the mesh.
  7918. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7919. * Supports definition of mesh facing forward or backward.
  7920. * @param {number} amountRight
  7921. * @param {number} amountUp
  7922. * @param {number} amountForward
  7923. */
  7924. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7925. var rotMatrix = new BABYLON.Matrix();
  7926. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7927. rotQuaternion.toRotationMatrix(rotMatrix);
  7928. var translationDelta = BABYLON.Vector3.Zero();
  7929. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7930. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7931. return translationDelta;
  7932. };
  7933. // ================================== Point of View Rotation =================================
  7934. /**
  7935. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7936. * Supports definition of mesh facing forward or backward.
  7937. * @param {number} flipBack
  7938. * @param {number} twirlClockwise
  7939. * @param {number} tiltRight
  7940. */
  7941. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7942. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7943. };
  7944. /**
  7945. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7946. * Supports definition of mesh facing forward or backward.
  7947. * @param {number} flipBack
  7948. * @param {number} twirlClockwise
  7949. * @param {number} tiltRight
  7950. */
  7951. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7952. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7953. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7954. };
  7955. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7956. this._pivotMatrix = matrix;
  7957. this._cache.pivotMatrixUpdated = true;
  7958. };
  7959. AbstractMesh.prototype.getPivotMatrix = function () {
  7960. return this._pivotMatrix;
  7961. };
  7962. AbstractMesh.prototype._isSynchronized = function () {
  7963. if (this._isDirty) {
  7964. return false;
  7965. }
  7966. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7967. return false;
  7968. if (this._cache.pivotMatrixUpdated) {
  7969. return false;
  7970. }
  7971. if (this.infiniteDistance) {
  7972. return false;
  7973. }
  7974. if (!this._cache.position.equals(this.position))
  7975. return false;
  7976. if (this.rotationQuaternion) {
  7977. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7978. return false;
  7979. }
  7980. else {
  7981. if (!this._cache.rotation.equals(this.rotation))
  7982. return false;
  7983. }
  7984. if (!this._cache.scaling.equals(this.scaling))
  7985. return false;
  7986. return true;
  7987. };
  7988. AbstractMesh.prototype._initCache = function () {
  7989. _super.prototype._initCache.call(this);
  7990. this._cache.localMatrixUpdated = false;
  7991. this._cache.position = BABYLON.Vector3.Zero();
  7992. this._cache.scaling = BABYLON.Vector3.Zero();
  7993. this._cache.rotation = BABYLON.Vector3.Zero();
  7994. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7995. };
  7996. AbstractMesh.prototype.markAsDirty = function (property) {
  7997. if (property === "rotation") {
  7998. this.rotationQuaternion = null;
  7999. }
  8000. this._currentRenderId = Number.MAX_VALUE;
  8001. this._isDirty = true;
  8002. };
  8003. AbstractMesh.prototype._updateBoundingInfo = function () {
  8004. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8005. this._boundingInfo._update(this.worldMatrixFromCache);
  8006. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8007. };
  8008. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8009. if (!this.subMeshes) {
  8010. return;
  8011. }
  8012. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8013. var subMesh = this.subMeshes[subIndex];
  8014. subMesh.updateBoundingInfo(matrix);
  8015. }
  8016. };
  8017. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8018. if (this._isWorldMatrixFrozen) {
  8019. return this._worldMatrix;
  8020. }
  8021. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8022. return this._worldMatrix;
  8023. }
  8024. this._cache.position.copyFrom(this.position);
  8025. this._cache.scaling.copyFrom(this.scaling);
  8026. this._cache.pivotMatrixUpdated = false;
  8027. this._currentRenderId = this.getScene().getRenderId();
  8028. this._isDirty = false;
  8029. // Scaling
  8030. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  8031. // Rotation
  8032. if (this.rotationQuaternion) {
  8033. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8034. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8035. }
  8036. else {
  8037. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8038. this._cache.rotation.copyFrom(this.rotation);
  8039. }
  8040. // Translation
  8041. if (this.infiniteDistance && !this.parent) {
  8042. var camera = this.getScene().activeCamera;
  8043. if (camera) {
  8044. var cameraWorldMatrix = camera.getWorldMatrix();
  8045. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8046. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8047. }
  8048. }
  8049. else {
  8050. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8051. }
  8052. // Composing transformations
  8053. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8054. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8055. // Billboarding
  8056. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8057. var localPosition = this.position.clone();
  8058. var zero = this.getScene().activeCamera.globalPosition.clone();
  8059. if (this.parent && this.parent.position) {
  8060. localPosition.addInPlace(this.parent.position);
  8061. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8062. }
  8063. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8064. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8065. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8066. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8067. zero.y = localPosition.y + 0.001;
  8068. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8069. zero.z = localPosition.z + 0.001;
  8070. }
  8071. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8072. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8073. this._localBillboard.invert();
  8074. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8075. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8076. }
  8077. // Local world
  8078. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8079. // Parent
  8080. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8081. this._markSyncedWithParent();
  8082. if (this._meshToBoneReferal) {
  8083. if (!this._localMeshReferalTransform) {
  8084. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8085. }
  8086. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8087. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8088. }
  8089. else {
  8090. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8091. }
  8092. }
  8093. else {
  8094. this._worldMatrix.copyFrom(this._localWorld);
  8095. }
  8096. // Bounding info
  8097. this._updateBoundingInfo();
  8098. // Absolute position
  8099. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8100. // Callbacks
  8101. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8102. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8103. }
  8104. return this._worldMatrix;
  8105. };
  8106. /**
  8107. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8108. * @param func: callback function to add
  8109. */
  8110. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8111. this._onAfterWorldMatrixUpdate.push(func);
  8112. };
  8113. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8114. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8115. if (index > -1) {
  8116. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8117. }
  8118. };
  8119. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8120. this.computeWorldMatrix();
  8121. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8122. };
  8123. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8124. this.computeWorldMatrix();
  8125. var invLocalWorldMatrix = this._localWorld.clone();
  8126. invLocalWorldMatrix.invert();
  8127. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8128. };
  8129. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8130. this.computeWorldMatrix(true);
  8131. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8132. };
  8133. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8134. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8135. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8136. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8137. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8138. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8139. /// <returns>Mesh oriented towards targetMesh</returns>
  8140. yawCor = yawCor || 0; // default to zero if undefined
  8141. pitchCor = pitchCor || 0;
  8142. rollCor = rollCor || 0;
  8143. var dv = targetPoint.subtract(this.position);
  8144. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8145. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8146. var pitch = Math.atan2(dv.y, len);
  8147. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8148. };
  8149. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8150. this._meshToBoneReferal = affectedMesh;
  8151. this.parent = bone;
  8152. if (bone.getWorldMatrix().determinant() < 0) {
  8153. this.scalingDeterminant *= -1;
  8154. }
  8155. };
  8156. AbstractMesh.prototype.detachFromBone = function () {
  8157. if (this.parent.getWorldMatrix().determinant() < 0) {
  8158. this.scalingDeterminant *= -1;
  8159. }
  8160. this._meshToBoneReferal = null;
  8161. this.parent = null;
  8162. };
  8163. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8164. return this._boundingInfo.isInFrustum(frustumPlanes);
  8165. };
  8166. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8167. if (!camera) {
  8168. camera = this.getScene().activeCamera;
  8169. }
  8170. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8171. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8172. return false;
  8173. }
  8174. return true;
  8175. };
  8176. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8177. if (!this._boundingInfo || !mesh._boundingInfo) {
  8178. return false;
  8179. }
  8180. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8181. };
  8182. AbstractMesh.prototype.intersectsPoint = function (point) {
  8183. if (!this._boundingInfo) {
  8184. return false;
  8185. }
  8186. return this._boundingInfo.intersectsPoint(point);
  8187. };
  8188. // Physics
  8189. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8190. var physicsEngine = this.getScene().getPhysicsEngine();
  8191. if (!physicsEngine) {
  8192. return null;
  8193. }
  8194. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8195. if (impostor.impostor) {
  8196. // Old API
  8197. options = impostor;
  8198. impostor = impostor.impostor;
  8199. }
  8200. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8201. physicsEngine._unregisterMesh(this);
  8202. return null;
  8203. }
  8204. if (!options) {
  8205. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8206. }
  8207. else {
  8208. if (!options.mass && options.mass !== 0)
  8209. options.mass = 0;
  8210. if (!options.friction && options.friction !== 0)
  8211. options.friction = 0.2;
  8212. if (!options.restitution && options.restitution !== 0)
  8213. options.restitution = 0.2;
  8214. }
  8215. this._physicImpostor = impostor;
  8216. this._physicsMass = options.mass;
  8217. this._physicsFriction = options.friction;
  8218. this._physicRestitution = options.restitution;
  8219. return physicsEngine._registerMesh(this, impostor, options);
  8220. };
  8221. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8222. if (!this._physicImpostor) {
  8223. return BABYLON.PhysicsEngine.NoImpostor;
  8224. }
  8225. return this._physicImpostor;
  8226. };
  8227. AbstractMesh.prototype.getPhysicsMass = function () {
  8228. if (!this._physicsMass) {
  8229. return 0;
  8230. }
  8231. return this._physicsMass;
  8232. };
  8233. AbstractMesh.prototype.getPhysicsFriction = function () {
  8234. if (!this._physicsFriction) {
  8235. return 0;
  8236. }
  8237. return this._physicsFriction;
  8238. };
  8239. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8240. if (!this._physicRestitution) {
  8241. return 0;
  8242. }
  8243. return this._physicRestitution;
  8244. };
  8245. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8246. if (!camera) {
  8247. camera = this.getScene().activeCamera;
  8248. }
  8249. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8250. };
  8251. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8252. if (!camera) {
  8253. camera = this.getScene().activeCamera;
  8254. }
  8255. return this.absolutePosition.subtract(camera.position).length();
  8256. };
  8257. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8258. if (!this._physicImpostor) {
  8259. return;
  8260. }
  8261. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8262. };
  8263. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8264. if (!this._physicImpostor) {
  8265. return;
  8266. }
  8267. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8268. };
  8269. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8270. if (!this._physicImpostor) {
  8271. return;
  8272. }
  8273. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8274. };
  8275. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8276. // Collisions
  8277. get: function () {
  8278. return this._checkCollisions;
  8279. },
  8280. set: function (collisionEnabled) {
  8281. this._checkCollisions = collisionEnabled;
  8282. if (this.getScene().workerCollisions) {
  8283. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8284. }
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8290. var globalPosition = this.getAbsolutePosition();
  8291. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8292. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8293. this._collider.radius = this.ellipsoid;
  8294. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8295. };
  8296. // Submeshes octree
  8297. /**
  8298. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8299. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8300. */
  8301. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8302. if (maxCapacity === void 0) { maxCapacity = 64; }
  8303. if (maxDepth === void 0) { maxDepth = 2; }
  8304. if (!this._submeshesOctree) {
  8305. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8306. }
  8307. this.computeWorldMatrix(true);
  8308. // Update octree
  8309. var bbox = this.getBoundingInfo().boundingBox;
  8310. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8311. return this._submeshesOctree;
  8312. };
  8313. // Collisions
  8314. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8315. this._generatePointsArray();
  8316. // Transformation
  8317. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8318. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8319. subMesh._lastColliderWorldVertices = [];
  8320. subMesh._trianglePlanes = [];
  8321. var start = subMesh.verticesStart;
  8322. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8323. for (var i = start; i < end; i++) {
  8324. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8325. }
  8326. }
  8327. // Collide
  8328. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8329. if (collider.collisionFound) {
  8330. collider.collidedMesh = this;
  8331. }
  8332. };
  8333. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8334. var subMeshes;
  8335. var len;
  8336. // Octrees
  8337. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8338. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8339. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8340. len = intersections.length;
  8341. subMeshes = intersections.data;
  8342. }
  8343. else {
  8344. subMeshes = this.subMeshes;
  8345. len = subMeshes.length;
  8346. }
  8347. for (var index = 0; index < len; index++) {
  8348. var subMesh = subMeshes[index];
  8349. // Bounding test
  8350. if (len > 1 && !subMesh._checkCollision(collider))
  8351. continue;
  8352. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8353. }
  8354. };
  8355. AbstractMesh.prototype._checkCollision = function (collider) {
  8356. // Bounding box test
  8357. if (!this._boundingInfo._checkCollision(collider))
  8358. return;
  8359. // Transformation matrix
  8360. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8361. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8362. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8363. };
  8364. // Picking
  8365. AbstractMesh.prototype._generatePointsArray = function () {
  8366. return false;
  8367. };
  8368. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8369. var pickingInfo = new BABYLON.PickingInfo();
  8370. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8371. return pickingInfo;
  8372. }
  8373. if (!this._generatePointsArray()) {
  8374. return pickingInfo;
  8375. }
  8376. var intersectInfo = null;
  8377. // Octrees
  8378. var subMeshes;
  8379. var len;
  8380. if (this._submeshesOctree && this.useOctreeForPicking) {
  8381. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8382. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8383. len = intersections.length;
  8384. subMeshes = intersections.data;
  8385. }
  8386. else {
  8387. subMeshes = this.subMeshes;
  8388. len = subMeshes.length;
  8389. }
  8390. for (var index = 0; index < len; index++) {
  8391. var subMesh = subMeshes[index];
  8392. // Bounding test
  8393. if (len > 1 && !subMesh.canIntersects(ray))
  8394. continue;
  8395. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8396. if (currentIntersectInfo) {
  8397. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8398. intersectInfo = currentIntersectInfo;
  8399. intersectInfo.subMeshId = index;
  8400. if (fastCheck) {
  8401. break;
  8402. }
  8403. }
  8404. }
  8405. }
  8406. if (intersectInfo) {
  8407. // Get picked point
  8408. var world = this.getWorldMatrix();
  8409. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8410. var direction = ray.direction.clone();
  8411. direction = direction.scale(intersectInfo.distance);
  8412. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8413. var pickedPoint = worldOrigin.add(worldDirection);
  8414. // Return result
  8415. pickingInfo.hit = true;
  8416. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8417. pickingInfo.pickedPoint = pickedPoint;
  8418. pickingInfo.pickedMesh = this;
  8419. pickingInfo.bu = intersectInfo.bu;
  8420. pickingInfo.bv = intersectInfo.bv;
  8421. pickingInfo.faceId = intersectInfo.faceId;
  8422. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8423. return pickingInfo;
  8424. }
  8425. return pickingInfo;
  8426. };
  8427. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8428. return null;
  8429. };
  8430. AbstractMesh.prototype.releaseSubMeshes = function () {
  8431. if (this.subMeshes) {
  8432. while (this.subMeshes.length) {
  8433. this.subMeshes[0].dispose();
  8434. }
  8435. }
  8436. else {
  8437. this.subMeshes = new Array();
  8438. }
  8439. };
  8440. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8441. var index;
  8442. // Physics
  8443. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8444. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8445. }
  8446. // Intersections in progress
  8447. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8448. var other = this._intersectionsInProgress[index];
  8449. var pos = other._intersectionsInProgress.indexOf(this);
  8450. other._intersectionsInProgress.splice(pos, 1);
  8451. }
  8452. this._intersectionsInProgress = [];
  8453. // Edges
  8454. if (this._edgesRenderer) {
  8455. this._edgesRenderer.dispose();
  8456. this._edgesRenderer = null;
  8457. }
  8458. // SubMeshes
  8459. this.releaseSubMeshes();
  8460. // Remove from scene
  8461. this.getScene().removeMesh(this);
  8462. if (!doNotRecurse) {
  8463. // Particles
  8464. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8465. if (this.getScene().particleSystems[index].emitter === this) {
  8466. this.getScene().particleSystems[index].dispose();
  8467. index--;
  8468. }
  8469. }
  8470. // Children
  8471. var objects = this.getScene().meshes.slice(0);
  8472. for (index = 0; index < objects.length; index++) {
  8473. if (objects[index].parent === this) {
  8474. objects[index].dispose();
  8475. }
  8476. }
  8477. }
  8478. else {
  8479. for (index = 0; index < this.getScene().meshes.length; index++) {
  8480. var obj = this.getScene().meshes[index];
  8481. if (obj.parent === this) {
  8482. obj.parent = null;
  8483. obj.computeWorldMatrix(true);
  8484. }
  8485. }
  8486. }
  8487. this._onAfterWorldMatrixUpdate = [];
  8488. this._isDisposed = true;
  8489. // Callback
  8490. if (this.onDispose) {
  8491. this.onDispose();
  8492. }
  8493. };
  8494. // Statics
  8495. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8496. AbstractMesh._BILLBOARDMODE_X = 1;
  8497. AbstractMesh._BILLBOARDMODE_Y = 2;
  8498. AbstractMesh._BILLBOARDMODE_Z = 4;
  8499. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8500. return AbstractMesh;
  8501. })(BABYLON.Node);
  8502. BABYLON.AbstractMesh = AbstractMesh;
  8503. })(BABYLON || (BABYLON = {}));
  8504. var BABYLON;
  8505. (function (BABYLON) {
  8506. var Light = (function (_super) {
  8507. __extends(Light, _super);
  8508. function Light(name, scene) {
  8509. _super.call(this, name, scene);
  8510. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8511. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8512. this.intensity = 1.0;
  8513. this.range = Number.MAX_VALUE;
  8514. this.includeOnlyWithLayerMask = 0;
  8515. this.includedOnlyMeshes = new Array();
  8516. this.excludedMeshes = new Array();
  8517. this.excludeWithLayerMask = 0;
  8518. this._excludedMeshesIds = new Array();
  8519. this._includedOnlyMeshesIds = new Array();
  8520. scene.addLight(this);
  8521. }
  8522. Light.prototype.getShadowGenerator = function () {
  8523. return this._shadowGenerator;
  8524. };
  8525. Light.prototype.getAbsolutePosition = function () {
  8526. return BABYLON.Vector3.Zero();
  8527. };
  8528. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8529. };
  8530. Light.prototype._getWorldMatrix = function () {
  8531. return BABYLON.Matrix.Identity();
  8532. };
  8533. Light.prototype.canAffectMesh = function (mesh) {
  8534. if (!mesh) {
  8535. return true;
  8536. }
  8537. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8538. return false;
  8539. }
  8540. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8541. return false;
  8542. }
  8543. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8544. return false;
  8545. }
  8546. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8547. return false;
  8548. }
  8549. return true;
  8550. };
  8551. Light.prototype.getWorldMatrix = function () {
  8552. this._currentRenderId = this.getScene().getRenderId();
  8553. var worldMatrix = this._getWorldMatrix();
  8554. if (this.parent && this.parent.getWorldMatrix) {
  8555. if (!this._parentedWorldMatrix) {
  8556. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8557. }
  8558. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8559. this._markSyncedWithParent();
  8560. return this._parentedWorldMatrix;
  8561. }
  8562. return worldMatrix;
  8563. };
  8564. Light.prototype.dispose = function () {
  8565. if (this._shadowGenerator) {
  8566. this._shadowGenerator.dispose();
  8567. this._shadowGenerator = null;
  8568. }
  8569. // Remove from scene
  8570. this.getScene().removeLight(this);
  8571. };
  8572. return Light;
  8573. })(BABYLON.Node);
  8574. BABYLON.Light = Light;
  8575. })(BABYLON || (BABYLON = {}));
  8576. var BABYLON;
  8577. (function (BABYLON) {
  8578. var PointLight = (function (_super) {
  8579. __extends(PointLight, _super);
  8580. function PointLight(name, position, scene) {
  8581. _super.call(this, name, scene);
  8582. this.position = position;
  8583. }
  8584. PointLight.prototype.getAbsolutePosition = function () {
  8585. return this._transformedPosition ? this._transformedPosition : this.position;
  8586. };
  8587. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8588. if (this.parent && this.parent.getWorldMatrix) {
  8589. if (!this._transformedPosition) {
  8590. this._transformedPosition = BABYLON.Vector3.Zero();
  8591. }
  8592. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8593. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8594. return;
  8595. }
  8596. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8597. };
  8598. PointLight.prototype.getShadowGenerator = function () {
  8599. return null;
  8600. };
  8601. PointLight.prototype._getWorldMatrix = function () {
  8602. if (!this._worldMatrix) {
  8603. this._worldMatrix = BABYLON.Matrix.Identity();
  8604. }
  8605. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8606. return this._worldMatrix;
  8607. };
  8608. return PointLight;
  8609. })(BABYLON.Light);
  8610. BABYLON.PointLight = PointLight;
  8611. })(BABYLON || (BABYLON = {}));
  8612. var BABYLON;
  8613. (function (BABYLON) {
  8614. var SpotLight = (function (_super) {
  8615. __extends(SpotLight, _super);
  8616. function SpotLight(name, position, direction, angle, exponent, scene) {
  8617. _super.call(this, name, scene);
  8618. this.position = position;
  8619. this.direction = direction;
  8620. this.angle = angle;
  8621. this.exponent = exponent;
  8622. }
  8623. SpotLight.prototype.getAbsolutePosition = function () {
  8624. return this.transformedPosition ? this.transformedPosition : this.position;
  8625. };
  8626. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8627. var activeCamera = this.getScene().activeCamera;
  8628. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8629. };
  8630. SpotLight.prototype.supportsVSM = function () {
  8631. return true;
  8632. };
  8633. SpotLight.prototype.needRefreshPerFrame = function () {
  8634. return false;
  8635. };
  8636. SpotLight.prototype.setDirectionToTarget = function (target) {
  8637. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8638. return this.direction;
  8639. };
  8640. SpotLight.prototype.computeTransformedPosition = function () {
  8641. if (this.parent && this.parent.getWorldMatrix) {
  8642. if (!this.transformedPosition) {
  8643. this.transformedPosition = BABYLON.Vector3.Zero();
  8644. }
  8645. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8646. return true;
  8647. }
  8648. return false;
  8649. };
  8650. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8651. var normalizeDirection;
  8652. if (this.parent && this.parent.getWorldMatrix) {
  8653. if (!this._transformedDirection) {
  8654. this._transformedDirection = BABYLON.Vector3.Zero();
  8655. }
  8656. this.computeTransformedPosition();
  8657. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8658. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8659. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8660. }
  8661. else {
  8662. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8663. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8664. }
  8665. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8666. };
  8667. SpotLight.prototype._getWorldMatrix = function () {
  8668. if (!this._worldMatrix) {
  8669. this._worldMatrix = BABYLON.Matrix.Identity();
  8670. }
  8671. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8672. return this._worldMatrix;
  8673. };
  8674. return SpotLight;
  8675. })(BABYLON.Light);
  8676. BABYLON.SpotLight = SpotLight;
  8677. })(BABYLON || (BABYLON = {}));
  8678. var BABYLON;
  8679. (function (BABYLON) {
  8680. var HemisphericLight = (function (_super) {
  8681. __extends(HemisphericLight, _super);
  8682. function HemisphericLight(name, direction, scene) {
  8683. _super.call(this, name, scene);
  8684. this.direction = direction;
  8685. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8686. }
  8687. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8688. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8689. return this.direction;
  8690. };
  8691. HemisphericLight.prototype.getShadowGenerator = function () {
  8692. return null;
  8693. };
  8694. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8695. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8696. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8697. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8698. };
  8699. HemisphericLight.prototype._getWorldMatrix = function () {
  8700. if (!this._worldMatrix) {
  8701. this._worldMatrix = BABYLON.Matrix.Identity();
  8702. }
  8703. return this._worldMatrix;
  8704. };
  8705. return HemisphericLight;
  8706. })(BABYLON.Light);
  8707. BABYLON.HemisphericLight = HemisphericLight;
  8708. })(BABYLON || (BABYLON = {}));
  8709. var BABYLON;
  8710. (function (BABYLON) {
  8711. var DirectionalLight = (function (_super) {
  8712. __extends(DirectionalLight, _super);
  8713. function DirectionalLight(name, direction, scene) {
  8714. _super.call(this, name, scene);
  8715. this.direction = direction;
  8716. this.shadowOrthoScale = 0.5;
  8717. this.position = direction.scale(-1);
  8718. }
  8719. DirectionalLight.prototype.getAbsolutePosition = function () {
  8720. return this.transformedPosition ? this.transformedPosition : this.position;
  8721. };
  8722. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8723. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8724. return this.direction;
  8725. };
  8726. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8727. var orthoLeft = Number.MAX_VALUE;
  8728. var orthoRight = Number.MIN_VALUE;
  8729. var orthoTop = Number.MIN_VALUE;
  8730. var orthoBottom = Number.MAX_VALUE;
  8731. var tempVector3 = BABYLON.Vector3.Zero();
  8732. var activeCamera = this.getScene().activeCamera;
  8733. // Check extends
  8734. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8735. var mesh = renderList[meshIndex];
  8736. if (!mesh) {
  8737. continue;
  8738. }
  8739. var boundingInfo = mesh.getBoundingInfo();
  8740. if (!boundingInfo) {
  8741. continue;
  8742. }
  8743. var boundingBox = boundingInfo.boundingBox;
  8744. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8745. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8746. if (tempVector3.x < orthoLeft)
  8747. orthoLeft = tempVector3.x;
  8748. if (tempVector3.y < orthoBottom)
  8749. orthoBottom = tempVector3.y;
  8750. if (tempVector3.x > orthoRight)
  8751. orthoRight = tempVector3.x;
  8752. if (tempVector3.y > orthoTop)
  8753. orthoTop = tempVector3.y;
  8754. }
  8755. }
  8756. var xOffset = orthoRight - orthoLeft;
  8757. var yOffset = orthoTop - orthoBottom;
  8758. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8759. };
  8760. DirectionalLight.prototype.supportsVSM = function () {
  8761. return true;
  8762. };
  8763. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8764. return true;
  8765. };
  8766. DirectionalLight.prototype.computeTransformedPosition = function () {
  8767. if (this.parent && this.parent.getWorldMatrix) {
  8768. if (!this.transformedPosition) {
  8769. this.transformedPosition = BABYLON.Vector3.Zero();
  8770. }
  8771. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8772. return true;
  8773. }
  8774. return false;
  8775. };
  8776. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8777. if (this.parent && this.parent.getWorldMatrix) {
  8778. if (!this._transformedDirection) {
  8779. this._transformedDirection = BABYLON.Vector3.Zero();
  8780. }
  8781. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8782. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8783. return;
  8784. }
  8785. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8786. };
  8787. DirectionalLight.prototype._getWorldMatrix = function () {
  8788. if (!this._worldMatrix) {
  8789. this._worldMatrix = BABYLON.Matrix.Identity();
  8790. }
  8791. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8792. return this._worldMatrix;
  8793. };
  8794. return DirectionalLight;
  8795. })(BABYLON.Light);
  8796. BABYLON.DirectionalLight = DirectionalLight;
  8797. })(BABYLON || (BABYLON = {}));
  8798. var BABYLON;
  8799. (function (BABYLON) {
  8800. var ShadowGenerator = (function () {
  8801. function ShadowGenerator(mapSize, light) {
  8802. var _this = this;
  8803. // Members
  8804. this._filter = ShadowGenerator.FILTER_NONE;
  8805. this.blurScale = 2;
  8806. this._blurBoxOffset = 0;
  8807. this._bias = 0.00005;
  8808. this._lightDirection = BABYLON.Vector3.Zero();
  8809. this._darkness = 0;
  8810. this._transparencyShadow = false;
  8811. this._viewMatrix = BABYLON.Matrix.Zero();
  8812. this._projectionMatrix = BABYLON.Matrix.Zero();
  8813. this._transformMatrix = BABYLON.Matrix.Zero();
  8814. this._worldViewProjection = BABYLON.Matrix.Zero();
  8815. this._light = light;
  8816. this._scene = light.getScene();
  8817. this._mapSize = mapSize;
  8818. light._shadowGenerator = this;
  8819. // Render target
  8820. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8821. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8822. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8823. this._shadowMap.anisotropicFilteringLevel = 1;
  8824. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8825. this._shadowMap.renderParticles = false;
  8826. this._shadowMap.onAfterUnbind = function () {
  8827. if (!_this.useBlurVarianceShadowMap) {
  8828. return;
  8829. }
  8830. if (!_this._shadowMap2) {
  8831. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8832. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8833. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8834. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8835. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8836. _this._downSamplePostprocess.onApply = function (effect) {
  8837. effect.setTexture("textureSampler", _this._shadowMap);
  8838. };
  8839. _this.blurBoxOffset = 1;
  8840. }
  8841. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8842. };
  8843. // Custom render function
  8844. var renderSubMesh = function (subMesh) {
  8845. var mesh = subMesh.getRenderingMesh();
  8846. var scene = _this._scene;
  8847. var engine = scene.getEngine();
  8848. // Culling
  8849. engine.setState(subMesh.getMaterial().backFaceCulling);
  8850. // Managing instances
  8851. var batch = mesh._getInstancesRenderList(subMesh._id);
  8852. if (batch.mustReturn) {
  8853. return;
  8854. }
  8855. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8856. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8857. engine.enableEffect(_this._effect);
  8858. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8859. var material = subMesh.getMaterial();
  8860. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8861. // Alpha test
  8862. if (material && material.needAlphaTesting()) {
  8863. var alphaTexture = material.getAlphaTestTexture();
  8864. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8865. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8866. }
  8867. // Bones
  8868. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8869. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8870. }
  8871. // Draw
  8872. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8873. }
  8874. else {
  8875. // Need to reset refresh rate of the shadowMap
  8876. _this._shadowMap.resetRefreshCounter();
  8877. }
  8878. };
  8879. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8880. var index;
  8881. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8882. renderSubMesh(opaqueSubMeshes.data[index]);
  8883. }
  8884. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8885. renderSubMesh(alphaTestSubMeshes.data[index]);
  8886. }
  8887. if (_this._transparencyShadow) {
  8888. for (index = 0; index < transparentSubMeshes.length; index++) {
  8889. renderSubMesh(transparentSubMeshes.data[index]);
  8890. }
  8891. }
  8892. };
  8893. this._shadowMap.onClear = function (engine) {
  8894. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8895. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8896. }
  8897. else {
  8898. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8899. }
  8900. };
  8901. }
  8902. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8903. // Static
  8904. get: function () {
  8905. return ShadowGenerator._FILTER_NONE;
  8906. },
  8907. enumerable: true,
  8908. configurable: true
  8909. });
  8910. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8911. get: function () {
  8912. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8913. },
  8914. enumerable: true,
  8915. configurable: true
  8916. });
  8917. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8918. get: function () {
  8919. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8920. },
  8921. enumerable: true,
  8922. configurable: true
  8923. });
  8924. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8925. get: function () {
  8926. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8927. },
  8928. enumerable: true,
  8929. configurable: true
  8930. });
  8931. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8932. get: function () {
  8933. return this._bias;
  8934. },
  8935. set: function (bias) {
  8936. this._bias = bias;
  8937. },
  8938. enumerable: true,
  8939. configurable: true
  8940. });
  8941. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8942. get: function () {
  8943. return this._blurBoxOffset;
  8944. },
  8945. set: function (value) {
  8946. var _this = this;
  8947. if (this._blurBoxOffset === value) {
  8948. return;
  8949. }
  8950. this._blurBoxOffset = value;
  8951. if (this._boxBlurPostprocess) {
  8952. this._boxBlurPostprocess.dispose();
  8953. }
  8954. 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);
  8955. this._boxBlurPostprocess.onApply = function (effect) {
  8956. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8957. };
  8958. },
  8959. enumerable: true,
  8960. configurable: true
  8961. });
  8962. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8963. get: function () {
  8964. return this._filter;
  8965. },
  8966. set: function (value) {
  8967. if (this._filter === value) {
  8968. return;
  8969. }
  8970. this._filter = value;
  8971. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8972. this._shadowMap.anisotropicFilteringLevel = 16;
  8973. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8974. }
  8975. else {
  8976. this._shadowMap.anisotropicFilteringLevel = 1;
  8977. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8978. }
  8979. },
  8980. enumerable: true,
  8981. configurable: true
  8982. });
  8983. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8984. get: function () {
  8985. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8986. },
  8987. set: function (value) {
  8988. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8989. },
  8990. enumerable: true,
  8991. configurable: true
  8992. });
  8993. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8994. get: function () {
  8995. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8996. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8997. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8998. },
  8999. set: function (value) {
  9000. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9001. },
  9002. enumerable: true,
  9003. configurable: true
  9004. });
  9005. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9006. get: function () {
  9007. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9008. },
  9009. set: function (value) {
  9010. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9011. },
  9012. enumerable: true,
  9013. configurable: true
  9014. });
  9015. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9016. var defines = [];
  9017. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9018. defines.push("#define VSM");
  9019. }
  9020. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9021. var mesh = subMesh.getMesh();
  9022. var material = subMesh.getMaterial();
  9023. // Alpha test
  9024. if (material && material.needAlphaTesting()) {
  9025. defines.push("#define ALPHATEST");
  9026. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9027. attribs.push(BABYLON.VertexBuffer.UVKind);
  9028. defines.push("#define UV1");
  9029. }
  9030. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9031. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9032. defines.push("#define UV2");
  9033. }
  9034. }
  9035. // Bones
  9036. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9037. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9038. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9039. defines.push("#define BONES");
  9040. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9041. }
  9042. // Instances
  9043. if (useInstances) {
  9044. defines.push("#define INSTANCES");
  9045. attribs.push("world0");
  9046. attribs.push("world1");
  9047. attribs.push("world2");
  9048. attribs.push("world3");
  9049. }
  9050. // Get correct effect
  9051. var join = defines.join("\n");
  9052. if (this._cachedDefines !== join) {
  9053. this._cachedDefines = join;
  9054. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9055. }
  9056. return this._effect.isReady();
  9057. };
  9058. ShadowGenerator.prototype.getShadowMap = function () {
  9059. return this._shadowMap;
  9060. };
  9061. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9062. if (this._shadowMap2) {
  9063. return this._shadowMap2;
  9064. }
  9065. return this._shadowMap;
  9066. };
  9067. ShadowGenerator.prototype.getLight = function () {
  9068. return this._light;
  9069. };
  9070. // Methods
  9071. ShadowGenerator.prototype.getTransformMatrix = function () {
  9072. var scene = this._scene;
  9073. if (this._currentRenderID === scene.getRenderId()) {
  9074. return this._transformMatrix;
  9075. }
  9076. this._currentRenderID = scene.getRenderId();
  9077. var lightPosition = this._light.position;
  9078. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9079. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9080. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9081. }
  9082. if (this._light.computeTransformedPosition()) {
  9083. lightPosition = this._light.transformedPosition;
  9084. }
  9085. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9086. this._cachedPosition = lightPosition.clone();
  9087. this._cachedDirection = this._lightDirection.clone();
  9088. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9089. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9090. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9091. }
  9092. return this._transformMatrix;
  9093. };
  9094. ShadowGenerator.prototype.getDarkness = function () {
  9095. return this._darkness;
  9096. };
  9097. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9098. if (darkness >= 1.0)
  9099. this._darkness = 1.0;
  9100. else if (darkness <= 0.0)
  9101. this._darkness = 0.0;
  9102. else
  9103. this._darkness = darkness;
  9104. };
  9105. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9106. this._transparencyShadow = hasShadow;
  9107. };
  9108. ShadowGenerator.prototype._packHalf = function (depth) {
  9109. var scale = depth * 255.0;
  9110. var fract = scale - Math.floor(scale);
  9111. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9112. };
  9113. ShadowGenerator.prototype.dispose = function () {
  9114. this._shadowMap.dispose();
  9115. if (this._shadowMap2) {
  9116. this._shadowMap2.dispose();
  9117. }
  9118. if (this._downSamplePostprocess) {
  9119. this._downSamplePostprocess.dispose();
  9120. }
  9121. if (this._boxBlurPostprocess) {
  9122. this._boxBlurPostprocess.dispose();
  9123. }
  9124. };
  9125. ShadowGenerator._FILTER_NONE = 0;
  9126. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9127. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9128. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9129. return ShadowGenerator;
  9130. })();
  9131. BABYLON.ShadowGenerator = ShadowGenerator;
  9132. })(BABYLON || (BABYLON = {}));
  9133. var BABYLON;
  9134. (function (BABYLON) {
  9135. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9136. if (boxMin.x > sphereCenter.x + sphereRadius)
  9137. return false;
  9138. if (sphereCenter.x - sphereRadius > boxMax.x)
  9139. return false;
  9140. if (boxMin.y > sphereCenter.y + sphereRadius)
  9141. return false;
  9142. if (sphereCenter.y - sphereRadius > boxMax.y)
  9143. return false;
  9144. if (boxMin.z > sphereCenter.z + sphereRadius)
  9145. return false;
  9146. if (sphereCenter.z - sphereRadius > boxMax.z)
  9147. return false;
  9148. return true;
  9149. };
  9150. var getLowestRoot = function (a, b, c, maxR) {
  9151. var determinant = b * b - 4.0 * a * c;
  9152. var result = { root: 0, found: false };
  9153. if (determinant < 0)
  9154. return result;
  9155. var sqrtD = Math.sqrt(determinant);
  9156. var r1 = (-b - sqrtD) / (2.0 * a);
  9157. var r2 = (-b + sqrtD) / (2.0 * a);
  9158. if (r1 > r2) {
  9159. var temp = r2;
  9160. r2 = r1;
  9161. r1 = temp;
  9162. }
  9163. if (r1 > 0 && r1 < maxR) {
  9164. result.root = r1;
  9165. result.found = true;
  9166. return result;
  9167. }
  9168. if (r2 > 0 && r2 < maxR) {
  9169. result.root = r2;
  9170. result.found = true;
  9171. return result;
  9172. }
  9173. return result;
  9174. };
  9175. var Collider = (function () {
  9176. function Collider() {
  9177. this.radius = new BABYLON.Vector3(1, 1, 1);
  9178. this.retry = 0;
  9179. this.basePointWorld = BABYLON.Vector3.Zero();
  9180. this.velocityWorld = BABYLON.Vector3.Zero();
  9181. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9182. this._collisionPoint = BABYLON.Vector3.Zero();
  9183. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9184. this._tempVector = BABYLON.Vector3.Zero();
  9185. this._tempVector2 = BABYLON.Vector3.Zero();
  9186. this._tempVector3 = BABYLON.Vector3.Zero();
  9187. this._tempVector4 = BABYLON.Vector3.Zero();
  9188. this._edge = BABYLON.Vector3.Zero();
  9189. this._baseToVertex = BABYLON.Vector3.Zero();
  9190. this._destinationPoint = BABYLON.Vector3.Zero();
  9191. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9192. this._displacementVector = BABYLON.Vector3.Zero();
  9193. }
  9194. // Methods
  9195. Collider.prototype._initialize = function (source, dir, e) {
  9196. this.velocity = dir;
  9197. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9198. this.basePoint = source;
  9199. source.multiplyToRef(this.radius, this.basePointWorld);
  9200. dir.multiplyToRef(this.radius, this.velocityWorld);
  9201. this.velocityWorldLength = this.velocityWorld.length();
  9202. this.epsilon = e;
  9203. this.collisionFound = false;
  9204. };
  9205. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9206. pa.subtractToRef(point, this._tempVector);
  9207. pb.subtractToRef(point, this._tempVector2);
  9208. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9209. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9210. if (d < 0)
  9211. return false;
  9212. pc.subtractToRef(point, this._tempVector3);
  9213. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9214. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9215. if (d < 0)
  9216. return false;
  9217. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9218. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9219. return d >= 0;
  9220. };
  9221. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9222. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9223. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9224. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9225. return false;
  9226. }
  9227. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9228. return false;
  9229. return true;
  9230. };
  9231. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9232. var t0;
  9233. var embeddedInPlane = false;
  9234. //defensive programming, actually not needed.
  9235. if (!trianglePlaneArray) {
  9236. trianglePlaneArray = [];
  9237. }
  9238. if (!trianglePlaneArray[faceIndex]) {
  9239. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9240. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9241. }
  9242. var trianglePlane = trianglePlaneArray[faceIndex];
  9243. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9244. return;
  9245. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9246. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9247. if (normalDotVelocity == 0) {
  9248. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9249. return;
  9250. embeddedInPlane = true;
  9251. t0 = 0;
  9252. }
  9253. else {
  9254. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9255. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9256. if (t0 > t1) {
  9257. var temp = t1;
  9258. t1 = t0;
  9259. t0 = temp;
  9260. }
  9261. if (t0 > 1.0 || t1 < 0.0)
  9262. return;
  9263. if (t0 < 0)
  9264. t0 = 0;
  9265. if (t0 > 1.0)
  9266. t0 = 1.0;
  9267. }
  9268. this._collisionPoint.copyFromFloats(0, 0, 0);
  9269. var found = false;
  9270. var t = 1.0;
  9271. if (!embeddedInPlane) {
  9272. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9273. this.velocity.scaleToRef(t0, this._tempVector);
  9274. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9275. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9276. found = true;
  9277. t = t0;
  9278. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9279. }
  9280. }
  9281. if (!found) {
  9282. var velocitySquaredLength = this.velocity.lengthSquared();
  9283. var a = velocitySquaredLength;
  9284. this.basePoint.subtractToRef(p1, this._tempVector);
  9285. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9286. var c = this._tempVector.lengthSquared() - 1.0;
  9287. var lowestRoot = getLowestRoot(a, b, c, t);
  9288. if (lowestRoot.found) {
  9289. t = lowestRoot.root;
  9290. found = true;
  9291. this._collisionPoint.copyFrom(p1);
  9292. }
  9293. this.basePoint.subtractToRef(p2, this._tempVector);
  9294. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9295. c = this._tempVector.lengthSquared() - 1.0;
  9296. lowestRoot = getLowestRoot(a, b, c, t);
  9297. if (lowestRoot.found) {
  9298. t = lowestRoot.root;
  9299. found = true;
  9300. this._collisionPoint.copyFrom(p2);
  9301. }
  9302. this.basePoint.subtractToRef(p3, this._tempVector);
  9303. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9304. c = this._tempVector.lengthSquared() - 1.0;
  9305. lowestRoot = getLowestRoot(a, b, c, t);
  9306. if (lowestRoot.found) {
  9307. t = lowestRoot.root;
  9308. found = true;
  9309. this._collisionPoint.copyFrom(p3);
  9310. }
  9311. p2.subtractToRef(p1, this._edge);
  9312. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9313. var edgeSquaredLength = this._edge.lengthSquared();
  9314. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9315. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9316. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9317. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9318. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9319. lowestRoot = getLowestRoot(a, b, c, t);
  9320. if (lowestRoot.found) {
  9321. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9322. if (f >= 0.0 && f <= 1.0) {
  9323. t = lowestRoot.root;
  9324. found = true;
  9325. this._edge.scaleInPlace(f);
  9326. p1.addToRef(this._edge, this._collisionPoint);
  9327. }
  9328. }
  9329. p3.subtractToRef(p2, this._edge);
  9330. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9331. edgeSquaredLength = this._edge.lengthSquared();
  9332. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9333. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9334. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9335. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9336. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9337. lowestRoot = getLowestRoot(a, b, c, t);
  9338. if (lowestRoot.found) {
  9339. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9340. if (f >= 0.0 && f <= 1.0) {
  9341. t = lowestRoot.root;
  9342. found = true;
  9343. this._edge.scaleInPlace(f);
  9344. p2.addToRef(this._edge, this._collisionPoint);
  9345. }
  9346. }
  9347. p1.subtractToRef(p3, this._edge);
  9348. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9349. edgeSquaredLength = this._edge.lengthSquared();
  9350. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9351. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9352. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9353. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9354. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9355. lowestRoot = getLowestRoot(a, b, c, t);
  9356. if (lowestRoot.found) {
  9357. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9358. if (f >= 0.0 && f <= 1.0) {
  9359. t = lowestRoot.root;
  9360. found = true;
  9361. this._edge.scaleInPlace(f);
  9362. p3.addToRef(this._edge, this._collisionPoint);
  9363. }
  9364. }
  9365. }
  9366. if (found) {
  9367. var distToCollision = t * this.velocity.length();
  9368. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9369. if (!this.intersectionPoint) {
  9370. this.intersectionPoint = this._collisionPoint.clone();
  9371. }
  9372. else {
  9373. this.intersectionPoint.copyFrom(this._collisionPoint);
  9374. }
  9375. this.nearestDistance = distToCollision;
  9376. this.collisionFound = true;
  9377. }
  9378. }
  9379. };
  9380. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9381. for (var i = indexStart; i < indexEnd; i += 3) {
  9382. var p1 = pts[indices[i] - decal];
  9383. var p2 = pts[indices[i + 1] - decal];
  9384. var p3 = pts[indices[i + 2] - decal];
  9385. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9386. }
  9387. };
  9388. Collider.prototype._getResponse = function (pos, vel) {
  9389. pos.addToRef(vel, this._destinationPoint);
  9390. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9391. this.basePoint.addToRef(vel, pos);
  9392. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9393. this._slidePlaneNormal.normalize();
  9394. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9395. pos.addInPlace(this._displacementVector);
  9396. this.intersectionPoint.addInPlace(this._displacementVector);
  9397. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9398. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9399. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9400. };
  9401. return Collider;
  9402. })();
  9403. BABYLON.Collider = Collider;
  9404. })(BABYLON || (BABYLON = {}));
  9405. var BABYLON;
  9406. (function (BABYLON) {
  9407. //WebWorker code will be inserted to this variable.
  9408. BABYLON.CollisionWorker = "";
  9409. (function (WorkerTaskType) {
  9410. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9411. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9412. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9413. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9414. var WorkerTaskType = BABYLON.WorkerTaskType;
  9415. (function (WorkerReplyType) {
  9416. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9417. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9418. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9419. var WorkerReplyType = BABYLON.WorkerReplyType;
  9420. var CollisionCoordinatorWorker = (function () {
  9421. function CollisionCoordinatorWorker() {
  9422. var _this = this;
  9423. this._scaledPosition = BABYLON.Vector3.Zero();
  9424. this._scaledVelocity = BABYLON.Vector3.Zero();
  9425. this.onMeshUpdated = function (mesh) {
  9426. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9427. };
  9428. this.onGeometryUpdated = function (geometry) {
  9429. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9430. };
  9431. this._afterRender = function () {
  9432. if (!_this._init)
  9433. return;
  9434. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9435. return;
  9436. }
  9437. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9438. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9439. if (_this._runningUpdated > 4) {
  9440. return;
  9441. }
  9442. ++_this._runningUpdated;
  9443. var payload = {
  9444. updatedMeshes: _this._addUpdateMeshesList,
  9445. updatedGeometries: _this._addUpdateGeometriesList,
  9446. removedGeometries: _this._toRemoveGeometryArray,
  9447. removedMeshes: _this._toRemoveMeshesArray
  9448. };
  9449. var message = {
  9450. payload: payload,
  9451. taskType: WorkerTaskType.UPDATE
  9452. };
  9453. var serializable = [];
  9454. for (var id in payload.updatedGeometries) {
  9455. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9456. //prepare transferables
  9457. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9458. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9459. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9460. }
  9461. }
  9462. _this._worker.postMessage(message, serializable);
  9463. _this._addUpdateMeshesList = {};
  9464. _this._addUpdateGeometriesList = {};
  9465. _this._toRemoveGeometryArray = [];
  9466. _this._toRemoveMeshesArray = [];
  9467. };
  9468. this._onMessageFromWorker = function (e) {
  9469. var returnData = e.data;
  9470. if (returnData.error != WorkerReplyType.SUCCESS) {
  9471. //TODO what errors can be returned from the worker?
  9472. BABYLON.Tools.Warn("error returned from worker!");
  9473. return;
  9474. }
  9475. switch (returnData.taskType) {
  9476. case WorkerTaskType.INIT:
  9477. _this._init = true;
  9478. //Update the worked with ALL of the scene's current state
  9479. _this._scene.meshes.forEach(function (mesh) {
  9480. _this.onMeshAdded(mesh);
  9481. });
  9482. _this._scene.getGeometries().forEach(function (geometry) {
  9483. _this.onGeometryAdded(geometry);
  9484. });
  9485. break;
  9486. case WorkerTaskType.UPDATE:
  9487. _this._runningUpdated--;
  9488. break;
  9489. case WorkerTaskType.COLLIDE:
  9490. _this._runningCollisionTask = false;
  9491. var returnPayload = returnData.payload;
  9492. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9493. return;
  9494. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9495. //cleanup
  9496. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9497. break;
  9498. }
  9499. };
  9500. this._collisionsCallbackArray = [];
  9501. this._init = false;
  9502. this._runningUpdated = 0;
  9503. this._runningCollisionTask = false;
  9504. this._addUpdateMeshesList = {};
  9505. this._addUpdateGeometriesList = {};
  9506. this._toRemoveGeometryArray = [];
  9507. this._toRemoveMeshesArray = [];
  9508. }
  9509. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9510. if (!this._init)
  9511. return;
  9512. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9513. return;
  9514. position.divideToRef(collider.radius, this._scaledPosition);
  9515. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9516. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9517. var payload = {
  9518. collider: {
  9519. position: this._scaledPosition.asArray(),
  9520. velocity: this._scaledVelocity.asArray(),
  9521. radius: collider.radius.asArray()
  9522. },
  9523. collisionId: collisionIndex,
  9524. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9525. maximumRetry: maximumRetry
  9526. };
  9527. var message = {
  9528. payload: payload,
  9529. taskType: WorkerTaskType.COLLIDE
  9530. };
  9531. this._worker.postMessage(message);
  9532. };
  9533. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9534. this._scene = scene;
  9535. this._scene.registerAfterRender(this._afterRender);
  9536. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9537. this._worker = new Worker(workerUrl);
  9538. this._worker.onmessage = this._onMessageFromWorker;
  9539. var message = {
  9540. payload: {},
  9541. taskType: WorkerTaskType.INIT
  9542. };
  9543. this._worker.postMessage(message);
  9544. };
  9545. CollisionCoordinatorWorker.prototype.destroy = function () {
  9546. this._scene.unregisterAfterRender(this._afterRender);
  9547. this._worker.terminate();
  9548. };
  9549. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9550. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9551. this.onMeshUpdated(mesh);
  9552. };
  9553. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9554. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9555. };
  9556. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9557. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9558. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9559. this.onGeometryUpdated(geometry);
  9560. };
  9561. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9562. this._toRemoveGeometryArray.push(geometry.id);
  9563. };
  9564. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9565. var submeshes = [];
  9566. if (mesh.subMeshes) {
  9567. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9568. return {
  9569. position: idx,
  9570. verticesStart: sm.verticesStart,
  9571. verticesCount: sm.verticesCount,
  9572. indexStart: sm.indexStart,
  9573. indexCount: sm.indexCount,
  9574. hasMaterial: !!sm.getMaterial(),
  9575. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9576. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9577. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9578. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9579. };
  9580. });
  9581. }
  9582. var geometryId = null;
  9583. if (mesh instanceof BABYLON.Mesh) {
  9584. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9585. }
  9586. else if (mesh instanceof BABYLON.InstancedMesh) {
  9587. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9588. }
  9589. return {
  9590. uniqueId: mesh.uniqueId,
  9591. id: mesh.id,
  9592. name: mesh.name,
  9593. geometryId: geometryId,
  9594. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9595. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9596. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9597. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9598. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9599. subMeshes: submeshes,
  9600. checkCollisions: mesh.checkCollisions
  9601. };
  9602. };
  9603. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9604. return {
  9605. id: geometry.id,
  9606. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9607. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9608. indices: new Int32Array(geometry.getIndices() || []),
  9609. };
  9610. };
  9611. return CollisionCoordinatorWorker;
  9612. })();
  9613. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9614. var CollisionCoordinatorLegacy = (function () {
  9615. function CollisionCoordinatorLegacy() {
  9616. this._scaledPosition = BABYLON.Vector3.Zero();
  9617. this._scaledVelocity = BABYLON.Vector3.Zero();
  9618. this._finalPosition = BABYLON.Vector3.Zero();
  9619. }
  9620. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9621. position.divideToRef(collider.radius, this._scaledPosition);
  9622. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9623. collider.collidedMesh = null;
  9624. collider.retry = 0;
  9625. collider.initialVelocity = this._scaledVelocity;
  9626. collider.initialPosition = this._scaledPosition;
  9627. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9628. this._finalPosition.multiplyInPlace(collider.radius);
  9629. //run the callback
  9630. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9631. };
  9632. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9633. this._scene = scene;
  9634. };
  9635. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9636. //Legacy need no destruction method.
  9637. };
  9638. //No update in legacy mode
  9639. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9640. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9641. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9642. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9643. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9644. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9645. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9646. if (excludedMesh === void 0) { excludedMesh = null; }
  9647. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9648. if (collider.retry >= maximumRetry) {
  9649. finalPosition.copyFrom(position);
  9650. return;
  9651. }
  9652. collider._initialize(position, velocity, closeDistance);
  9653. // Check all meshes
  9654. for (var index = 0; index < this._scene.meshes.length; index++) {
  9655. var mesh = this._scene.meshes[index];
  9656. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9657. mesh._checkCollision(collider);
  9658. }
  9659. }
  9660. if (!collider.collisionFound) {
  9661. position.addToRef(velocity, finalPosition);
  9662. return;
  9663. }
  9664. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9665. collider._getResponse(position, velocity);
  9666. }
  9667. if (velocity.length() <= closeDistance) {
  9668. finalPosition.copyFrom(position);
  9669. return;
  9670. }
  9671. collider.retry++;
  9672. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9673. };
  9674. return CollisionCoordinatorLegacy;
  9675. })();
  9676. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9677. })(BABYLON || (BABYLON = {}));
  9678. var BABYLON;
  9679. (function (BABYLON) {
  9680. var VRCameraMetrics = (function () {
  9681. function VRCameraMetrics() {
  9682. this.compensateDistortion = true;
  9683. }
  9684. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9685. get: function () {
  9686. return this.hResolution / (2 * this.vResolution);
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9692. get: function () {
  9693. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9694. },
  9695. enumerable: true,
  9696. configurable: true
  9697. });
  9698. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9699. get: function () {
  9700. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9701. var h = (4 * meters) / this.hScreenSize;
  9702. return BABYLON.Matrix.Translation(h, 0, 0);
  9703. },
  9704. enumerable: true,
  9705. configurable: true
  9706. });
  9707. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9708. get: function () {
  9709. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9710. var h = (4 * meters) / this.hScreenSize;
  9711. return BABYLON.Matrix.Translation(-h, 0, 0);
  9712. },
  9713. enumerable: true,
  9714. configurable: true
  9715. });
  9716. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9717. get: function () {
  9718. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9719. },
  9720. enumerable: true,
  9721. configurable: true
  9722. });
  9723. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9724. get: function () {
  9725. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9726. },
  9727. enumerable: true,
  9728. configurable: true
  9729. });
  9730. VRCameraMetrics.GetDefault = function () {
  9731. var result = new VRCameraMetrics();
  9732. result.hResolution = 1280;
  9733. result.vResolution = 800;
  9734. result.hScreenSize = 0.149759993;
  9735. result.vScreenSize = 0.0935999975;
  9736. result.vScreenCenter = 0.0467999987,
  9737. result.eyeToScreenDistance = 0.0410000011;
  9738. result.lensSeparationDistance = 0.0635000020;
  9739. result.interpupillaryDistance = 0.0640000030;
  9740. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9741. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9742. result.postProcessScaleFactor = 1.714605507808412;
  9743. result.lensCenterOffset = 0.151976421;
  9744. return result;
  9745. };
  9746. return VRCameraMetrics;
  9747. })();
  9748. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9749. var Camera = (function (_super) {
  9750. __extends(Camera, _super);
  9751. function Camera(name, position, scene) {
  9752. _super.call(this, name, scene);
  9753. this.position = position;
  9754. // Members
  9755. this.upVector = BABYLON.Vector3.Up();
  9756. this.orthoLeft = null;
  9757. this.orthoRight = null;
  9758. this.orthoBottom = null;
  9759. this.orthoTop = null;
  9760. this.fov = 0.8;
  9761. this.minZ = 1.0;
  9762. this.maxZ = 10000.0;
  9763. this.inertia = 0.9;
  9764. this.mode = Camera.PERSPECTIVE_CAMERA;
  9765. this.isIntermediate = false;
  9766. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9767. this.layerMask = 0x0FFFFFFF;
  9768. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9769. // Camera rig members
  9770. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9771. this._rigCameras = new Array();
  9772. // Cache
  9773. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9774. this._projectionMatrix = new BABYLON.Matrix();
  9775. this._postProcesses = new Array();
  9776. this._postProcessesTakenIndices = [];
  9777. this._activeMeshes = new BABYLON.SmartArray(256);
  9778. this._globalPosition = BABYLON.Vector3.Zero();
  9779. scene.addCamera(this);
  9780. if (!scene.activeCamera) {
  9781. scene.activeCamera = this;
  9782. }
  9783. }
  9784. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9785. get: function () {
  9786. return Camera._PERSPECTIVE_CAMERA;
  9787. },
  9788. enumerable: true,
  9789. configurable: true
  9790. });
  9791. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9792. get: function () {
  9793. return Camera._ORTHOGRAPHIC_CAMERA;
  9794. },
  9795. enumerable: true,
  9796. configurable: true
  9797. });
  9798. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9799. get: function () {
  9800. return Camera._FOVMODE_VERTICAL_FIXED;
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9806. get: function () {
  9807. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9813. get: function () {
  9814. return Camera._RIG_MODE_NONE;
  9815. },
  9816. enumerable: true,
  9817. configurable: true
  9818. });
  9819. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9820. get: function () {
  9821. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9822. },
  9823. enumerable: true,
  9824. configurable: true
  9825. });
  9826. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9827. get: function () {
  9828. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9829. },
  9830. enumerable: true,
  9831. configurable: true
  9832. });
  9833. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9834. get: function () {
  9835. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9836. },
  9837. enumerable: true,
  9838. configurable: true
  9839. });
  9840. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9841. get: function () {
  9842. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9843. },
  9844. enumerable: true,
  9845. configurable: true
  9846. });
  9847. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9848. get: function () {
  9849. return Camera._RIG_MODE_VR;
  9850. },
  9851. enumerable: true,
  9852. configurable: true
  9853. });
  9854. Object.defineProperty(Camera.prototype, "globalPosition", {
  9855. get: function () {
  9856. return this._globalPosition;
  9857. },
  9858. enumerable: true,
  9859. configurable: true
  9860. });
  9861. Camera.prototype.getActiveMeshes = function () {
  9862. return this._activeMeshes;
  9863. };
  9864. Camera.prototype.isActiveMesh = function (mesh) {
  9865. return (this._activeMeshes.indexOf(mesh) !== -1);
  9866. };
  9867. //Cache
  9868. Camera.prototype._initCache = function () {
  9869. _super.prototype._initCache.call(this);
  9870. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9871. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9872. this._cache.mode = undefined;
  9873. this._cache.minZ = undefined;
  9874. this._cache.maxZ = undefined;
  9875. this._cache.fov = undefined;
  9876. this._cache.aspectRatio = undefined;
  9877. this._cache.orthoLeft = undefined;
  9878. this._cache.orthoRight = undefined;
  9879. this._cache.orthoBottom = undefined;
  9880. this._cache.orthoTop = undefined;
  9881. this._cache.renderWidth = undefined;
  9882. this._cache.renderHeight = undefined;
  9883. };
  9884. Camera.prototype._updateCache = function (ignoreParentClass) {
  9885. if (!ignoreParentClass) {
  9886. _super.prototype._updateCache.call(this);
  9887. }
  9888. var engine = this.getEngine();
  9889. this._cache.position.copyFrom(this.position);
  9890. this._cache.upVector.copyFrom(this.upVector);
  9891. this._cache.mode = this.mode;
  9892. this._cache.minZ = this.minZ;
  9893. this._cache.maxZ = this.maxZ;
  9894. this._cache.fov = this.fov;
  9895. this._cache.aspectRatio = engine.getAspectRatio(this);
  9896. this._cache.orthoLeft = this.orthoLeft;
  9897. this._cache.orthoRight = this.orthoRight;
  9898. this._cache.orthoBottom = this.orthoBottom;
  9899. this._cache.orthoTop = this.orthoTop;
  9900. this._cache.renderWidth = engine.getRenderWidth();
  9901. this._cache.renderHeight = engine.getRenderHeight();
  9902. };
  9903. Camera.prototype._updateFromScene = function () {
  9904. this.updateCache();
  9905. this._update();
  9906. };
  9907. // Synchronized
  9908. Camera.prototype._isSynchronized = function () {
  9909. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9910. };
  9911. Camera.prototype._isSynchronizedViewMatrix = function () {
  9912. if (!_super.prototype._isSynchronized.call(this))
  9913. return false;
  9914. return this._cache.position.equals(this.position)
  9915. && this._cache.upVector.equals(this.upVector)
  9916. && this.isSynchronizedWithParent();
  9917. };
  9918. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9919. var check = this._cache.mode === this.mode
  9920. && this._cache.minZ === this.minZ
  9921. && this._cache.maxZ === this.maxZ;
  9922. if (!check) {
  9923. return false;
  9924. }
  9925. var engine = this.getEngine();
  9926. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9927. check = this._cache.fov === this.fov
  9928. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9929. }
  9930. else {
  9931. check = this._cache.orthoLeft === this.orthoLeft
  9932. && this._cache.orthoRight === this.orthoRight
  9933. && this._cache.orthoBottom === this.orthoBottom
  9934. && this._cache.orthoTop === this.orthoTop
  9935. && this._cache.renderWidth === engine.getRenderWidth()
  9936. && this._cache.renderHeight === engine.getRenderHeight();
  9937. }
  9938. return check;
  9939. };
  9940. // Controls
  9941. Camera.prototype.attachControl = function (element) {
  9942. };
  9943. Camera.prototype.detachControl = function (element) {
  9944. };
  9945. Camera.prototype._update = function () {
  9946. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9947. this._updateRigCameras();
  9948. }
  9949. this._checkInputs();
  9950. };
  9951. Camera.prototype._checkInputs = function () {
  9952. };
  9953. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9954. if (insertAt === void 0) { insertAt = null; }
  9955. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9956. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9957. return 0;
  9958. }
  9959. if (insertAt == null || insertAt < 0) {
  9960. this._postProcesses.push(postProcess);
  9961. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9962. return this._postProcesses.length - 1;
  9963. }
  9964. var add = 0;
  9965. var i;
  9966. var start;
  9967. if (this._postProcesses[insertAt]) {
  9968. start = this._postProcesses.length - 1;
  9969. for (i = start; i >= insertAt + 1; --i) {
  9970. this._postProcesses[i + 1] = this._postProcesses[i];
  9971. }
  9972. add = 1;
  9973. }
  9974. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9975. if (this._postProcessesTakenIndices[i] < insertAt) {
  9976. continue;
  9977. }
  9978. start = this._postProcessesTakenIndices.length - 1;
  9979. for (var j = start; j >= i; --j) {
  9980. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9981. }
  9982. this._postProcessesTakenIndices[i] = insertAt;
  9983. break;
  9984. }
  9985. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  9986. this._postProcessesTakenIndices.push(insertAt);
  9987. }
  9988. var result = insertAt + add;
  9989. this._postProcesses[result] = postProcess;
  9990. return result;
  9991. };
  9992. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9993. if (atIndices === void 0) { atIndices = null; }
  9994. var result = [];
  9995. var i;
  9996. var index;
  9997. if (!atIndices) {
  9998. var length = this._postProcesses.length;
  9999. for (i = 0; i < length; i++) {
  10000. if (this._postProcesses[i] !== postProcess) {
  10001. continue;
  10002. }
  10003. delete this._postProcesses[i];
  10004. index = this._postProcessesTakenIndices.indexOf(i);
  10005. this._postProcessesTakenIndices.splice(index, 1);
  10006. }
  10007. }
  10008. else {
  10009. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10010. for (i = 0; i < atIndices.length; i++) {
  10011. var foundPostProcess = this._postProcesses[atIndices[i]];
  10012. if (foundPostProcess !== postProcess) {
  10013. result.push(i);
  10014. continue;
  10015. }
  10016. delete this._postProcesses[atIndices[i]];
  10017. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10018. this._postProcessesTakenIndices.splice(index, 1);
  10019. }
  10020. }
  10021. return result;
  10022. };
  10023. Camera.prototype.getWorldMatrix = function () {
  10024. if (!this._worldMatrix) {
  10025. this._worldMatrix = BABYLON.Matrix.Identity();
  10026. }
  10027. var viewMatrix = this.getViewMatrix();
  10028. viewMatrix.invertToRef(this._worldMatrix);
  10029. return this._worldMatrix;
  10030. };
  10031. Camera.prototype._getViewMatrix = function () {
  10032. return BABYLON.Matrix.Identity();
  10033. };
  10034. Camera.prototype.getViewMatrix = function (force) {
  10035. this._computedViewMatrix = this._computeViewMatrix(force);
  10036. if (!force && this._isSynchronizedViewMatrix()) {
  10037. return this._computedViewMatrix;
  10038. }
  10039. if (!this.parent || !this.parent.getWorldMatrix) {
  10040. this._globalPosition.copyFrom(this.position);
  10041. }
  10042. else {
  10043. if (!this._worldMatrix) {
  10044. this._worldMatrix = BABYLON.Matrix.Identity();
  10045. }
  10046. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10047. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10048. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10049. this._computedViewMatrix.invert();
  10050. this._markSyncedWithParent();
  10051. }
  10052. this._currentRenderId = this.getScene().getRenderId();
  10053. return this._computedViewMatrix;
  10054. };
  10055. Camera.prototype._computeViewMatrix = function (force) {
  10056. if (!force && this._isSynchronizedViewMatrix()) {
  10057. return this._computedViewMatrix;
  10058. }
  10059. this._computedViewMatrix = this._getViewMatrix();
  10060. this._currentRenderId = this.getScene().getRenderId();
  10061. return this._computedViewMatrix;
  10062. };
  10063. Camera.prototype.getProjectionMatrix = function (force) {
  10064. if (!force && this._isSynchronizedProjectionMatrix()) {
  10065. return this._projectionMatrix;
  10066. }
  10067. var engine = this.getEngine();
  10068. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10069. if (this.minZ <= 0) {
  10070. this.minZ = 0.1;
  10071. }
  10072. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10073. return this._projectionMatrix;
  10074. }
  10075. var halfWidth = engine.getRenderWidth() / 2.0;
  10076. var halfHeight = engine.getRenderHeight() / 2.0;
  10077. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10078. return this._projectionMatrix;
  10079. };
  10080. Camera.prototype.dispose = function () {
  10081. // Remove from scene
  10082. this.getScene().removeCamera(this);
  10083. while (this._rigCameras.length > 0) {
  10084. this._rigCameras.pop().dispose();
  10085. }
  10086. // Postprocesses
  10087. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10088. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10089. }
  10090. };
  10091. // ---- Camera rigs section ----
  10092. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10093. while (this._rigCameras.length > 0) {
  10094. this._rigCameras.pop().dispose();
  10095. }
  10096. this.cameraRigMode = mode;
  10097. this._cameraRigParams = {};
  10098. switch (this.cameraRigMode) {
  10099. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10100. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10101. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10102. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10103. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10104. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10105. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10106. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10107. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10108. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10109. break;
  10110. }
  10111. var postProcesses = new Array();
  10112. switch (this.cameraRigMode) {
  10113. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10114. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10115. this._rigCameras[0].isIntermediate = true;
  10116. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10117. postProcesses[1].onApply = function (effect) {
  10118. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10119. };
  10120. break;
  10121. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10122. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10123. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10124. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10125. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10126. var secondCamIndex = 1 - firstCamIndex;
  10127. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10128. this._rigCameras[firstCamIndex].isIntermediate = true;
  10129. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10130. break;
  10131. case Camera.RIG_MODE_VR:
  10132. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10133. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10134. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10135. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10136. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10137. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10138. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10139. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10140. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10141. if (metrics.compensateDistortion) {
  10142. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10143. }
  10144. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10145. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10146. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10147. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10148. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10149. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10150. if (metrics.compensateDistortion) {
  10151. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10152. }
  10153. break;
  10154. }
  10155. this._update();
  10156. };
  10157. Camera.prototype._getVRProjectionMatrix = function () {
  10158. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10159. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10160. return this._projectionMatrix;
  10161. };
  10162. Camera.prototype.setCameraRigParameter = function (name, value) {
  10163. this._cameraRigParams[name] = value;
  10164. //provisionnally:
  10165. if (name === "interaxialDistance") {
  10166. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10167. }
  10168. };
  10169. /**
  10170. * May needs to be overridden by children so sub has required properties to be copied
  10171. */
  10172. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10173. return null;
  10174. };
  10175. /**
  10176. * May needs to be overridden by children
  10177. */
  10178. Camera.prototype._updateRigCameras = function () {
  10179. for (var i = 0; i < this._rigCameras.length; i++) {
  10180. this._rigCameras[i].minZ = this.minZ;
  10181. this._rigCameras[i].maxZ = this.maxZ;
  10182. this._rigCameras[i].fov = this.fov;
  10183. }
  10184. // only update viewport when ANAGLYPH
  10185. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10186. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10187. }
  10188. };
  10189. // Statics
  10190. Camera._PERSPECTIVE_CAMERA = 0;
  10191. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10192. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10193. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10194. Camera._RIG_MODE_NONE = 0;
  10195. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10196. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10197. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10198. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10199. Camera._RIG_MODE_VR = 20;
  10200. return Camera;
  10201. })(BABYLON.Node);
  10202. BABYLON.Camera = Camera;
  10203. })(BABYLON || (BABYLON = {}));
  10204. var BABYLON;
  10205. (function (BABYLON) {
  10206. var TargetCamera = (function (_super) {
  10207. __extends(TargetCamera, _super);
  10208. function TargetCamera(name, position, scene) {
  10209. _super.call(this, name, position, scene);
  10210. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10211. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10212. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10213. this.speed = 2.0;
  10214. this.noRotationConstraint = false;
  10215. this.lockedTarget = null;
  10216. this._currentTarget = BABYLON.Vector3.Zero();
  10217. this._viewMatrix = BABYLON.Matrix.Zero();
  10218. this._camMatrix = BABYLON.Matrix.Zero();
  10219. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10220. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10221. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10222. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10223. this._lookAtTemp = BABYLON.Matrix.Zero();
  10224. this._tempMatrix = BABYLON.Matrix.Zero();
  10225. }
  10226. TargetCamera.prototype.getFrontPosition = function (distance) {
  10227. var direction = this.getTarget().subtract(this.position);
  10228. direction.normalize();
  10229. direction.scaleInPlace(distance);
  10230. return this.globalPosition.add(direction);
  10231. };
  10232. TargetCamera.prototype._getLockedTargetPosition = function () {
  10233. if (!this.lockedTarget) {
  10234. return null;
  10235. }
  10236. return this.lockedTarget.position || this.lockedTarget;
  10237. };
  10238. // Cache
  10239. TargetCamera.prototype._initCache = function () {
  10240. _super.prototype._initCache.call(this);
  10241. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10242. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10243. };
  10244. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10245. if (!ignoreParentClass) {
  10246. _super.prototype._updateCache.call(this);
  10247. }
  10248. var lockedTargetPosition = this._getLockedTargetPosition();
  10249. if (!lockedTargetPosition) {
  10250. this._cache.lockedTarget = null;
  10251. }
  10252. else {
  10253. if (!this._cache.lockedTarget) {
  10254. this._cache.lockedTarget = lockedTargetPosition.clone();
  10255. }
  10256. else {
  10257. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10258. }
  10259. }
  10260. this._cache.rotation.copyFrom(this.rotation);
  10261. };
  10262. // Synchronized
  10263. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10264. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10265. return false;
  10266. }
  10267. var lockedTargetPosition = this._getLockedTargetPosition();
  10268. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10269. && this._cache.rotation.equals(this.rotation);
  10270. };
  10271. // Methods
  10272. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10273. var engine = this.getEngine();
  10274. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10275. };
  10276. // Target
  10277. TargetCamera.prototype.setTarget = function (target) {
  10278. this.upVector.normalize();
  10279. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10280. this._camMatrix.invert();
  10281. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10282. var vDir = target.subtract(this.position);
  10283. if (vDir.x >= 0.0) {
  10284. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10285. }
  10286. else {
  10287. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10288. }
  10289. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10290. if (isNaN(this.rotation.x)) {
  10291. this.rotation.x = 0;
  10292. }
  10293. if (isNaN(this.rotation.y)) {
  10294. this.rotation.y = 0;
  10295. }
  10296. if (isNaN(this.rotation.z)) {
  10297. this.rotation.z = 0;
  10298. }
  10299. };
  10300. TargetCamera.prototype.getTarget = function () {
  10301. return this._currentTarget;
  10302. };
  10303. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10304. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10305. };
  10306. TargetCamera.prototype._updatePosition = function () {
  10307. this.position.addInPlace(this.cameraDirection);
  10308. };
  10309. TargetCamera.prototype._checkInputs = function () {
  10310. var needToMove = this._decideIfNeedsToMove();
  10311. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10312. // Move
  10313. if (needToMove) {
  10314. this._updatePosition();
  10315. }
  10316. // Rotate
  10317. if (needToRotate) {
  10318. this.rotation.x += this.cameraRotation.x;
  10319. this.rotation.y += this.cameraRotation.y;
  10320. if (!this.noRotationConstraint) {
  10321. var limit = (Math.PI / 2) * 0.95;
  10322. if (this.rotation.x > limit)
  10323. this.rotation.x = limit;
  10324. if (this.rotation.x < -limit)
  10325. this.rotation.x = -limit;
  10326. }
  10327. }
  10328. // Inertia
  10329. if (needToMove) {
  10330. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10331. this.cameraDirection.x = 0;
  10332. }
  10333. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10334. this.cameraDirection.y = 0;
  10335. }
  10336. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10337. this.cameraDirection.z = 0;
  10338. }
  10339. this.cameraDirection.scaleInPlace(this.inertia);
  10340. }
  10341. if (needToRotate) {
  10342. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10343. this.cameraRotation.x = 0;
  10344. }
  10345. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10346. this.cameraRotation.y = 0;
  10347. }
  10348. this.cameraRotation.scaleInPlace(this.inertia);
  10349. }
  10350. _super.prototype._checkInputs.call(this);
  10351. };
  10352. TargetCamera.prototype._getViewMatrix = function () {
  10353. if (!this.lockedTarget) {
  10354. // Compute
  10355. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10356. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10357. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10358. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10359. this._lookAtTemp.invert();
  10360. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10361. }
  10362. else {
  10363. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10364. }
  10365. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10366. // Computing target and final matrix
  10367. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10368. }
  10369. else {
  10370. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10371. }
  10372. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10373. return this._viewMatrix;
  10374. };
  10375. TargetCamera.prototype._getVRViewMatrix = function () {
  10376. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10377. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10378. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10379. // Computing target and final matrix
  10380. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10381. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10382. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10383. return this._viewMatrix;
  10384. };
  10385. /**
  10386. * @override
  10387. * Override Camera.createRigCamera
  10388. */
  10389. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10390. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10391. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10392. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10393. rigCamera._cameraRigParams = {};
  10394. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10395. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10396. }
  10397. return rigCamera;
  10398. }
  10399. return null;
  10400. };
  10401. /**
  10402. * @override
  10403. * Override Camera._updateRigCameras
  10404. */
  10405. TargetCamera.prototype._updateRigCameras = function () {
  10406. switch (this.cameraRigMode) {
  10407. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10408. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10409. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10410. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10411. case BABYLON.Camera.RIG_MODE_VR:
  10412. var camLeft = this._rigCameras[0];
  10413. var camRight = this._rigCameras[1];
  10414. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10415. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10416. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10417. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10418. camLeft.position.copyFrom(this.position);
  10419. camRight.position.copyFrom(this.position);
  10420. }
  10421. else {
  10422. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10423. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10424. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10425. camLeft.setTarget(this.getTarget());
  10426. camRight.setTarget(this.getTarget());
  10427. }
  10428. break;
  10429. }
  10430. _super.prototype._updateRigCameras.call(this);
  10431. };
  10432. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10433. if (!this._rigCamTransformMatrix) {
  10434. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10435. }
  10436. var target = this.getTarget();
  10437. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10438. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10439. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10440. };
  10441. return TargetCamera;
  10442. })(BABYLON.Camera);
  10443. BABYLON.TargetCamera = TargetCamera;
  10444. })(BABYLON || (BABYLON = {}));
  10445. var BABYLON;
  10446. (function (BABYLON) {
  10447. var FreeCamera = (function (_super) {
  10448. __extends(FreeCamera, _super);
  10449. function FreeCamera(name, position, scene) {
  10450. var _this = this;
  10451. _super.call(this, name, position, scene);
  10452. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10453. this.keysUp = [38];
  10454. this.keysDown = [40];
  10455. this.keysLeft = [37];
  10456. this.keysRight = [39];
  10457. this.checkCollisions = false;
  10458. this.applyGravity = false;
  10459. this.angularSensibility = 2000.0;
  10460. this._keys = [];
  10461. this._collider = new BABYLON.Collider();
  10462. this._needMoveForGravity = false;
  10463. this._oldPosition = BABYLON.Vector3.Zero();
  10464. this._diffPosition = BABYLON.Vector3.Zero();
  10465. this._newPosition = BABYLON.Vector3.Zero();
  10466. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10467. if (collidedMesh === void 0) { collidedMesh = null; }
  10468. //TODO move this to the collision coordinator!
  10469. if (_this.getScene().workerCollisions)
  10470. newPosition.multiplyInPlace(_this._collider.radius);
  10471. var updatePosition = function (newPos) {
  10472. _this._newPosition.copyFrom(newPos);
  10473. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10474. var oldPosition = _this.position.clone();
  10475. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10476. _this.position.addInPlace(_this._diffPosition);
  10477. if (_this.onCollide && collidedMesh) {
  10478. _this.onCollide(collidedMesh);
  10479. }
  10480. }
  10481. };
  10482. updatePosition(newPosition);
  10483. };
  10484. }
  10485. // Controls
  10486. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10487. var _this = this;
  10488. var previousPosition;
  10489. var engine = this.getEngine();
  10490. if (this._attachedElement) {
  10491. return;
  10492. }
  10493. this._attachedElement = element;
  10494. if (this._onMouseDown === undefined) {
  10495. this._onMouseDown = function (evt) {
  10496. previousPosition = {
  10497. x: evt.clientX,
  10498. y: evt.clientY
  10499. };
  10500. if (!noPreventDefault) {
  10501. evt.preventDefault();
  10502. }
  10503. };
  10504. this._onMouseUp = function (evt) {
  10505. previousPosition = null;
  10506. if (!noPreventDefault) {
  10507. evt.preventDefault();
  10508. }
  10509. };
  10510. this._onMouseOut = function (evt) {
  10511. previousPosition = null;
  10512. _this._keys = [];
  10513. if (!noPreventDefault) {
  10514. evt.preventDefault();
  10515. }
  10516. };
  10517. this._onMouseMove = function (evt) {
  10518. if (!previousPosition && !engine.isPointerLock) {
  10519. return;
  10520. }
  10521. var offsetX;
  10522. var offsetY;
  10523. if (!engine.isPointerLock) {
  10524. offsetX = evt.clientX - previousPosition.x;
  10525. offsetY = evt.clientY - previousPosition.y;
  10526. }
  10527. else {
  10528. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10529. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10530. }
  10531. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10532. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10533. previousPosition = {
  10534. x: evt.clientX,
  10535. y: evt.clientY
  10536. };
  10537. if (!noPreventDefault) {
  10538. evt.preventDefault();
  10539. }
  10540. };
  10541. this._onKeyDown = function (evt) {
  10542. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10543. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10544. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10545. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10546. var index = _this._keys.indexOf(evt.keyCode);
  10547. if (index === -1) {
  10548. _this._keys.push(evt.keyCode);
  10549. }
  10550. if (!noPreventDefault) {
  10551. evt.preventDefault();
  10552. }
  10553. }
  10554. };
  10555. this._onKeyUp = function (evt) {
  10556. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10557. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10558. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10559. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10560. var index = _this._keys.indexOf(evt.keyCode);
  10561. if (index >= 0) {
  10562. _this._keys.splice(index, 1);
  10563. }
  10564. if (!noPreventDefault) {
  10565. evt.preventDefault();
  10566. }
  10567. }
  10568. };
  10569. this._onLostFocus = function () {
  10570. _this._keys = [];
  10571. };
  10572. this._reset = function () {
  10573. _this._keys = [];
  10574. previousPosition = null;
  10575. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10576. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10577. };
  10578. }
  10579. element.addEventListener("mousedown", this._onMouseDown, false);
  10580. element.addEventListener("mouseup", this._onMouseUp, false);
  10581. element.addEventListener("mouseout", this._onMouseOut, false);
  10582. element.addEventListener("mousemove", this._onMouseMove, false);
  10583. BABYLON.Tools.RegisterTopRootEvents([
  10584. { name: "keydown", handler: this._onKeyDown },
  10585. { name: "keyup", handler: this._onKeyUp },
  10586. { name: "blur", handler: this._onLostFocus }
  10587. ]);
  10588. };
  10589. FreeCamera.prototype.detachControl = function (element) {
  10590. if (this._attachedElement != element) {
  10591. return;
  10592. }
  10593. element.removeEventListener("mousedown", this._onMouseDown);
  10594. element.removeEventListener("mouseup", this._onMouseUp);
  10595. element.removeEventListener("mouseout", this._onMouseOut);
  10596. element.removeEventListener("mousemove", this._onMouseMove);
  10597. BABYLON.Tools.UnregisterTopRootEvents([
  10598. { name: "keydown", handler: this._onKeyDown },
  10599. { name: "keyup", handler: this._onKeyUp },
  10600. { name: "blur", handler: this._onLostFocus }
  10601. ]);
  10602. this._attachedElement = null;
  10603. if (this._reset) {
  10604. this._reset();
  10605. }
  10606. };
  10607. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10608. var globalPosition;
  10609. if (this.parent) {
  10610. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10611. }
  10612. else {
  10613. globalPosition = this.position;
  10614. }
  10615. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10616. this._collider.radius = this.ellipsoid;
  10617. //no need for clone, as long as gravity is not on.
  10618. var actualVelocity = velocity;
  10619. //add gravity to the velocity to prevent the dual-collision checking
  10620. if (this.applyGravity) {
  10621. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10622. actualVelocity = velocity.add(this.getScene().gravity);
  10623. }
  10624. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10625. };
  10626. FreeCamera.prototype._checkInputs = function () {
  10627. if (!this._localDirection) {
  10628. this._localDirection = BABYLON.Vector3.Zero();
  10629. this._transformedDirection = BABYLON.Vector3.Zero();
  10630. }
  10631. // Keyboard
  10632. for (var index = 0; index < this._keys.length; index++) {
  10633. var keyCode = this._keys[index];
  10634. var speed = this._computeLocalCameraSpeed();
  10635. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10636. this._localDirection.copyFromFloats(-speed, 0, 0);
  10637. }
  10638. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10639. this._localDirection.copyFromFloats(0, 0, speed);
  10640. }
  10641. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10642. this._localDirection.copyFromFloats(speed, 0, 0);
  10643. }
  10644. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10645. this._localDirection.copyFromFloats(0, 0, -speed);
  10646. }
  10647. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10648. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10649. this.cameraDirection.addInPlace(this._transformedDirection);
  10650. }
  10651. _super.prototype._checkInputs.call(this);
  10652. };
  10653. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10654. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10655. };
  10656. FreeCamera.prototype._updatePosition = function () {
  10657. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10658. this._collideWithWorld(this.cameraDirection);
  10659. }
  10660. else {
  10661. this.position.addInPlace(this.cameraDirection);
  10662. }
  10663. };
  10664. return FreeCamera;
  10665. })(BABYLON.TargetCamera);
  10666. BABYLON.FreeCamera = FreeCamera;
  10667. })(BABYLON || (BABYLON = {}));
  10668. var BABYLON;
  10669. (function (BABYLON) {
  10670. var FollowCamera = (function (_super) {
  10671. __extends(FollowCamera, _super);
  10672. function FollowCamera(name, position, scene) {
  10673. _super.call(this, name, position, scene);
  10674. this.radius = 12;
  10675. this.rotationOffset = 0;
  10676. this.heightOffset = 4;
  10677. this.cameraAcceleration = 0.05;
  10678. this.maxCameraSpeed = 20;
  10679. }
  10680. FollowCamera.prototype.getRadians = function (degrees) {
  10681. return degrees * Math.PI / 180;
  10682. };
  10683. FollowCamera.prototype.follow = function (cameraTarget) {
  10684. if (!cameraTarget)
  10685. return;
  10686. var yRotation;
  10687. if (cameraTarget.rotationQuaternion) {
  10688. var rotMatrix = new BABYLON.Matrix();
  10689. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10690. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10691. }
  10692. else {
  10693. yRotation = cameraTarget.rotation.y;
  10694. }
  10695. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10696. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10697. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10698. var dx = targetX - this.position.x;
  10699. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10700. var dz = (targetZ) - this.position.z;
  10701. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10702. var vy = dy * this.cameraAcceleration;
  10703. var vz = dz * this.cameraAcceleration * 2;
  10704. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10705. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10706. }
  10707. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10708. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10709. }
  10710. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10711. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10712. }
  10713. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10714. this.setTarget(cameraTarget.position);
  10715. };
  10716. FollowCamera.prototype._checkInputs = function () {
  10717. _super.prototype._checkInputs.call(this);
  10718. this.follow(this.target);
  10719. };
  10720. return FollowCamera;
  10721. })(BABYLON.TargetCamera);
  10722. BABYLON.FollowCamera = FollowCamera;
  10723. var ArcFollowCamera = (function (_super) {
  10724. __extends(ArcFollowCamera, _super);
  10725. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10726. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10727. this.alpha = alpha;
  10728. this.beta = beta;
  10729. this.radius = radius;
  10730. this.target = target;
  10731. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10732. this.follow();
  10733. }
  10734. ArcFollowCamera.prototype.follow = function () {
  10735. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10736. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10737. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10738. this.position = this.target.position.add(this._cartesianCoordinates);
  10739. this.setTarget(this.target.position);
  10740. };
  10741. ArcFollowCamera.prototype._checkInputs = function () {
  10742. _super.prototype._checkInputs.call(this);
  10743. this.follow();
  10744. };
  10745. return ArcFollowCamera;
  10746. })(BABYLON.TargetCamera);
  10747. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10748. })(BABYLON || (BABYLON = {}));
  10749. var BABYLON;
  10750. (function (BABYLON) {
  10751. // We're mainly based on the logic defined into the FreeCamera code
  10752. var TouchCamera = (function (_super) {
  10753. __extends(TouchCamera, _super);
  10754. function TouchCamera(name, position, scene) {
  10755. _super.call(this, name, position, scene);
  10756. this._offsetX = null;
  10757. this._offsetY = null;
  10758. this._pointerCount = 0;
  10759. this._pointerPressed = [];
  10760. this.angularSensibility = 200000.0;
  10761. this.moveSensibility = 500.0;
  10762. }
  10763. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10764. var _this = this;
  10765. var previousPosition;
  10766. if (this._attachedCanvas) {
  10767. return;
  10768. }
  10769. this._attachedCanvas = canvas;
  10770. if (this._onPointerDown === undefined) {
  10771. this._onPointerDown = function (evt) {
  10772. if (!noPreventDefault) {
  10773. evt.preventDefault();
  10774. }
  10775. _this._pointerPressed.push(evt.pointerId);
  10776. if (_this._pointerPressed.length !== 1) {
  10777. return;
  10778. }
  10779. previousPosition = {
  10780. x: evt.clientX,
  10781. y: evt.clientY
  10782. };
  10783. };
  10784. this._onPointerUp = function (evt) {
  10785. if (!noPreventDefault) {
  10786. evt.preventDefault();
  10787. }
  10788. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10789. if (index === -1) {
  10790. return;
  10791. }
  10792. _this._pointerPressed.splice(index, 1);
  10793. if (index != 0) {
  10794. return;
  10795. }
  10796. previousPosition = null;
  10797. _this._offsetX = null;
  10798. _this._offsetY = null;
  10799. };
  10800. this._onPointerMove = function (evt) {
  10801. if (!noPreventDefault) {
  10802. evt.preventDefault();
  10803. }
  10804. if (!previousPosition) {
  10805. return;
  10806. }
  10807. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10808. if (index != 0) {
  10809. return;
  10810. }
  10811. _this._offsetX = evt.clientX - previousPosition.x;
  10812. _this._offsetY = -(evt.clientY - previousPosition.y);
  10813. };
  10814. this._onLostFocus = function () {
  10815. _this._offsetX = null;
  10816. _this._offsetY = null;
  10817. };
  10818. }
  10819. canvas.addEventListener("pointerdown", this._onPointerDown);
  10820. canvas.addEventListener("pointerup", this._onPointerUp);
  10821. canvas.addEventListener("pointerout", this._onPointerUp);
  10822. canvas.addEventListener("pointermove", this._onPointerMove);
  10823. BABYLON.Tools.RegisterTopRootEvents([
  10824. { name: "blur", handler: this._onLostFocus }
  10825. ]);
  10826. };
  10827. TouchCamera.prototype.detachControl = function (canvas) {
  10828. if (this._attachedCanvas != canvas) {
  10829. return;
  10830. }
  10831. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10832. canvas.removeEventListener("pointerup", this._onPointerUp);
  10833. canvas.removeEventListener("pointerout", this._onPointerUp);
  10834. canvas.removeEventListener("pointermove", this._onPointerMove);
  10835. BABYLON.Tools.UnregisterTopRootEvents([
  10836. { name: "blur", handler: this._onLostFocus }
  10837. ]);
  10838. this._attachedCanvas = null;
  10839. };
  10840. TouchCamera.prototype._checkInputs = function () {
  10841. if (this._offsetX) {
  10842. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10843. if (this._pointerPressed.length > 1) {
  10844. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10845. }
  10846. else {
  10847. var speed = this._computeLocalCameraSpeed();
  10848. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10849. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10850. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10851. }
  10852. }
  10853. _super.prototype._checkInputs.call(this);
  10854. };
  10855. return TouchCamera;
  10856. })(BABYLON.FreeCamera);
  10857. BABYLON.TouchCamera = TouchCamera;
  10858. })(BABYLON || (BABYLON = {}));
  10859. var BABYLON;
  10860. (function (BABYLON) {
  10861. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10862. var ArcRotateCamera = (function (_super) {
  10863. __extends(ArcRotateCamera, _super);
  10864. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10865. var _this = this;
  10866. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10867. this.alpha = alpha;
  10868. this.beta = beta;
  10869. this.radius = radius;
  10870. this.target = target;
  10871. this.inertialAlphaOffset = 0;
  10872. this.inertialBetaOffset = 0;
  10873. this.inertialRadiusOffset = 0;
  10874. this.lowerAlphaLimit = null;
  10875. this.upperAlphaLimit = null;
  10876. this.lowerBetaLimit = 0.01;
  10877. this.upperBetaLimit = Math.PI;
  10878. this.lowerRadiusLimit = null;
  10879. this.upperRadiusLimit = null;
  10880. this.angularSensibilityX = 1000.0;
  10881. this.angularSensibilityY = 1000.0;
  10882. this.wheelPrecision = 3.0;
  10883. this.pinchPrecision = 2.0;
  10884. this.panningSensibility = 50.0;
  10885. this.inertialPanningX = 0;
  10886. this.inertialPanningY = 0;
  10887. this.keysUp = [38];
  10888. this.keysDown = [40];
  10889. this.keysLeft = [37];
  10890. this.keysRight = [39];
  10891. this.zoomOnFactor = 1;
  10892. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10893. this.pinchInwards = true;
  10894. this.allowUpsideDown = true;
  10895. this._keys = [];
  10896. this._viewMatrix = new BABYLON.Matrix();
  10897. this._isRightClick = false;
  10898. this._isCtrlPushed = false;
  10899. this.checkCollisions = false;
  10900. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10901. this._collider = new BABYLON.Collider();
  10902. this._previousPosition = BABYLON.Vector3.Zero();
  10903. this._collisionVelocity = BABYLON.Vector3.Zero();
  10904. this._newPosition = BABYLON.Vector3.Zero();
  10905. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10906. if (collidedMesh === void 0) { collidedMesh = null; }
  10907. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10908. newPosition.multiplyInPlace(_this._collider.radius);
  10909. }
  10910. if (!collidedMesh) {
  10911. _this._previousPosition.copyFrom(_this.position);
  10912. }
  10913. else {
  10914. _this.setPosition(_this.position);
  10915. if (_this.onCollide) {
  10916. _this.onCollide(collidedMesh);
  10917. }
  10918. }
  10919. // Recompute because of constraints
  10920. var cosa = Math.cos(_this.alpha);
  10921. var sina = Math.sin(_this.alpha);
  10922. var cosb = Math.cos(_this.beta);
  10923. var sinb = Math.sin(_this.beta);
  10924. var target = _this._getTargetPosition();
  10925. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10926. _this.position.copyFrom(_this._newPosition);
  10927. var up = _this.upVector;
  10928. if (_this.allowUpsideDown && _this.beta < 0) {
  10929. var up = up.clone();
  10930. up = up.negate();
  10931. }
  10932. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10933. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10934. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10935. _this._collisionTriggered = false;
  10936. };
  10937. if (!this.target) {
  10938. this.target = BABYLON.Vector3.Zero();
  10939. }
  10940. this.getViewMatrix();
  10941. }
  10942. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  10943. //deprecated angularSensibility support
  10944. get: function () {
  10945. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10946. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  10947. },
  10948. //deprecated angularSensibility support
  10949. set: function (value) {
  10950. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10951. this.angularSensibilityX = value;
  10952. this.angularSensibilityY = value;
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. ArcRotateCamera.prototype._getTargetPosition = function () {
  10958. return this.target.position || this.target;
  10959. };
  10960. // Cache
  10961. ArcRotateCamera.prototype._initCache = function () {
  10962. _super.prototype._initCache.call(this);
  10963. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10964. this._cache.alpha = undefined;
  10965. this._cache.beta = undefined;
  10966. this._cache.radius = undefined;
  10967. this._cache.targetScreenOffset = undefined;
  10968. };
  10969. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10970. if (!ignoreParentClass) {
  10971. _super.prototype._updateCache.call(this);
  10972. }
  10973. this._cache.target.copyFrom(this._getTargetPosition());
  10974. this._cache.alpha = this.alpha;
  10975. this._cache.beta = this.beta;
  10976. this._cache.radius = this.radius;
  10977. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10978. };
  10979. // Synchronized
  10980. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10981. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10982. return false;
  10983. return this._cache.target.equals(this._getTargetPosition())
  10984. && this._cache.alpha === this.alpha
  10985. && this._cache.beta === this.beta
  10986. && this._cache.radius === this.radius
  10987. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10988. };
  10989. // Methods
  10990. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  10991. var _this = this;
  10992. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  10993. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10994. var previousPinchDistance = 0;
  10995. var pointers = new BABYLON.SmartCollection();
  10996. if (this._attachedElement) {
  10997. return;
  10998. }
  10999. this._attachedElement = element;
  11000. var engine = this.getEngine();
  11001. if (this._onPointerDown === undefined) {
  11002. this._onPointerDown = function (evt) {
  11003. // Manage panning with right click
  11004. _this._isRightClick = evt.button === 2 ? true : false;
  11005. // manage pointers
  11006. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11007. cacheSoloPointer = pointers.item(evt.pointerId);
  11008. if (!noPreventDefault) {
  11009. evt.preventDefault();
  11010. }
  11011. };
  11012. this._onPointerUp = function (evt) {
  11013. cacheSoloPointer = null;
  11014. previousPinchDistance = 0;
  11015. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11016. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11017. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11018. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11019. pointers.empty();
  11020. if (!noPreventDefault) {
  11021. evt.preventDefault();
  11022. }
  11023. };
  11024. this._onContextMenu = function (evt) {
  11025. evt.preventDefault();
  11026. };
  11027. this._onPointerMove = function (evt) {
  11028. if (!noPreventDefault) {
  11029. evt.preventDefault();
  11030. }
  11031. switch (pointers.count) {
  11032. case 1:
  11033. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11034. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11035. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11036. }
  11037. else {
  11038. var offsetX = evt.clientX - cacheSoloPointer.x;
  11039. var offsetY = evt.clientY - cacheSoloPointer.y;
  11040. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11041. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11042. }
  11043. cacheSoloPointer.x = evt.clientX;
  11044. cacheSoloPointer.y = evt.clientY;
  11045. break;
  11046. case 2:
  11047. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11048. pointers.item(evt.pointerId).x = evt.clientX;
  11049. pointers.item(evt.pointerId).y = evt.clientY;
  11050. var direction = _this.pinchInwards ? 1 : -1;
  11051. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11052. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11053. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11054. if (previousPinchDistance === 0) {
  11055. previousPinchDistance = pinchSquaredDistance;
  11056. return;
  11057. }
  11058. if (pinchSquaredDistance !== previousPinchDistance) {
  11059. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11060. previousPinchDistance = pinchSquaredDistance;
  11061. }
  11062. break;
  11063. default:
  11064. if (pointers.item(evt.pointerId)) {
  11065. pointers.item(evt.pointerId).x = evt.clientX;
  11066. pointers.item(evt.pointerId).y = evt.clientY;
  11067. }
  11068. }
  11069. };
  11070. this._onMouseMove = function (evt) {
  11071. if (!engine.isPointerLock) {
  11072. return;
  11073. }
  11074. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11075. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11076. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11077. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11078. if (!noPreventDefault) {
  11079. evt.preventDefault();
  11080. }
  11081. };
  11082. this._wheel = function (event) {
  11083. var delta = 0;
  11084. if (event.wheelDelta) {
  11085. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11086. }
  11087. else if (event.detail) {
  11088. delta = -event.detail / _this.wheelPrecision;
  11089. }
  11090. if (delta)
  11091. _this.inertialRadiusOffset += delta;
  11092. if (event.preventDefault) {
  11093. if (!noPreventDefault) {
  11094. event.preventDefault();
  11095. }
  11096. }
  11097. };
  11098. this._onKeyDown = function (evt) {
  11099. _this._isCtrlPushed = evt.ctrlKey;
  11100. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11101. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11102. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11103. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11104. var index = _this._keys.indexOf(evt.keyCode);
  11105. if (index === -1) {
  11106. _this._keys.push(evt.keyCode);
  11107. }
  11108. if (evt.preventDefault) {
  11109. if (!noPreventDefault) {
  11110. evt.preventDefault();
  11111. }
  11112. }
  11113. }
  11114. };
  11115. this._onKeyUp = function (evt) {
  11116. _this._isCtrlPushed = evt.ctrlKey;
  11117. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11118. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11119. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11120. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11121. var index = _this._keys.indexOf(evt.keyCode);
  11122. if (index >= 0) {
  11123. _this._keys.splice(index, 1);
  11124. }
  11125. if (evt.preventDefault) {
  11126. if (!noPreventDefault) {
  11127. evt.preventDefault();
  11128. }
  11129. }
  11130. }
  11131. };
  11132. this._onLostFocus = function () {
  11133. _this._keys = [];
  11134. pointers.empty();
  11135. previousPinchDistance = 0;
  11136. cacheSoloPointer = null;
  11137. };
  11138. this._onGestureStart = function (e) {
  11139. if (window.MSGesture === undefined) {
  11140. return;
  11141. }
  11142. if (!_this._MSGestureHandler) {
  11143. _this._MSGestureHandler = new MSGesture();
  11144. _this._MSGestureHandler.target = element;
  11145. }
  11146. _this._MSGestureHandler.addPointer(e.pointerId);
  11147. };
  11148. this._onGesture = function (e) {
  11149. _this.radius *= e.scale;
  11150. if (e.preventDefault) {
  11151. if (!noPreventDefault) {
  11152. e.stopPropagation();
  11153. e.preventDefault();
  11154. }
  11155. }
  11156. };
  11157. this._reset = function () {
  11158. _this._keys = [];
  11159. _this.inertialAlphaOffset = 0;
  11160. _this.inertialBetaOffset = 0;
  11161. _this.inertialRadiusOffset = 0;
  11162. pointers.empty();
  11163. previousPinchDistance = 0;
  11164. cacheSoloPointer = null;
  11165. };
  11166. }
  11167. if (!useCtrlForPanning) {
  11168. element.addEventListener("contextmenu", this._onContextMenu, false);
  11169. }
  11170. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11171. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11172. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11173. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11174. element.addEventListener("mousemove", this._onMouseMove, false);
  11175. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11176. element.addEventListener("MSGestureChange", this._onGesture, false);
  11177. element.addEventListener('mousewheel', this._wheel, false);
  11178. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11179. BABYLON.Tools.RegisterTopRootEvents([
  11180. { name: "keydown", handler: this._onKeyDown },
  11181. { name: "keyup", handler: this._onKeyUp },
  11182. { name: "blur", handler: this._onLostFocus }
  11183. ]);
  11184. };
  11185. ArcRotateCamera.prototype.detachControl = function (element) {
  11186. if (this._attachedElement !== element) {
  11187. return;
  11188. }
  11189. element.removeEventListener("contextmenu", this._onContextMenu);
  11190. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11191. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11192. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11193. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11194. element.removeEventListener("mousemove", this._onMouseMove);
  11195. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11196. element.removeEventListener("MSGestureChange", this._onGesture);
  11197. element.removeEventListener('mousewheel', this._wheel);
  11198. element.removeEventListener('DOMMouseScroll', this._wheel);
  11199. BABYLON.Tools.UnregisterTopRootEvents([
  11200. { name: "keydown", handler: this._onKeyDown },
  11201. { name: "keyup", handler: this._onKeyUp },
  11202. { name: "blur", handler: this._onLostFocus }
  11203. ]);
  11204. this._MSGestureHandler = null;
  11205. this._attachedElement = null;
  11206. if (this._reset) {
  11207. this._reset();
  11208. }
  11209. };
  11210. ArcRotateCamera.prototype._checkInputs = function () {
  11211. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11212. if (this._collisionTriggered) {
  11213. return;
  11214. }
  11215. // Keyboard
  11216. for (var index = 0; index < this._keys.length; index++) {
  11217. var keyCode = this._keys[index];
  11218. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11219. this.inertialAlphaOffset -= 0.01;
  11220. }
  11221. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11222. this.inertialBetaOffset -= 0.01;
  11223. }
  11224. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11225. this.inertialAlphaOffset += 0.01;
  11226. }
  11227. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11228. this.inertialBetaOffset += 0.01;
  11229. }
  11230. }
  11231. // Inertia
  11232. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11233. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11234. this.beta += this.inertialBetaOffset;
  11235. this.radius -= this.inertialRadiusOffset;
  11236. this.inertialAlphaOffset *= this.inertia;
  11237. this.inertialBetaOffset *= this.inertia;
  11238. this.inertialRadiusOffset *= this.inertia;
  11239. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11240. this.inertialAlphaOffset = 0;
  11241. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11242. this.inertialBetaOffset = 0;
  11243. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11244. this.inertialRadiusOffset = 0;
  11245. }
  11246. // Panning inertia
  11247. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11248. if (!this._localDirection) {
  11249. this._localDirection = BABYLON.Vector3.Zero();
  11250. this._transformedDirection = BABYLON.Vector3.Zero();
  11251. }
  11252. this.inertialPanningX *= this.inertia;
  11253. this.inertialPanningY *= this.inertia;
  11254. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11255. this.inertialPanningX = 0;
  11256. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11257. this.inertialPanningY = 0;
  11258. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11259. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11260. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11261. this.target.addInPlace(this._transformedDirection);
  11262. }
  11263. // Limits
  11264. this._checkLimits();
  11265. _super.prototype._checkInputs.call(this);
  11266. };
  11267. ArcRotateCamera.prototype._checkLimits = function () {
  11268. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11269. if (this.allowUpsideDown && this.beta > Math.PI) {
  11270. this.beta = this.beta - (2 * Math.PI);
  11271. }
  11272. }
  11273. else {
  11274. if (this.beta < this.lowerBetaLimit) {
  11275. this.beta = this.lowerBetaLimit;
  11276. }
  11277. }
  11278. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11279. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11280. this.beta = this.beta + (2 * Math.PI);
  11281. }
  11282. }
  11283. else {
  11284. if (this.beta > this.upperBetaLimit) {
  11285. this.beta = this.upperBetaLimit;
  11286. }
  11287. }
  11288. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11289. this.alpha = this.lowerAlphaLimit;
  11290. }
  11291. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11292. this.alpha = this.upperAlphaLimit;
  11293. }
  11294. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11295. this.radius = this.lowerRadiusLimit;
  11296. }
  11297. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11298. this.radius = this.upperRadiusLimit;
  11299. }
  11300. };
  11301. ArcRotateCamera.prototype.setPosition = function (position) {
  11302. var radiusv3 = position.subtract(this._getTargetPosition());
  11303. this.radius = radiusv3.length();
  11304. // Alpha
  11305. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11306. if (radiusv3.z < 0) {
  11307. this.alpha = 2 * Math.PI - this.alpha;
  11308. }
  11309. // Beta
  11310. this.beta = Math.acos(radiusv3.y / this.radius);
  11311. this._checkLimits();
  11312. };
  11313. ArcRotateCamera.prototype.setTarget = function (target) {
  11314. this.target = target;
  11315. };
  11316. ArcRotateCamera.prototype._getViewMatrix = function () {
  11317. // Compute
  11318. var cosa = Math.cos(this.alpha);
  11319. var sina = Math.sin(this.alpha);
  11320. var cosb = Math.cos(this.beta);
  11321. var sinb = Math.sin(this.beta);
  11322. var target = this._getTargetPosition();
  11323. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11324. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11325. this._collider.radius = this.collisionRadius;
  11326. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11327. this._collisionTriggered = true;
  11328. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11329. }
  11330. else {
  11331. this.position.copyFrom(this._newPosition);
  11332. var up = this.upVector;
  11333. if (this.allowUpsideDown && this.beta < 0) {
  11334. var up = up.clone();
  11335. up = up.negate();
  11336. }
  11337. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11338. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11339. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11340. }
  11341. return this._viewMatrix;
  11342. };
  11343. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11344. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11345. meshes = meshes || this.getScene().meshes;
  11346. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11347. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11348. this.radius = distance * this.zoomOnFactor;
  11349. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11350. };
  11351. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11352. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11353. var meshesOrMinMaxVector;
  11354. var distance;
  11355. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11356. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11357. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11358. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11359. }
  11360. else {
  11361. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11362. distance = meshesOrMinMaxVectorAndDistance.distance;
  11363. }
  11364. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11365. if (!doNotUpdateMaxZ) {
  11366. this.maxZ = distance * 2;
  11367. }
  11368. };
  11369. /**
  11370. * @override
  11371. * Override Camera.createRigCamera
  11372. */
  11373. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11374. switch (this.cameraRigMode) {
  11375. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11376. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11377. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11378. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11379. case BABYLON.Camera.RIG_MODE_VR:
  11380. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11381. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11382. }
  11383. };
  11384. /**
  11385. * @override
  11386. * Override Camera._updateRigCameras
  11387. */
  11388. ArcRotateCamera.prototype._updateRigCameras = function () {
  11389. switch (this.cameraRigMode) {
  11390. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11391. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11392. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11393. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11394. case BABYLON.Camera.RIG_MODE_VR:
  11395. var camLeft = this._rigCameras[0];
  11396. var camRight = this._rigCameras[1];
  11397. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11398. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11399. camLeft.beta = camRight.beta = this.beta;
  11400. camLeft.radius = camRight.radius = this.radius;
  11401. break;
  11402. }
  11403. _super.prototype._updateRigCameras.call(this);
  11404. };
  11405. return ArcRotateCamera;
  11406. })(BABYLON.TargetCamera);
  11407. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11408. })(BABYLON || (BABYLON = {}));
  11409. var BABYLON;
  11410. (function (BABYLON) {
  11411. var RenderingManager = (function () {
  11412. function RenderingManager(scene) {
  11413. this._renderingGroups = new Array();
  11414. this._scene = scene;
  11415. }
  11416. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11417. if (this._scene._activeParticleSystems.length === 0) {
  11418. return;
  11419. }
  11420. // Particles
  11421. var activeCamera = this._scene.activeCamera;
  11422. var beforeParticlesDate = BABYLON.Tools.Now;
  11423. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11424. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11425. if (particleSystem.renderingGroupId !== index) {
  11426. continue;
  11427. }
  11428. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11429. continue;
  11430. }
  11431. this._clearDepthBuffer();
  11432. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11433. this._scene._activeParticles += particleSystem.render();
  11434. }
  11435. }
  11436. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11437. };
  11438. RenderingManager.prototype._renderSprites = function (index) {
  11439. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11440. return;
  11441. }
  11442. // Sprites
  11443. var activeCamera = this._scene.activeCamera;
  11444. var beforeSpritessDate = BABYLON.Tools.Now;
  11445. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11446. var spriteManager = this._scene.spriteManagers[id];
  11447. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11448. this._clearDepthBuffer();
  11449. spriteManager.render();
  11450. }
  11451. }
  11452. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11453. };
  11454. RenderingManager.prototype._clearDepthBuffer = function () {
  11455. if (this._depthBufferAlreadyCleaned) {
  11456. return;
  11457. }
  11458. this._scene.getEngine().clear(0, false, true);
  11459. this._depthBufferAlreadyCleaned = true;
  11460. };
  11461. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11462. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11463. this._depthBufferAlreadyCleaned = false;
  11464. var renderingGroup = this._renderingGroups[index];
  11465. var needToStepBack = false;
  11466. if (renderingGroup) {
  11467. this._clearDepthBuffer();
  11468. if (!renderingGroup.render(customRenderFunction)) {
  11469. this._renderingGroups.splice(index, 1);
  11470. needToStepBack = true;
  11471. }
  11472. }
  11473. if (renderSprites) {
  11474. this._renderSprites(index);
  11475. }
  11476. if (renderParticles) {
  11477. this._renderParticles(index, activeMeshes);
  11478. }
  11479. if (needToStepBack) {
  11480. index--;
  11481. }
  11482. }
  11483. };
  11484. RenderingManager.prototype.reset = function () {
  11485. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11486. if (renderingGroup) {
  11487. renderingGroup.prepare();
  11488. }
  11489. });
  11490. };
  11491. RenderingManager.prototype.dispatch = function (subMesh) {
  11492. var mesh = subMesh.getMesh();
  11493. var renderingGroupId = mesh.renderingGroupId || 0;
  11494. if (!this._renderingGroups[renderingGroupId]) {
  11495. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11496. }
  11497. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11498. };
  11499. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11500. return RenderingManager;
  11501. })();
  11502. BABYLON.RenderingManager = RenderingManager;
  11503. })(BABYLON || (BABYLON = {}));
  11504. var BABYLON;
  11505. (function (BABYLON) {
  11506. var RenderingGroup = (function () {
  11507. function RenderingGroup(index, scene) {
  11508. this.index = index;
  11509. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11510. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11511. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11512. this._scene = scene;
  11513. }
  11514. RenderingGroup.prototype.render = function (customRenderFunction) {
  11515. if (customRenderFunction) {
  11516. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11517. return true;
  11518. }
  11519. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11520. return false;
  11521. }
  11522. var engine = this._scene.getEngine();
  11523. // Opaque
  11524. var subIndex;
  11525. var submesh;
  11526. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11527. submesh = this._opaqueSubMeshes.data[subIndex];
  11528. submesh.render(false);
  11529. }
  11530. // Alpha test
  11531. engine.setAlphaTesting(true);
  11532. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11533. submesh = this._alphaTestSubMeshes.data[subIndex];
  11534. submesh.render(false);
  11535. }
  11536. engine.setAlphaTesting(false);
  11537. // Transparent
  11538. if (this._transparentSubMeshes.length) {
  11539. // Sorting
  11540. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11541. submesh = this._transparentSubMeshes.data[subIndex];
  11542. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11543. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11544. }
  11545. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11546. sortedArray.sort(function (a, b) {
  11547. // Alpha index first
  11548. if (a._alphaIndex > b._alphaIndex) {
  11549. return 1;
  11550. }
  11551. if (a._alphaIndex < b._alphaIndex) {
  11552. return -1;
  11553. }
  11554. // Then distance to camera
  11555. if (a._distanceToCamera < b._distanceToCamera) {
  11556. return 1;
  11557. }
  11558. if (a._distanceToCamera > b._distanceToCamera) {
  11559. return -1;
  11560. }
  11561. return 0;
  11562. });
  11563. // Rendering
  11564. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11565. submesh = sortedArray[subIndex];
  11566. submesh.render(true);
  11567. }
  11568. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11569. }
  11570. return true;
  11571. };
  11572. RenderingGroup.prototype.prepare = function () {
  11573. this._opaqueSubMeshes.reset();
  11574. this._transparentSubMeshes.reset();
  11575. this._alphaTestSubMeshes.reset();
  11576. };
  11577. RenderingGroup.prototype.dispatch = function (subMesh) {
  11578. var material = subMesh.getMaterial();
  11579. var mesh = subMesh.getMesh();
  11580. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11581. this._transparentSubMeshes.push(subMesh);
  11582. }
  11583. else if (material.needAlphaTesting()) {
  11584. this._alphaTestSubMeshes.push(subMesh);
  11585. }
  11586. else {
  11587. this._opaqueSubMeshes.push(subMesh); // Opaque
  11588. }
  11589. };
  11590. return RenderingGroup;
  11591. })();
  11592. BABYLON.RenderingGroup = RenderingGroup;
  11593. })(BABYLON || (BABYLON = {}));
  11594. var BABYLON;
  11595. (function (BABYLON) {
  11596. /**
  11597. * Represents a scene to be rendered by the engine.
  11598. * @see http://doc.babylonjs.com/page.php?p=21911
  11599. */
  11600. var Scene = (function () {
  11601. /**
  11602. * @constructor
  11603. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11604. */
  11605. function Scene(engine) {
  11606. // Members
  11607. this.autoClear = true;
  11608. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11609. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11610. this.forceWireframe = false;
  11611. this.forcePointsCloud = false;
  11612. this.forceShowBoundingBoxes = false;
  11613. this.animationsEnabled = true;
  11614. this.constantlyUpdateMeshUnderPointer = false;
  11615. 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
  11616. // Fog
  11617. /**
  11618. * is fog enabled on this scene.
  11619. * @type {boolean}
  11620. */
  11621. this.fogEnabled = true;
  11622. this.fogMode = Scene.FOGMODE_NONE;
  11623. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11624. this.fogDensity = 0.1;
  11625. this.fogStart = 0;
  11626. this.fogEnd = 1000.0;
  11627. // Lights
  11628. /**
  11629. * is shadow enabled on this scene.
  11630. * @type {boolean}
  11631. */
  11632. this.shadowsEnabled = true;
  11633. /**
  11634. * is light enabled on this scene.
  11635. * @type {boolean}
  11636. */
  11637. this.lightsEnabled = true;
  11638. /**
  11639. * All of the lights added to this scene.
  11640. * @see BABYLON.Light
  11641. * @type {BABYLON.Light[]}
  11642. */
  11643. this.lights = new Array();
  11644. // Cameras
  11645. /**
  11646. * All of the cameras added to this scene.
  11647. * @see BABYLON.Camera
  11648. * @type {BABYLON.Camera[]}
  11649. */
  11650. this.cameras = new Array();
  11651. this.activeCameras = new Array();
  11652. // Meshes
  11653. /**
  11654. * All of the (abstract) meshes added to this scene.
  11655. * @see BABYLON.AbstractMesh
  11656. * @type {BABYLON.AbstractMesh[]}
  11657. */
  11658. this.meshes = new Array();
  11659. // Geometries
  11660. this._geometries = new Array();
  11661. this.materials = new Array();
  11662. this.multiMaterials = new Array();
  11663. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11664. // Textures
  11665. this.texturesEnabled = true;
  11666. this.textures = new Array();
  11667. // Particles
  11668. this.particlesEnabled = true;
  11669. this.particleSystems = new Array();
  11670. // Sprites
  11671. this.spritesEnabled = true;
  11672. this.spriteManagers = new Array();
  11673. // Layers
  11674. this.layers = new Array();
  11675. // Skeletons
  11676. this.skeletonsEnabled = true;
  11677. this.skeletons = new Array();
  11678. // Lens flares
  11679. this.lensFlaresEnabled = true;
  11680. this.lensFlareSystems = new Array();
  11681. // Collisions
  11682. this.collisionsEnabled = true;
  11683. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11684. // Postprocesses
  11685. this.postProcessesEnabled = true;
  11686. // Customs render targets
  11687. this.renderTargetsEnabled = true;
  11688. this.dumpNextRenderTargets = false;
  11689. this.customRenderTargets = new Array();
  11690. // Imported meshes
  11691. this.importedMeshesFiles = new Array();
  11692. // Probes
  11693. this.probesEnabled = true;
  11694. this.reflectionProbes = new Array();
  11695. this._actionManagers = new Array();
  11696. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11697. // Procedural textures
  11698. this.proceduralTexturesEnabled = true;
  11699. this._proceduralTextures = new Array();
  11700. this.soundTracks = new Array();
  11701. this._audioEnabled = true;
  11702. this._headphone = false;
  11703. this._totalVertices = 0;
  11704. this._activeIndices = 0;
  11705. this._activeParticles = 0;
  11706. this._lastFrameDuration = 0;
  11707. this._evaluateActiveMeshesDuration = 0;
  11708. this._renderTargetsDuration = 0;
  11709. this._particlesDuration = 0;
  11710. this._renderDuration = 0;
  11711. this._spritesDuration = 0;
  11712. this._animationRatio = 0;
  11713. this._renderId = 0;
  11714. this._executeWhenReadyTimeoutId = -1;
  11715. this._toBeDisposed = new BABYLON.SmartArray(256);
  11716. this._onReadyCallbacks = new Array();
  11717. this._pendingData = []; //ANY
  11718. this._onBeforeRenderCallbacks = new Array();
  11719. this._onAfterRenderCallbacks = new Array();
  11720. this._activeMeshes = new BABYLON.SmartArray(256);
  11721. this._processedMaterials = new BABYLON.SmartArray(256);
  11722. this._renderTargets = new BABYLON.SmartArray(256);
  11723. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11724. this._activeSkeletons = new BABYLON.SmartArray(32);
  11725. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  11726. this._activeBones = 0;
  11727. this._activeAnimatables = new Array();
  11728. this._transformMatrix = BABYLON.Matrix.Zero();
  11729. this._edgesRenderers = new BABYLON.SmartArray(16);
  11730. this._uniqueIdCounter = 0;
  11731. this._engine = engine;
  11732. engine.scenes.push(this);
  11733. this._renderingManager = new BABYLON.RenderingManager(this);
  11734. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11735. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11736. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11737. if (BABYLON.OutlineRenderer) {
  11738. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11739. }
  11740. this.attachControl();
  11741. this._debugLayer = new BABYLON.DebugLayer(this);
  11742. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11743. //simplification queue
  11744. if (BABYLON.SimplificationQueue) {
  11745. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11746. }
  11747. //collision coordinator initialization. For now legacy per default.
  11748. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11749. }
  11750. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11751. get: function () {
  11752. return Scene._FOGMODE_NONE;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11758. get: function () {
  11759. return Scene._FOGMODE_EXP;
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11765. get: function () {
  11766. return Scene._FOGMODE_EXP2;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11772. get: function () {
  11773. return Scene._FOGMODE_LINEAR;
  11774. },
  11775. enumerable: true,
  11776. configurable: true
  11777. });
  11778. Object.defineProperty(Scene.prototype, "debugLayer", {
  11779. // Properties
  11780. get: function () {
  11781. return this._debugLayer;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11787. get: function () {
  11788. return this._workerCollisions;
  11789. },
  11790. set: function (enabled) {
  11791. enabled = (enabled && !!Worker);
  11792. this._workerCollisions = enabled;
  11793. if (this.collisionCoordinator) {
  11794. this.collisionCoordinator.destroy();
  11795. }
  11796. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11797. this.collisionCoordinator.init(this);
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  11803. get: function () {
  11804. return this._selectionOctree;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11810. /**
  11811. * The mesh that is currently under the pointer.
  11812. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11813. */
  11814. get: function () {
  11815. return this._meshUnderPointer;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Scene.prototype, "pointerX", {
  11821. /**
  11822. * Current on-screen X position of the pointer
  11823. * @return {number} X position of the pointer
  11824. */
  11825. get: function () {
  11826. return this._pointerX;
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(Scene.prototype, "pointerY", {
  11832. /**
  11833. * Current on-screen Y position of the pointer
  11834. * @return {number} Y position of the pointer
  11835. */
  11836. get: function () {
  11837. return this._pointerY;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Scene.prototype.getCachedMaterial = function () {
  11843. return this._cachedMaterial;
  11844. };
  11845. Scene.prototype.getBoundingBoxRenderer = function () {
  11846. return this._boundingBoxRenderer;
  11847. };
  11848. Scene.prototype.getOutlineRenderer = function () {
  11849. return this._outlineRenderer;
  11850. };
  11851. Scene.prototype.getEngine = function () {
  11852. return this._engine;
  11853. };
  11854. Scene.prototype.getTotalVertices = function () {
  11855. return this._totalVertices;
  11856. };
  11857. Scene.prototype.getActiveIndices = function () {
  11858. return this._activeIndices;
  11859. };
  11860. Scene.prototype.getActiveParticles = function () {
  11861. return this._activeParticles;
  11862. };
  11863. Scene.prototype.getActiveBones = function () {
  11864. return this._activeBones;
  11865. };
  11866. // Stats
  11867. Scene.prototype.getLastFrameDuration = function () {
  11868. return this._lastFrameDuration;
  11869. };
  11870. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11871. return this._evaluateActiveMeshesDuration;
  11872. };
  11873. Scene.prototype.getActiveMeshes = function () {
  11874. return this._activeMeshes;
  11875. };
  11876. Scene.prototype.getRenderTargetsDuration = function () {
  11877. return this._renderTargetsDuration;
  11878. };
  11879. Scene.prototype.getRenderDuration = function () {
  11880. return this._renderDuration;
  11881. };
  11882. Scene.prototype.getParticlesDuration = function () {
  11883. return this._particlesDuration;
  11884. };
  11885. Scene.prototype.getSpritesDuration = function () {
  11886. return this._spritesDuration;
  11887. };
  11888. Scene.prototype.getAnimationRatio = function () {
  11889. return this._animationRatio;
  11890. };
  11891. Scene.prototype.getRenderId = function () {
  11892. return this._renderId;
  11893. };
  11894. Scene.prototype.incrementRenderId = function () {
  11895. this._renderId++;
  11896. };
  11897. Scene.prototype._updatePointerPosition = function (evt) {
  11898. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11899. this._pointerX = evt.clientX - canvasRect.left;
  11900. this._pointerY = evt.clientY - canvasRect.top;
  11901. if (this.cameraToUseForPointers) {
  11902. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11903. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11904. }
  11905. };
  11906. // Pointers handling
  11907. Scene.prototype.attachControl = function () {
  11908. var _this = this;
  11909. var spritePredicate = function (sprite) {
  11910. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  11911. };
  11912. this._onPointerMove = function (evt) {
  11913. var canvas = _this._engine.getRenderingCanvas();
  11914. _this._updatePointerPosition(evt);
  11915. // Meshes
  11916. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); }, false, _this.cameraToUseForPointers);
  11917. if (pickResult.hit && pickResult.pickedMesh) {
  11918. _this._meshUnderPointer = pickResult.pickedMesh;
  11919. _this.setPointerOverMesh(pickResult.pickedMesh);
  11920. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  11921. canvas.style.cursor = "pointer";
  11922. }
  11923. else {
  11924. canvas.style.cursor = "";
  11925. }
  11926. }
  11927. else {
  11928. // Sprites
  11929. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11930. if (pickResult.hit && pickResult.pickedSprite) {
  11931. canvas.style.cursor = "pointer";
  11932. return;
  11933. }
  11934. // Restore pointer
  11935. _this.setPointerOverMesh(null);
  11936. canvas.style.cursor = "";
  11937. _this._meshUnderPointer = null;
  11938. }
  11939. };
  11940. this._onPointerDown = function (evt) {
  11941. _this._updatePointerPosition(evt);
  11942. var predicate = null;
  11943. // Meshes
  11944. if (!_this.onPointerDown) {
  11945. predicate = function (mesh) {
  11946. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11947. };
  11948. }
  11949. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11950. if (pickResult.hit && pickResult.pickedMesh) {
  11951. if (pickResult.pickedMesh.actionManager) {
  11952. switch (evt.button) {
  11953. case 0:
  11954. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11955. break;
  11956. case 1:
  11957. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11958. break;
  11959. case 2:
  11960. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11961. break;
  11962. }
  11963. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11964. }
  11965. }
  11966. if (_this.onPointerDown) {
  11967. _this.onPointerDown(evt, pickResult);
  11968. }
  11969. // Sprites
  11970. if (_this.spriteManagers.length > 0) {
  11971. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11972. if (pickResult.hit && pickResult.pickedSprite) {
  11973. if (pickResult.pickedSprite.actionManager) {
  11974. switch (evt.button) {
  11975. case 0:
  11976. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11977. break;
  11978. case 1:
  11979. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11980. break;
  11981. case 2:
  11982. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11983. break;
  11984. }
  11985. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11986. }
  11987. }
  11988. }
  11989. };
  11990. this._onPointerUp = function (evt) {
  11991. var predicate = null;
  11992. _this._updatePointerPosition(evt);
  11993. if (!_this.onPointerUp) {
  11994. predicate = function (mesh) {
  11995. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11996. };
  11997. }
  11998. // Meshes
  11999. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12000. if (pickResult.hit && pickResult.pickedMesh) {
  12001. if (pickResult.pickedMesh.actionManager) {
  12002. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12003. }
  12004. }
  12005. if (_this.onPointerUp) {
  12006. _this.onPointerUp(evt, pickResult);
  12007. }
  12008. // Sprites
  12009. if (_this.spriteManagers.length > 0) {
  12010. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12011. if (pickResult.hit && pickResult.pickedSprite) {
  12012. if (pickResult.pickedSprite.actionManager) {
  12013. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12014. }
  12015. }
  12016. }
  12017. };
  12018. this._onKeyDown = function (evt) {
  12019. if (_this.actionManager) {
  12020. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12021. }
  12022. };
  12023. this._onKeyUp = function (evt) {
  12024. if (_this.actionManager) {
  12025. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12026. }
  12027. };
  12028. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12029. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12030. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12031. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12032. // Wheel
  12033. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12034. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12035. BABYLON.Tools.RegisterTopRootEvents([
  12036. { name: "keydown", handler: this._onKeyDown },
  12037. { name: "keyup", handler: this._onKeyUp }
  12038. ]);
  12039. };
  12040. Scene.prototype.detachControl = function () {
  12041. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12042. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12043. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12044. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12045. // Wheel
  12046. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12047. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12048. BABYLON.Tools.UnregisterTopRootEvents([
  12049. { name: "keydown", handler: this._onKeyDown },
  12050. { name: "keyup", handler: this._onKeyUp }
  12051. ]);
  12052. };
  12053. // Ready
  12054. Scene.prototype.isReady = function () {
  12055. if (this._pendingData.length > 0) {
  12056. return false;
  12057. }
  12058. var index;
  12059. for (index = 0; index < this._geometries.length; index++) {
  12060. var geometry = this._geometries[index];
  12061. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12062. return false;
  12063. }
  12064. }
  12065. for (index = 0; index < this.meshes.length; index++) {
  12066. var mesh = this.meshes[index];
  12067. if (!mesh.isReady()) {
  12068. return false;
  12069. }
  12070. var mat = mesh.material;
  12071. if (mat) {
  12072. if (!mat.isReady(mesh)) {
  12073. return false;
  12074. }
  12075. }
  12076. }
  12077. return true;
  12078. };
  12079. Scene.prototype.resetCachedMaterial = function () {
  12080. this._cachedMaterial = null;
  12081. };
  12082. Scene.prototype.registerBeforeRender = function (func) {
  12083. this._onBeforeRenderCallbacks.push(func);
  12084. };
  12085. Scene.prototype.unregisterBeforeRender = function (func) {
  12086. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12087. if (index > -1) {
  12088. this._onBeforeRenderCallbacks.splice(index, 1);
  12089. }
  12090. };
  12091. Scene.prototype.registerAfterRender = function (func) {
  12092. this._onAfterRenderCallbacks.push(func);
  12093. };
  12094. Scene.prototype.unregisterAfterRender = function (func) {
  12095. var index = this._onAfterRenderCallbacks.indexOf(func);
  12096. if (index > -1) {
  12097. this._onAfterRenderCallbacks.splice(index, 1);
  12098. }
  12099. };
  12100. Scene.prototype._addPendingData = function (data) {
  12101. this._pendingData.push(data);
  12102. };
  12103. Scene.prototype._removePendingData = function (data) {
  12104. var index = this._pendingData.indexOf(data);
  12105. if (index !== -1) {
  12106. this._pendingData.splice(index, 1);
  12107. }
  12108. };
  12109. Scene.prototype.getWaitingItemsCount = function () {
  12110. return this._pendingData.length;
  12111. };
  12112. /**
  12113. * Registers a function to be executed when the scene is ready.
  12114. * @param {Function} func - the function to be executed.
  12115. */
  12116. Scene.prototype.executeWhenReady = function (func) {
  12117. var _this = this;
  12118. this._onReadyCallbacks.push(func);
  12119. if (this._executeWhenReadyTimeoutId !== -1) {
  12120. return;
  12121. }
  12122. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12123. _this._checkIsReady();
  12124. }, 150);
  12125. };
  12126. Scene.prototype._checkIsReady = function () {
  12127. var _this = this;
  12128. if (this.isReady()) {
  12129. this._onReadyCallbacks.forEach(function (func) {
  12130. func();
  12131. });
  12132. this._onReadyCallbacks = [];
  12133. this._executeWhenReadyTimeoutId = -1;
  12134. return;
  12135. }
  12136. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12137. _this._checkIsReady();
  12138. }, 150);
  12139. };
  12140. // Animations
  12141. /**
  12142. * Will start the animation sequence of a given target
  12143. * @param target - the target
  12144. * @param {number} from - from which frame should animation start
  12145. * @param {number} to - till which frame should animation run.
  12146. * @param {boolean} [loop] - should the animation loop
  12147. * @param {number} [speedRatio] - the speed in which to run the animation
  12148. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12149. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12150. * @return {BABYLON.Animatable} the animatable object created for this animation
  12151. * @see BABYLON.Animatable
  12152. * @see http://doc.babylonjs.com/page.php?p=22081
  12153. */
  12154. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12155. if (speedRatio === void 0) { speedRatio = 1.0; }
  12156. this.stopAnimation(target);
  12157. if (!animatable) {
  12158. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12159. }
  12160. // Local animations
  12161. if (target.animations) {
  12162. animatable.appendAnimations(target, target.animations);
  12163. }
  12164. // Children animations
  12165. if (target.getAnimatables) {
  12166. var animatables = target.getAnimatables();
  12167. for (var index = 0; index < animatables.length; index++) {
  12168. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12169. }
  12170. }
  12171. return animatable;
  12172. };
  12173. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12174. if (speedRatio === undefined) {
  12175. speedRatio = 1.0;
  12176. }
  12177. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12178. return animatable;
  12179. };
  12180. Scene.prototype.getAnimatableByTarget = function (target) {
  12181. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12182. if (this._activeAnimatables[index].target === target) {
  12183. return this._activeAnimatables[index];
  12184. }
  12185. }
  12186. return null;
  12187. };
  12188. /**
  12189. * Will stop the animation of the given target
  12190. * @param target - the target
  12191. * @see beginAnimation
  12192. */
  12193. Scene.prototype.stopAnimation = function (target) {
  12194. var animatable = this.getAnimatableByTarget(target);
  12195. if (animatable) {
  12196. animatable.stop();
  12197. }
  12198. };
  12199. Scene.prototype._animate = function () {
  12200. if (!this.animationsEnabled) {
  12201. return;
  12202. }
  12203. if (!this._animationStartDate) {
  12204. this._animationStartDate = BABYLON.Tools.Now;
  12205. }
  12206. // Getting time
  12207. var now = BABYLON.Tools.Now;
  12208. var delay = now - this._animationStartDate;
  12209. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12210. this._activeAnimatables[index]._animate(delay);
  12211. }
  12212. };
  12213. // Matrix
  12214. Scene.prototype.getViewMatrix = function () {
  12215. return this._viewMatrix;
  12216. };
  12217. Scene.prototype.getProjectionMatrix = function () {
  12218. return this._projectionMatrix;
  12219. };
  12220. Scene.prototype.getTransformMatrix = function () {
  12221. return this._transformMatrix;
  12222. };
  12223. Scene.prototype.setTransformMatrix = function (view, projection) {
  12224. this._viewMatrix = view;
  12225. this._projectionMatrix = projection;
  12226. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12227. };
  12228. // Methods
  12229. Scene.prototype.addMesh = function (newMesh) {
  12230. newMesh.uniqueId = this._uniqueIdCounter++;
  12231. var position = this.meshes.push(newMesh);
  12232. //notify the collision coordinator
  12233. this.collisionCoordinator.onMeshAdded(newMesh);
  12234. if (this.onNewMeshAdded) {
  12235. this.onNewMeshAdded(newMesh, position, this);
  12236. }
  12237. };
  12238. Scene.prototype.removeMesh = function (toRemove) {
  12239. var index = this.meshes.indexOf(toRemove);
  12240. if (index !== -1) {
  12241. // Remove from the scene if mesh found
  12242. this.meshes.splice(index, 1);
  12243. }
  12244. //notify the collision coordinator
  12245. this.collisionCoordinator.onMeshRemoved(toRemove);
  12246. if (this.onMeshRemoved) {
  12247. this.onMeshRemoved(toRemove);
  12248. }
  12249. return index;
  12250. };
  12251. Scene.prototype.removeLight = function (toRemove) {
  12252. var index = this.lights.indexOf(toRemove);
  12253. if (index !== -1) {
  12254. // Remove from the scene if mesh found
  12255. this.lights.splice(index, 1);
  12256. }
  12257. if (this.onLightRemoved) {
  12258. this.onLightRemoved(toRemove);
  12259. }
  12260. return index;
  12261. };
  12262. Scene.prototype.removeCamera = function (toRemove) {
  12263. var index = this.cameras.indexOf(toRemove);
  12264. if (index !== -1) {
  12265. // Remove from the scene if mesh found
  12266. this.cameras.splice(index, 1);
  12267. }
  12268. // Remove from activeCameras
  12269. var index2 = this.activeCameras.indexOf(toRemove);
  12270. if (index2 !== -1) {
  12271. // Remove from the scene if mesh found
  12272. this.activeCameras.splice(index2, 1);
  12273. }
  12274. // Reset the activeCamera
  12275. if (this.activeCamera === toRemove) {
  12276. if (this.cameras.length > 0) {
  12277. this.activeCamera = this.cameras[0];
  12278. }
  12279. else {
  12280. this.activeCamera = null;
  12281. }
  12282. }
  12283. if (this.onCameraRemoved) {
  12284. this.onCameraRemoved(toRemove);
  12285. }
  12286. return index;
  12287. };
  12288. Scene.prototype.addLight = function (newLight) {
  12289. newLight.uniqueId = this._uniqueIdCounter++;
  12290. var position = this.lights.push(newLight);
  12291. if (this.onNewLightAdded) {
  12292. this.onNewLightAdded(newLight, position, this);
  12293. }
  12294. };
  12295. Scene.prototype.addCamera = function (newCamera) {
  12296. newCamera.uniqueId = this._uniqueIdCounter++;
  12297. var position = this.cameras.push(newCamera);
  12298. if (this.onNewCameraAdded) {
  12299. this.onNewCameraAdded(newCamera, position, this);
  12300. }
  12301. };
  12302. /**
  12303. * sets the active camera of the scene using its ID
  12304. * @param {string} id - the camera's ID
  12305. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12306. * @see activeCamera
  12307. */
  12308. Scene.prototype.setActiveCameraByID = function (id) {
  12309. var camera = this.getCameraByID(id);
  12310. if (camera) {
  12311. this.activeCamera = camera;
  12312. return camera;
  12313. }
  12314. return null;
  12315. };
  12316. /**
  12317. * sets the active camera of the scene using its name
  12318. * @param {string} name - the camera's name
  12319. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12320. * @see activeCamera
  12321. */
  12322. Scene.prototype.setActiveCameraByName = function (name) {
  12323. var camera = this.getCameraByName(name);
  12324. if (camera) {
  12325. this.activeCamera = camera;
  12326. return camera;
  12327. }
  12328. return null;
  12329. };
  12330. /**
  12331. * get a material using its id
  12332. * @param {string} the material's ID
  12333. * @return {BABYLON.Material|null} the material or null if none found.
  12334. */
  12335. Scene.prototype.getMaterialByID = function (id) {
  12336. for (var index = 0; index < this.materials.length; index++) {
  12337. if (this.materials[index].id === id) {
  12338. return this.materials[index];
  12339. }
  12340. }
  12341. return null;
  12342. };
  12343. /**
  12344. * get a material using its name
  12345. * @param {string} the material's name
  12346. * @return {BABYLON.Material|null} the material or null if none found.
  12347. */
  12348. Scene.prototype.getMaterialByName = function (name) {
  12349. for (var index = 0; index < this.materials.length; index++) {
  12350. if (this.materials[index].name === name) {
  12351. return this.materials[index];
  12352. }
  12353. }
  12354. return null;
  12355. };
  12356. Scene.prototype.getLensFlareSystemByName = function (name) {
  12357. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12358. if (this.lensFlareSystems[index].name === name) {
  12359. return this.lensFlareSystems[index];
  12360. }
  12361. }
  12362. return null;
  12363. };
  12364. Scene.prototype.getCameraByID = function (id) {
  12365. for (var index = 0; index < this.cameras.length; index++) {
  12366. if (this.cameras[index].id === id) {
  12367. return this.cameras[index];
  12368. }
  12369. }
  12370. return null;
  12371. };
  12372. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12373. for (var index = 0; index < this.cameras.length; index++) {
  12374. if (this.cameras[index].uniqueId === uniqueId) {
  12375. return this.cameras[index];
  12376. }
  12377. }
  12378. return null;
  12379. };
  12380. /**
  12381. * get a camera using its name
  12382. * @param {string} the camera's name
  12383. * @return {BABYLON.Camera|null} the camera or null if none found.
  12384. */
  12385. Scene.prototype.getCameraByName = function (name) {
  12386. for (var index = 0; index < this.cameras.length; index++) {
  12387. if (this.cameras[index].name === name) {
  12388. return this.cameras[index];
  12389. }
  12390. }
  12391. return null;
  12392. };
  12393. /**
  12394. * get a light node using its name
  12395. * @param {string} the light's name
  12396. * @return {BABYLON.Light|null} the light or null if none found.
  12397. */
  12398. Scene.prototype.getLightByName = function (name) {
  12399. for (var index = 0; index < this.lights.length; index++) {
  12400. if (this.lights[index].name === name) {
  12401. return this.lights[index];
  12402. }
  12403. }
  12404. return null;
  12405. };
  12406. /**
  12407. * get a light node using its ID
  12408. * @param {string} the light's id
  12409. * @return {BABYLON.Light|null} the light or null if none found.
  12410. */
  12411. Scene.prototype.getLightByID = function (id) {
  12412. for (var index = 0; index < this.lights.length; index++) {
  12413. if (this.lights[index].id === id) {
  12414. return this.lights[index];
  12415. }
  12416. }
  12417. return null;
  12418. };
  12419. /**
  12420. * get a light node using its scene-generated unique ID
  12421. * @param {number} the light's unique id
  12422. * @return {BABYLON.Light|null} the light or null if none found.
  12423. */
  12424. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12425. for (var index = 0; index < this.lights.length; index++) {
  12426. if (this.lights[index].uniqueId === uniqueId) {
  12427. return this.lights[index];
  12428. }
  12429. }
  12430. return null;
  12431. };
  12432. /**
  12433. * get a geometry using its ID
  12434. * @param {string} the geometry's id
  12435. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12436. */
  12437. Scene.prototype.getGeometryByID = function (id) {
  12438. for (var index = 0; index < this._geometries.length; index++) {
  12439. if (this._geometries[index].id === id) {
  12440. return this._geometries[index];
  12441. }
  12442. }
  12443. return null;
  12444. };
  12445. /**
  12446. * add a new geometry to this scene.
  12447. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12448. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12449. * @return {boolean} was the geometry added or not
  12450. */
  12451. Scene.prototype.pushGeometry = function (geometry, force) {
  12452. if (!force && this.getGeometryByID(geometry.id)) {
  12453. return false;
  12454. }
  12455. this._geometries.push(geometry);
  12456. //notify the collision coordinator
  12457. this.collisionCoordinator.onGeometryAdded(geometry);
  12458. if (this.onGeometryAdded) {
  12459. this.onGeometryAdded(geometry);
  12460. }
  12461. return true;
  12462. };
  12463. /**
  12464. * Removes an existing geometry
  12465. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12466. * @return {boolean} was the geometry removed or not
  12467. */
  12468. Scene.prototype.removeGeometry = function (geometry) {
  12469. var index = this._geometries.indexOf(geometry);
  12470. if (index > -1) {
  12471. this._geometries.splice(index, 1);
  12472. //notify the collision coordinator
  12473. this.collisionCoordinator.onGeometryDeleted(geometry);
  12474. if (this.onGeometryRemoved) {
  12475. this.onGeometryRemoved(geometry);
  12476. }
  12477. return true;
  12478. }
  12479. return false;
  12480. };
  12481. Scene.prototype.getGeometries = function () {
  12482. return this._geometries;
  12483. };
  12484. /**
  12485. * Get the first added mesh found of a given ID
  12486. * @param {string} id - the id to search for
  12487. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12488. */
  12489. Scene.prototype.getMeshByID = function (id) {
  12490. for (var index = 0; index < this.meshes.length; index++) {
  12491. if (this.meshes[index].id === id) {
  12492. return this.meshes[index];
  12493. }
  12494. }
  12495. return null;
  12496. };
  12497. /**
  12498. * Get a mesh with its auto-generated unique id
  12499. * @param {number} uniqueId - the unique id to search for
  12500. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12501. */
  12502. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12503. for (var index = 0; index < this.meshes.length; index++) {
  12504. if (this.meshes[index].uniqueId === uniqueId) {
  12505. return this.meshes[index];
  12506. }
  12507. }
  12508. return null;
  12509. };
  12510. /**
  12511. * Get a the last added mesh found of a given ID
  12512. * @param {string} id - the id to search for
  12513. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12514. */
  12515. Scene.prototype.getLastMeshByID = function (id) {
  12516. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12517. if (this.meshes[index].id === id) {
  12518. return this.meshes[index];
  12519. }
  12520. }
  12521. return null;
  12522. };
  12523. /**
  12524. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12525. * @param {string} id - the id to search for
  12526. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12527. */
  12528. Scene.prototype.getLastEntryByID = function (id) {
  12529. var index;
  12530. for (index = this.meshes.length - 1; index >= 0; index--) {
  12531. if (this.meshes[index].id === id) {
  12532. return this.meshes[index];
  12533. }
  12534. }
  12535. for (index = this.cameras.length - 1; index >= 0; index--) {
  12536. if (this.cameras[index].id === id) {
  12537. return this.cameras[index];
  12538. }
  12539. }
  12540. for (index = this.lights.length - 1; index >= 0; index--) {
  12541. if (this.lights[index].id === id) {
  12542. return this.lights[index];
  12543. }
  12544. }
  12545. return null;
  12546. };
  12547. Scene.prototype.getNodeByID = function (id) {
  12548. var mesh = this.getMeshByID(id);
  12549. if (mesh) {
  12550. return mesh;
  12551. }
  12552. var light = this.getLightByID(id);
  12553. if (light) {
  12554. return light;
  12555. }
  12556. return this.getCameraByID(id);
  12557. };
  12558. Scene.prototype.getNodeByName = function (name) {
  12559. var mesh = this.getMeshByName(name);
  12560. if (mesh) {
  12561. return mesh;
  12562. }
  12563. var light = this.getLightByName(name);
  12564. if (light) {
  12565. return light;
  12566. }
  12567. return this.getCameraByName(name);
  12568. };
  12569. Scene.prototype.getMeshByName = function (name) {
  12570. for (var index = 0; index < this.meshes.length; index++) {
  12571. if (this.meshes[index].name === name) {
  12572. return this.meshes[index];
  12573. }
  12574. }
  12575. return null;
  12576. };
  12577. Scene.prototype.getSoundByName = function (name) {
  12578. var index;
  12579. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12580. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12581. return this.mainSoundTrack.soundCollection[index];
  12582. }
  12583. }
  12584. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12585. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12586. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12587. return this.soundTracks[sdIndex].soundCollection[index];
  12588. }
  12589. }
  12590. }
  12591. return null;
  12592. };
  12593. Scene.prototype.getLastSkeletonByID = function (id) {
  12594. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12595. if (this.skeletons[index].id === id) {
  12596. return this.skeletons[index];
  12597. }
  12598. }
  12599. return null;
  12600. };
  12601. Scene.prototype.getSkeletonById = function (id) {
  12602. for (var index = 0; index < this.skeletons.length; index++) {
  12603. if (this.skeletons[index].id === id) {
  12604. return this.skeletons[index];
  12605. }
  12606. }
  12607. return null;
  12608. };
  12609. Scene.prototype.getSkeletonByName = function (name) {
  12610. for (var index = 0; index < this.skeletons.length; index++) {
  12611. if (this.skeletons[index].name === name) {
  12612. return this.skeletons[index];
  12613. }
  12614. }
  12615. return null;
  12616. };
  12617. Scene.prototype.isActiveMesh = function (mesh) {
  12618. return (this._activeMeshes.indexOf(mesh) !== -1);
  12619. };
  12620. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12621. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12622. var material = subMesh.getMaterial();
  12623. if (mesh.showSubMeshesBoundingBox) {
  12624. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12625. }
  12626. if (material) {
  12627. // Render targets
  12628. if (material.getRenderTargetTextures) {
  12629. if (this._processedMaterials.indexOf(material) === -1) {
  12630. this._processedMaterials.push(material);
  12631. this._renderTargets.concat(material.getRenderTargetTextures());
  12632. }
  12633. }
  12634. // Dispatch
  12635. this._activeIndices += subMesh.indexCount;
  12636. this._renderingManager.dispatch(subMesh);
  12637. }
  12638. }
  12639. };
  12640. Scene.prototype._evaluateActiveMeshes = function () {
  12641. this.activeCamera._activeMeshes.reset();
  12642. this._activeMeshes.reset();
  12643. this._renderingManager.reset();
  12644. this._processedMaterials.reset();
  12645. this._activeParticleSystems.reset();
  12646. this._activeSkeletons.reset();
  12647. this._softwareSkinnedMeshes.reset();
  12648. this._boundingBoxRenderer.reset();
  12649. this._edgesRenderers.reset();
  12650. if (!this._frustumPlanes) {
  12651. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12652. }
  12653. else {
  12654. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12655. }
  12656. // Meshes
  12657. var meshes;
  12658. var len;
  12659. if (this._selectionOctree) {
  12660. var selection = this._selectionOctree.select(this._frustumPlanes);
  12661. meshes = selection.data;
  12662. len = selection.length;
  12663. }
  12664. else {
  12665. len = this.meshes.length;
  12666. meshes = this.meshes;
  12667. }
  12668. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12669. var mesh = meshes[meshIndex];
  12670. if (mesh.isBlocked) {
  12671. continue;
  12672. }
  12673. this._totalVertices += mesh.getTotalVertices();
  12674. if (!mesh.isReady() || !mesh.isEnabled()) {
  12675. continue;
  12676. }
  12677. mesh.computeWorldMatrix();
  12678. // Intersections
  12679. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12680. this._meshesForIntersections.pushNoDuplicate(mesh);
  12681. }
  12682. // Switch to current LOD
  12683. var meshLOD = mesh.getLOD(this.activeCamera);
  12684. if (!meshLOD) {
  12685. continue;
  12686. }
  12687. mesh._preActivate();
  12688. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12689. this._activeMeshes.push(mesh);
  12690. this.activeCamera._activeMeshes.push(mesh);
  12691. mesh._activate(this._renderId);
  12692. this._activeMesh(meshLOD);
  12693. }
  12694. }
  12695. // Particle systems
  12696. var beforeParticlesDate = BABYLON.Tools.Now;
  12697. if (this.particlesEnabled) {
  12698. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12699. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12700. var particleSystem = this.particleSystems[particleIndex];
  12701. if (!particleSystem.isStarted()) {
  12702. continue;
  12703. }
  12704. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12705. this._activeParticleSystems.push(particleSystem);
  12706. particleSystem.animate();
  12707. }
  12708. }
  12709. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12710. }
  12711. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12712. };
  12713. Scene.prototype._activeMesh = function (mesh) {
  12714. if (mesh.skeleton && this.skeletonsEnabled) {
  12715. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12716. if (!mesh.computeBonesUsingShaders) {
  12717. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  12718. }
  12719. }
  12720. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12721. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12722. }
  12723. if (mesh._edgesRenderer) {
  12724. this._edgesRenderers.push(mesh._edgesRenderer);
  12725. }
  12726. if (mesh && mesh.subMeshes) {
  12727. // Submeshes Octrees
  12728. var len;
  12729. var subMeshes;
  12730. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12731. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12732. len = intersections.length;
  12733. subMeshes = intersections.data;
  12734. }
  12735. else {
  12736. subMeshes = mesh.subMeshes;
  12737. len = subMeshes.length;
  12738. }
  12739. for (var subIndex = 0; subIndex < len; subIndex++) {
  12740. var subMesh = subMeshes[subIndex];
  12741. this._evaluateSubMesh(subMesh, mesh);
  12742. }
  12743. }
  12744. };
  12745. Scene.prototype.updateTransformMatrix = function (force) {
  12746. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12747. };
  12748. Scene.prototype._renderForCamera = function (camera) {
  12749. var engine = this._engine;
  12750. this.activeCamera = camera;
  12751. if (!this.activeCamera)
  12752. throw new Error("Active camera not set");
  12753. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12754. // Viewport
  12755. engine.setViewport(this.activeCamera.viewport);
  12756. // Camera
  12757. this.resetCachedMaterial();
  12758. this._renderId++;
  12759. this.updateTransformMatrix();
  12760. if (this.beforeCameraRender) {
  12761. this.beforeCameraRender(this.activeCamera);
  12762. }
  12763. // Meshes
  12764. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12765. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12766. this._evaluateActiveMeshes();
  12767. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12768. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12769. // Skeletons
  12770. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12771. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12772. skeleton.prepare();
  12773. }
  12774. // Software skinning
  12775. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  12776. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  12777. mesh.applySkeleton(mesh.skeleton);
  12778. }
  12779. // Render targets
  12780. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12781. if (this.renderTargetsEnabled) {
  12782. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12783. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12784. var renderTarget = this._renderTargets.data[renderIndex];
  12785. if (renderTarget._shouldRender()) {
  12786. this._renderId++;
  12787. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12788. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12789. }
  12790. }
  12791. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12792. this._renderId++;
  12793. }
  12794. if (this._renderTargets.length > 0) {
  12795. engine.restoreDefaultFramebuffer();
  12796. }
  12797. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12798. // Prepare Frame
  12799. this.postProcessManager._prepareFrame();
  12800. var beforeRenderDate = BABYLON.Tools.Now;
  12801. // Backgrounds
  12802. var layerIndex;
  12803. var layer;
  12804. if (this.layers.length) {
  12805. engine.setDepthBuffer(false);
  12806. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12807. layer = this.layers[layerIndex];
  12808. if (layer.isBackground) {
  12809. layer.render();
  12810. }
  12811. }
  12812. engine.setDepthBuffer(true);
  12813. }
  12814. // Render
  12815. BABYLON.Tools.StartPerformanceCounter("Main render");
  12816. this._renderingManager.render(null, null, true, true);
  12817. BABYLON.Tools.EndPerformanceCounter("Main render");
  12818. // Bounding boxes
  12819. this._boundingBoxRenderer.render();
  12820. // Edges
  12821. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  12822. this._edgesRenderers.data[edgesRendererIndex].render();
  12823. }
  12824. // Lens flares
  12825. if (this.lensFlaresEnabled) {
  12826. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12827. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12828. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  12829. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  12830. lensFlareSystem.render();
  12831. }
  12832. }
  12833. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12834. }
  12835. // Foregrounds
  12836. if (this.layers.length) {
  12837. engine.setDepthBuffer(false);
  12838. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12839. layer = this.layers[layerIndex];
  12840. if (!layer.isBackground) {
  12841. layer.render();
  12842. }
  12843. }
  12844. engine.setDepthBuffer(true);
  12845. }
  12846. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12847. // Finalize frame
  12848. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12849. // Update camera
  12850. this.activeCamera._updateFromScene();
  12851. // Reset some special arrays
  12852. this._renderTargets.reset();
  12853. if (this.afterCameraRender) {
  12854. this.afterCameraRender(this.activeCamera);
  12855. }
  12856. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12857. };
  12858. Scene.prototype._processSubCameras = function (camera) {
  12859. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  12860. this._renderForCamera(camera);
  12861. return;
  12862. }
  12863. // rig cameras
  12864. for (var index = 0; index < camera._rigCameras.length; index++) {
  12865. this._renderForCamera(camera._rigCameras[index]);
  12866. }
  12867. this.activeCamera = camera;
  12868. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12869. // Update camera
  12870. this.activeCamera._updateFromScene();
  12871. };
  12872. Scene.prototype._checkIntersections = function () {
  12873. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12874. var sourceMesh = this._meshesForIntersections.data[index];
  12875. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12876. var action = sourceMesh.actionManager.actions[actionIndex];
  12877. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12878. var parameters = action.getTriggerParameter();
  12879. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12880. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12881. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12882. if (areIntersecting && currentIntersectionInProgress === -1) {
  12883. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12884. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12885. sourceMesh._intersectionsInProgress.push(otherMesh);
  12886. }
  12887. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12888. sourceMesh._intersectionsInProgress.push(otherMesh);
  12889. }
  12890. }
  12891. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12892. //They intersected, and now they don't.
  12893. //is this trigger an exit trigger? execute an event.
  12894. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12895. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12896. }
  12897. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12898. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12899. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12900. }
  12901. }
  12902. }
  12903. }
  12904. }
  12905. };
  12906. Scene.prototype.render = function () {
  12907. var startDate = BABYLON.Tools.Now;
  12908. this._particlesDuration = 0;
  12909. this._spritesDuration = 0;
  12910. this._activeParticles = 0;
  12911. this._renderDuration = 0;
  12912. this._renderTargetsDuration = 0;
  12913. this._evaluateActiveMeshesDuration = 0;
  12914. this._totalVertices = 0;
  12915. this._activeIndices = 0;
  12916. this._activeBones = 0;
  12917. this.getEngine().resetDrawCalls();
  12918. this._meshesForIntersections.reset();
  12919. this.resetCachedMaterial();
  12920. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12921. // Actions
  12922. if (this.actionManager) {
  12923. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12924. }
  12925. //Simplification Queue
  12926. if (this.simplificationQueue && !this.simplificationQueue.running) {
  12927. this.simplificationQueue.executeNext();
  12928. }
  12929. // Animations
  12930. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12931. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12932. this._animate();
  12933. // Physics
  12934. if (this._physicsEngine) {
  12935. BABYLON.Tools.StartPerformanceCounter("Physics");
  12936. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12937. BABYLON.Tools.EndPerformanceCounter("Physics");
  12938. }
  12939. // Before render
  12940. if (this.beforeRender) {
  12941. this.beforeRender();
  12942. }
  12943. var callbackIndex;
  12944. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12945. this._onBeforeRenderCallbacks[callbackIndex]();
  12946. }
  12947. // Customs render targets
  12948. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12949. var engine = this.getEngine();
  12950. var currentActiveCamera = this.activeCamera;
  12951. if (this.renderTargetsEnabled) {
  12952. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12953. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12954. var renderTarget = this.customRenderTargets[customIndex];
  12955. if (renderTarget._shouldRender()) {
  12956. this._renderId++;
  12957. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12958. if (!this.activeCamera)
  12959. throw new Error("Active camera not set");
  12960. // Viewport
  12961. engine.setViewport(this.activeCamera.viewport);
  12962. // Camera
  12963. this.updateTransformMatrix();
  12964. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12965. }
  12966. }
  12967. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12968. this._renderId++;
  12969. }
  12970. if (this.customRenderTargets.length > 0) {
  12971. engine.restoreDefaultFramebuffer();
  12972. }
  12973. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12974. this.activeCamera = currentActiveCamera;
  12975. // Procedural textures
  12976. if (this.proceduralTexturesEnabled) {
  12977. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12978. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12979. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12980. if (proceduralTexture._shouldRender()) {
  12981. proceduralTexture.render();
  12982. }
  12983. }
  12984. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12985. }
  12986. // Clear
  12987. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12988. // Shadows
  12989. if (this.shadowsEnabled) {
  12990. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12991. var light = this.lights[lightIndex];
  12992. var shadowGenerator = light.getShadowGenerator();
  12993. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12994. this._renderTargets.push(shadowGenerator.getShadowMap());
  12995. }
  12996. }
  12997. }
  12998. // Depth renderer
  12999. if (this._depthRenderer) {
  13000. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13001. }
  13002. // RenderPipeline
  13003. this.postProcessRenderPipelineManager.update();
  13004. // Multi-cameras?
  13005. if (this.activeCameras.length > 0) {
  13006. var currentRenderId = this._renderId;
  13007. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13008. this._renderId = currentRenderId;
  13009. this._processSubCameras(this.activeCameras[cameraIndex]);
  13010. }
  13011. }
  13012. else {
  13013. if (!this.activeCamera) {
  13014. throw new Error("No camera defined");
  13015. }
  13016. this._processSubCameras(this.activeCamera);
  13017. }
  13018. // Intersection checks
  13019. this._checkIntersections();
  13020. // Update the audio listener attached to the camera
  13021. this._updateAudioParameters();
  13022. // After render
  13023. if (this.afterRender) {
  13024. this.afterRender();
  13025. }
  13026. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13027. this._onAfterRenderCallbacks[callbackIndex]();
  13028. }
  13029. // Cleaning
  13030. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13031. this._toBeDisposed.data[index].dispose();
  13032. this._toBeDisposed[index] = null;
  13033. }
  13034. this._toBeDisposed.reset();
  13035. if (this.dumpNextRenderTargets) {
  13036. this.dumpNextRenderTargets = false;
  13037. }
  13038. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13039. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13040. };
  13041. Scene.prototype._updateAudioParameters = function () {
  13042. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13043. return;
  13044. }
  13045. var listeningCamera;
  13046. var audioEngine = BABYLON.Engine.audioEngine;
  13047. if (this.activeCameras.length > 0) {
  13048. listeningCamera = this.activeCameras[0];
  13049. }
  13050. else {
  13051. listeningCamera = this.activeCamera;
  13052. }
  13053. if (listeningCamera && audioEngine.canUseWebAudio) {
  13054. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13055. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13056. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13057. cameraDirection.normalize();
  13058. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13059. var i;
  13060. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13061. var sound = this.mainSoundTrack.soundCollection[i];
  13062. if (sound.useCustomAttenuation) {
  13063. sound.updateDistanceFromListener();
  13064. }
  13065. }
  13066. for (i = 0; i < this.soundTracks.length; i++) {
  13067. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13068. sound = this.soundTracks[i].soundCollection[j];
  13069. if (sound.useCustomAttenuation) {
  13070. sound.updateDistanceFromListener();
  13071. }
  13072. }
  13073. }
  13074. }
  13075. };
  13076. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13077. // Audio
  13078. get: function () {
  13079. return this._audioEnabled;
  13080. },
  13081. set: function (value) {
  13082. this._audioEnabled = value;
  13083. if (this._audioEnabled) {
  13084. this._enableAudio();
  13085. }
  13086. else {
  13087. this._disableAudio();
  13088. }
  13089. },
  13090. enumerable: true,
  13091. configurable: true
  13092. });
  13093. Scene.prototype._disableAudio = function () {
  13094. var i;
  13095. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13096. this.mainSoundTrack.soundCollection[i].pause();
  13097. }
  13098. for (i = 0; i < this.soundTracks.length; i++) {
  13099. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13100. this.soundTracks[i].soundCollection[j].pause();
  13101. }
  13102. }
  13103. };
  13104. Scene.prototype._enableAudio = function () {
  13105. var i;
  13106. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13107. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13108. this.mainSoundTrack.soundCollection[i].play();
  13109. }
  13110. }
  13111. for (i = 0; i < this.soundTracks.length; i++) {
  13112. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13113. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13114. this.soundTracks[i].soundCollection[j].play();
  13115. }
  13116. }
  13117. }
  13118. };
  13119. Object.defineProperty(Scene.prototype, "headphone", {
  13120. get: function () {
  13121. return this._headphone;
  13122. },
  13123. set: function (value) {
  13124. this._headphone = value;
  13125. if (this._headphone) {
  13126. this._switchAudioModeForHeadphones();
  13127. }
  13128. else {
  13129. this._switchAudioModeForNormalSpeakers();
  13130. }
  13131. },
  13132. enumerable: true,
  13133. configurable: true
  13134. });
  13135. Scene.prototype._switchAudioModeForHeadphones = function () {
  13136. this.mainSoundTrack.switchPanningModelToHRTF();
  13137. for (var i = 0; i < this.soundTracks.length; i++) {
  13138. this.soundTracks[i].switchPanningModelToHRTF();
  13139. }
  13140. };
  13141. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13142. this.mainSoundTrack.switchPanningModelToEqualPower();
  13143. for (var i = 0; i < this.soundTracks.length; i++) {
  13144. this.soundTracks[i].switchPanningModelToEqualPower();
  13145. }
  13146. };
  13147. Scene.prototype.enableDepthRenderer = function () {
  13148. if (this._depthRenderer) {
  13149. return this._depthRenderer;
  13150. }
  13151. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13152. return this._depthRenderer;
  13153. };
  13154. Scene.prototype.disableDepthRenderer = function () {
  13155. if (!this._depthRenderer) {
  13156. return;
  13157. }
  13158. this._depthRenderer.dispose();
  13159. this._depthRenderer = null;
  13160. };
  13161. Scene.prototype.dispose = function () {
  13162. this.beforeRender = null;
  13163. this.afterRender = null;
  13164. this.skeletons = [];
  13165. this._boundingBoxRenderer.dispose();
  13166. if (this._depthRenderer) {
  13167. this._depthRenderer.dispose();
  13168. }
  13169. // Debug layer
  13170. this.debugLayer.hide();
  13171. // Events
  13172. if (this.onDispose) {
  13173. this.onDispose();
  13174. }
  13175. this._onBeforeRenderCallbacks = [];
  13176. this._onAfterRenderCallbacks = [];
  13177. this.detachControl();
  13178. // Release sounds & sounds tracks
  13179. this.disposeSounds();
  13180. // Detach cameras
  13181. var canvas = this._engine.getRenderingCanvas();
  13182. var index;
  13183. for (index = 0; index < this.cameras.length; index++) {
  13184. this.cameras[index].detachControl(canvas);
  13185. }
  13186. // Release lights
  13187. while (this.lights.length) {
  13188. this.lights[0].dispose();
  13189. }
  13190. // Release meshes
  13191. while (this.meshes.length) {
  13192. this.meshes[0].dispose(true);
  13193. }
  13194. // Release cameras
  13195. while (this.cameras.length) {
  13196. this.cameras[0].dispose();
  13197. }
  13198. // Release materials
  13199. while (this.materials.length) {
  13200. this.materials[0].dispose();
  13201. }
  13202. // Release particles
  13203. while (this.particleSystems.length) {
  13204. this.particleSystems[0].dispose();
  13205. }
  13206. // Release sprites
  13207. while (this.spriteManagers.length) {
  13208. this.spriteManagers[0].dispose();
  13209. }
  13210. // Release layers
  13211. while (this.layers.length) {
  13212. this.layers[0].dispose();
  13213. }
  13214. // Release textures
  13215. while (this.textures.length) {
  13216. this.textures[0].dispose();
  13217. }
  13218. // Post-processes
  13219. this.postProcessManager.dispose();
  13220. // Physics
  13221. if (this._physicsEngine) {
  13222. this.disablePhysicsEngine();
  13223. }
  13224. // Remove from engine
  13225. index = this._engine.scenes.indexOf(this);
  13226. if (index > -1) {
  13227. this._engine.scenes.splice(index, 1);
  13228. }
  13229. this._engine.wipeCaches();
  13230. };
  13231. // Release sounds & sounds tracks
  13232. Scene.prototype.disposeSounds = function () {
  13233. this.mainSoundTrack.dispose();
  13234. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13235. this.soundTracks[scIndex].dispose();
  13236. }
  13237. };
  13238. // Octrees
  13239. Scene.prototype.getWorldExtends = function () {
  13240. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13241. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13242. for (var index = 0; index < this.meshes.length; index++) {
  13243. var mesh = this.meshes[index];
  13244. mesh.computeWorldMatrix(true);
  13245. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13246. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13247. BABYLON.Tools.CheckExtends(minBox, min, max);
  13248. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13249. }
  13250. return {
  13251. min: min,
  13252. max: max
  13253. };
  13254. };
  13255. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13256. if (maxCapacity === void 0) { maxCapacity = 64; }
  13257. if (maxDepth === void 0) { maxDepth = 2; }
  13258. if (!this._selectionOctree) {
  13259. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13260. }
  13261. var worldExtends = this.getWorldExtends();
  13262. // Update octree
  13263. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13264. return this._selectionOctree;
  13265. };
  13266. // Picking
  13267. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13268. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13269. var engine = this._engine;
  13270. if (!camera) {
  13271. if (!this.activeCamera)
  13272. throw new Error("Active camera not set");
  13273. camera = this.activeCamera;
  13274. }
  13275. var cameraViewport = camera.viewport;
  13276. var viewport = cameraViewport.toGlobal(engine);
  13277. // Moving coordinates to local viewport world
  13278. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13279. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13280. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13281. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13282. };
  13283. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13284. var engine = this._engine;
  13285. if (!camera) {
  13286. if (!this.activeCamera)
  13287. throw new Error("Active camera not set");
  13288. camera = this.activeCamera;
  13289. }
  13290. var cameraViewport = camera.viewport;
  13291. var viewport = cameraViewport.toGlobal(engine);
  13292. var identity = BABYLON.Matrix.Identity();
  13293. // Moving coordinates to local viewport world
  13294. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13295. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13296. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13297. };
  13298. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13299. var pickingInfo = null;
  13300. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13301. var mesh = this.meshes[meshIndex];
  13302. if (predicate) {
  13303. if (!predicate(mesh)) {
  13304. continue;
  13305. }
  13306. }
  13307. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13308. continue;
  13309. }
  13310. var world = mesh.getWorldMatrix();
  13311. var ray = rayFunction(world);
  13312. var result = mesh.intersects(ray, fastCheck);
  13313. if (!result || !result.hit)
  13314. continue;
  13315. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13316. continue;
  13317. pickingInfo = result;
  13318. if (fastCheck) {
  13319. break;
  13320. }
  13321. }
  13322. return pickingInfo || new BABYLON.PickingInfo();
  13323. };
  13324. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13325. var pickingInfo = null;
  13326. camera = camera || this.activeCamera;
  13327. if (this.spriteManagers.length > 0) {
  13328. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13329. var spriteManager = this.spriteManagers[spriteIndex];
  13330. if (!spriteManager.isPickable) {
  13331. continue;
  13332. }
  13333. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13334. if (!result || !result.hit)
  13335. continue;
  13336. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13337. continue;
  13338. pickingInfo = result;
  13339. if (fastCheck) {
  13340. break;
  13341. }
  13342. }
  13343. }
  13344. return pickingInfo || new BABYLON.PickingInfo();
  13345. };
  13346. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13347. var _this = this;
  13348. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13349. /// <param name="x">X position on screen</param>
  13350. /// <param name="y">Y position on screen</param>
  13351. /// <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>
  13352. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13353. /// <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>
  13354. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13355. };
  13356. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13357. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13358. /// <param name="x">X position on screen</param>
  13359. /// <param name="y">Y position on screen</param>
  13360. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  13361. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13362. /// <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>
  13363. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13364. };
  13365. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13366. var _this = this;
  13367. return this._internalPick(function (world) {
  13368. if (!_this._pickWithRayInverseMatrix) {
  13369. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13370. }
  13371. world.invertToRef(_this._pickWithRayInverseMatrix);
  13372. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13373. }, predicate, fastCheck);
  13374. };
  13375. Scene.prototype.setPointerOverMesh = function (mesh) {
  13376. if (this._pointerOverMesh === mesh) {
  13377. return;
  13378. }
  13379. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13380. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13381. }
  13382. this._pointerOverMesh = mesh;
  13383. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13384. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13385. }
  13386. };
  13387. Scene.prototype.getPointerOverMesh = function () {
  13388. return this._pointerOverMesh;
  13389. };
  13390. // Physics
  13391. Scene.prototype.getPhysicsEngine = function () {
  13392. return this._physicsEngine;
  13393. };
  13394. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13395. if (this._physicsEngine) {
  13396. return true;
  13397. }
  13398. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13399. if (!this._physicsEngine.isSupported()) {
  13400. this._physicsEngine = null;
  13401. return false;
  13402. }
  13403. this._physicsEngine._initialize(gravity);
  13404. return true;
  13405. };
  13406. Scene.prototype.disablePhysicsEngine = function () {
  13407. if (!this._physicsEngine) {
  13408. return;
  13409. }
  13410. this._physicsEngine.dispose();
  13411. this._physicsEngine = undefined;
  13412. };
  13413. Scene.prototype.isPhysicsEnabled = function () {
  13414. return this._physicsEngine !== undefined;
  13415. };
  13416. Scene.prototype.setGravity = function (gravity) {
  13417. if (!this._physicsEngine) {
  13418. return;
  13419. }
  13420. this._physicsEngine._setGravity(gravity);
  13421. };
  13422. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13423. if (parts.parts) {
  13424. options = parts;
  13425. parts = parts.parts;
  13426. }
  13427. if (!this._physicsEngine) {
  13428. return null;
  13429. }
  13430. for (var index = 0; index < parts.length; index++) {
  13431. var mesh = parts[index].mesh;
  13432. mesh._physicImpostor = parts[index].impostor;
  13433. mesh._physicsMass = options.mass / parts.length;
  13434. mesh._physicsFriction = options.friction;
  13435. mesh._physicRestitution = options.restitution;
  13436. }
  13437. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13438. };
  13439. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13440. for (var index = 0; index < compound.parts.length; index++) {
  13441. var mesh = compound.parts[index].mesh;
  13442. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13443. this._physicsEngine._unregisterMesh(mesh);
  13444. }
  13445. };
  13446. // Misc.
  13447. Scene.prototype.createDefaultCameraOrLight = function () {
  13448. // Light
  13449. if (this.lights.length === 0) {
  13450. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13451. }
  13452. // Camera
  13453. if (!this.activeCamera) {
  13454. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13455. // Compute position
  13456. var worldExtends = this.getWorldExtends();
  13457. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13458. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13459. camera.setTarget(worldCenter);
  13460. this.activeCamera = camera;
  13461. }
  13462. };
  13463. // Tags
  13464. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13465. if (tagsQuery === undefined) {
  13466. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13467. return list;
  13468. }
  13469. var listByTags = [];
  13470. forEach = forEach || (function (item) { return; });
  13471. for (var i in list) {
  13472. var item = list[i];
  13473. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13474. listByTags.push(item);
  13475. forEach(item);
  13476. }
  13477. }
  13478. return listByTags;
  13479. };
  13480. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13481. return this._getByTags(this.meshes, tagsQuery, forEach);
  13482. };
  13483. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13484. return this._getByTags(this.cameras, tagsQuery, forEach);
  13485. };
  13486. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13487. return this._getByTags(this.lights, tagsQuery, forEach);
  13488. };
  13489. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13490. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13491. };
  13492. // Statics
  13493. Scene._FOGMODE_NONE = 0;
  13494. Scene._FOGMODE_EXP = 1;
  13495. Scene._FOGMODE_EXP2 = 2;
  13496. Scene._FOGMODE_LINEAR = 3;
  13497. Scene.MinDeltaTime = 1.0;
  13498. Scene.MaxDeltaTime = 1000.0;
  13499. return Scene;
  13500. })();
  13501. BABYLON.Scene = Scene;
  13502. })(BABYLON || (BABYLON = {}));
  13503. var BABYLON;
  13504. (function (BABYLON) {
  13505. var VertexBuffer = (function () {
  13506. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13507. if (engine instanceof BABYLON.Mesh) {
  13508. this._engine = engine.getScene().getEngine();
  13509. }
  13510. else {
  13511. this._engine = engine;
  13512. }
  13513. this._updatable = updatable;
  13514. this._data = data;
  13515. if (!postponeInternalCreation) {
  13516. this.create();
  13517. }
  13518. this._kind = kind;
  13519. if (stride) {
  13520. this._strideSize = stride;
  13521. return;
  13522. }
  13523. // Deduce stride from kind
  13524. switch (kind) {
  13525. case VertexBuffer.PositionKind:
  13526. this._strideSize = 3;
  13527. break;
  13528. case VertexBuffer.NormalKind:
  13529. this._strideSize = 3;
  13530. break;
  13531. case VertexBuffer.UVKind:
  13532. case VertexBuffer.UV2Kind:
  13533. case VertexBuffer.UV3Kind:
  13534. case VertexBuffer.UV4Kind:
  13535. case VertexBuffer.UV5Kind:
  13536. case VertexBuffer.UV6Kind:
  13537. this._strideSize = 2;
  13538. break;
  13539. case VertexBuffer.ColorKind:
  13540. this._strideSize = 4;
  13541. break;
  13542. case VertexBuffer.MatricesIndicesKind:
  13543. this._strideSize = 4;
  13544. break;
  13545. case VertexBuffer.MatricesWeightsKind:
  13546. this._strideSize = 4;
  13547. break;
  13548. }
  13549. }
  13550. // Properties
  13551. VertexBuffer.prototype.isUpdatable = function () {
  13552. return this._updatable;
  13553. };
  13554. VertexBuffer.prototype.getData = function () {
  13555. return this._data;
  13556. };
  13557. VertexBuffer.prototype.getBuffer = function () {
  13558. return this._buffer;
  13559. };
  13560. VertexBuffer.prototype.getStrideSize = function () {
  13561. return this._strideSize;
  13562. };
  13563. // Methods
  13564. VertexBuffer.prototype.create = function (data) {
  13565. if (!data && this._buffer) {
  13566. return; // nothing to do
  13567. }
  13568. data = data || this._data;
  13569. if (!this._buffer) {
  13570. if (this._updatable) {
  13571. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13572. }
  13573. else {
  13574. this._buffer = this._engine.createVertexBuffer(data);
  13575. }
  13576. }
  13577. if (this._updatable) {
  13578. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13579. this._data = data;
  13580. }
  13581. };
  13582. VertexBuffer.prototype.update = function (data) {
  13583. this.create(data);
  13584. };
  13585. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13586. if (!this._buffer) {
  13587. return;
  13588. }
  13589. if (this._updatable) {
  13590. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13591. this._data = null;
  13592. }
  13593. };
  13594. VertexBuffer.prototype.dispose = function () {
  13595. if (!this._buffer) {
  13596. return;
  13597. }
  13598. if (this._engine._releaseBuffer(this._buffer)) {
  13599. this._buffer = null;
  13600. }
  13601. };
  13602. Object.defineProperty(VertexBuffer, "PositionKind", {
  13603. get: function () {
  13604. return VertexBuffer._PositionKind;
  13605. },
  13606. enumerable: true,
  13607. configurable: true
  13608. });
  13609. Object.defineProperty(VertexBuffer, "NormalKind", {
  13610. get: function () {
  13611. return VertexBuffer._NormalKind;
  13612. },
  13613. enumerable: true,
  13614. configurable: true
  13615. });
  13616. Object.defineProperty(VertexBuffer, "UVKind", {
  13617. get: function () {
  13618. return VertexBuffer._UVKind;
  13619. },
  13620. enumerable: true,
  13621. configurable: true
  13622. });
  13623. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13624. get: function () {
  13625. return VertexBuffer._UV2Kind;
  13626. },
  13627. enumerable: true,
  13628. configurable: true
  13629. });
  13630. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13631. get: function () {
  13632. return VertexBuffer._UV3Kind;
  13633. },
  13634. enumerable: true,
  13635. configurable: true
  13636. });
  13637. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13638. get: function () {
  13639. return VertexBuffer._UV4Kind;
  13640. },
  13641. enumerable: true,
  13642. configurable: true
  13643. });
  13644. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13645. get: function () {
  13646. return VertexBuffer._UV5Kind;
  13647. },
  13648. enumerable: true,
  13649. configurable: true
  13650. });
  13651. Object.defineProperty(VertexBuffer, "UV6Kind", {
  13652. get: function () {
  13653. return VertexBuffer._UV6Kind;
  13654. },
  13655. enumerable: true,
  13656. configurable: true
  13657. });
  13658. Object.defineProperty(VertexBuffer, "ColorKind", {
  13659. get: function () {
  13660. return VertexBuffer._ColorKind;
  13661. },
  13662. enumerable: true,
  13663. configurable: true
  13664. });
  13665. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13666. get: function () {
  13667. return VertexBuffer._MatricesIndicesKind;
  13668. },
  13669. enumerable: true,
  13670. configurable: true
  13671. });
  13672. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13673. get: function () {
  13674. return VertexBuffer._MatricesWeightsKind;
  13675. },
  13676. enumerable: true,
  13677. configurable: true
  13678. });
  13679. // Enums
  13680. VertexBuffer._PositionKind = "position";
  13681. VertexBuffer._NormalKind = "normal";
  13682. VertexBuffer._UVKind = "uv";
  13683. VertexBuffer._UV2Kind = "uv2";
  13684. VertexBuffer._UV3Kind = "uv3";
  13685. VertexBuffer._UV4Kind = "uv4";
  13686. VertexBuffer._UV5Kind = "uv5";
  13687. VertexBuffer._UV6Kind = "uv6";
  13688. VertexBuffer._ColorKind = "color";
  13689. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13690. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13691. return VertexBuffer;
  13692. })();
  13693. BABYLON.VertexBuffer = VertexBuffer;
  13694. })(BABYLON || (BABYLON = {}));
  13695. var BABYLON;
  13696. (function (BABYLON) {
  13697. /**
  13698. * Creates an instance based on a source mesh.
  13699. */
  13700. var InstancedMesh = (function (_super) {
  13701. __extends(InstancedMesh, _super);
  13702. function InstancedMesh(name, source) {
  13703. _super.call(this, name, source.getScene());
  13704. source.instances.push(this);
  13705. this._sourceMesh = source;
  13706. this.position.copyFrom(source.position);
  13707. this.rotation.copyFrom(source.rotation);
  13708. this.scaling.copyFrom(source.scaling);
  13709. if (source.rotationQuaternion) {
  13710. this.rotationQuaternion = source.rotationQuaternion.clone();
  13711. }
  13712. this.infiniteDistance = source.infiniteDistance;
  13713. this.setPivotMatrix(source.getPivotMatrix());
  13714. this.refreshBoundingInfo();
  13715. this._syncSubMeshes();
  13716. }
  13717. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13718. // Methods
  13719. get: function () {
  13720. return this._sourceMesh.receiveShadows;
  13721. },
  13722. enumerable: true,
  13723. configurable: true
  13724. });
  13725. Object.defineProperty(InstancedMesh.prototype, "material", {
  13726. get: function () {
  13727. return this._sourceMesh.material;
  13728. },
  13729. enumerable: true,
  13730. configurable: true
  13731. });
  13732. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13733. get: function () {
  13734. return this._sourceMesh.visibility;
  13735. },
  13736. enumerable: true,
  13737. configurable: true
  13738. });
  13739. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13740. get: function () {
  13741. return this._sourceMesh.skeleton;
  13742. },
  13743. enumerable: true,
  13744. configurable: true
  13745. });
  13746. InstancedMesh.prototype.getTotalVertices = function () {
  13747. return this._sourceMesh.getTotalVertices();
  13748. };
  13749. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13750. get: function () {
  13751. return this._sourceMesh;
  13752. },
  13753. enumerable: true,
  13754. configurable: true
  13755. });
  13756. InstancedMesh.prototype.getVerticesData = function (kind) {
  13757. return this._sourceMesh.getVerticesData(kind);
  13758. };
  13759. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13760. return this._sourceMesh.isVerticesDataPresent(kind);
  13761. };
  13762. InstancedMesh.prototype.getIndices = function () {
  13763. return this._sourceMesh.getIndices();
  13764. };
  13765. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13766. get: function () {
  13767. return this._sourceMesh._positions;
  13768. },
  13769. enumerable: true,
  13770. configurable: true
  13771. });
  13772. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13773. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13774. if (data) {
  13775. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  13776. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13777. }
  13778. this._updateBoundingInfo();
  13779. };
  13780. InstancedMesh.prototype._preActivate = function () {
  13781. if (this._currentLOD) {
  13782. this._currentLOD._preActivate();
  13783. }
  13784. };
  13785. InstancedMesh.prototype._activate = function (renderId) {
  13786. if (this._currentLOD) {
  13787. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13788. }
  13789. };
  13790. InstancedMesh.prototype.getLOD = function (camera) {
  13791. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13792. if (this._currentLOD === this.sourceMesh) {
  13793. return this;
  13794. }
  13795. return this._currentLOD;
  13796. };
  13797. InstancedMesh.prototype._syncSubMeshes = function () {
  13798. this.releaseSubMeshes();
  13799. if (this._sourceMesh.subMeshes) {
  13800. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13801. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13802. }
  13803. }
  13804. };
  13805. InstancedMesh.prototype._generatePointsArray = function () {
  13806. return this._sourceMesh._generatePointsArray();
  13807. };
  13808. // Clone
  13809. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13810. var result = this._sourceMesh.createInstance(name);
  13811. // Deep copy
  13812. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13813. // Bounding info
  13814. this.refreshBoundingInfo();
  13815. // Parent
  13816. if (newParent) {
  13817. result.parent = newParent;
  13818. }
  13819. if (!doNotCloneChildren) {
  13820. // Children
  13821. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13822. var mesh = this.getScene().meshes[index];
  13823. if (mesh.parent === this) {
  13824. mesh.clone(mesh.name, result);
  13825. }
  13826. }
  13827. }
  13828. result.computeWorldMatrix(true);
  13829. return result;
  13830. };
  13831. // Dispoe
  13832. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13833. // Remove from mesh
  13834. var index = this._sourceMesh.instances.indexOf(this);
  13835. this._sourceMesh.instances.splice(index, 1);
  13836. _super.prototype.dispose.call(this, doNotRecurse);
  13837. };
  13838. return InstancedMesh;
  13839. })(BABYLON.AbstractMesh);
  13840. BABYLON.InstancedMesh = InstancedMesh;
  13841. })(BABYLON || (BABYLON = {}));
  13842. var BABYLON;
  13843. (function (BABYLON) {
  13844. var _InstancesBatch = (function () {
  13845. function _InstancesBatch() {
  13846. this.mustReturn = false;
  13847. this.visibleInstances = new Array();
  13848. this.renderSelf = new Array();
  13849. }
  13850. return _InstancesBatch;
  13851. })();
  13852. BABYLON._InstancesBatch = _InstancesBatch;
  13853. var Mesh = (function (_super) {
  13854. __extends(Mesh, _super);
  13855. /**
  13856. * @constructor
  13857. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13858. * @param {Scene} scene - The scene to add this mesh to.
  13859. * @param {Node} parent - The parent of this mesh, if it has one
  13860. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13861. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13862. * When false, achieved by calling a clone(), also passing False.
  13863. * This will make creation of children, recursive.
  13864. */
  13865. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13866. if (parent === void 0) { parent = null; }
  13867. _super.call(this, name, scene);
  13868. // Members
  13869. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13870. this.instances = new Array();
  13871. this._LODLevels = new Array();
  13872. this._onBeforeRenderCallbacks = new Array();
  13873. this._onAfterRenderCallbacks = new Array();
  13874. this._visibleInstances = {};
  13875. this._renderIdForInstances = new Array();
  13876. this._batchCache = new _InstancesBatch();
  13877. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13878. this._sideOrientation = Mesh._DEFAULTSIDE;
  13879. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13880. if (source) {
  13881. // Geometry
  13882. if (source._geometry) {
  13883. source._geometry.applyToMesh(this);
  13884. }
  13885. // Deep copy
  13886. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13887. this.id = name + "." + source.id;
  13888. // Material
  13889. this.material = source.material;
  13890. var index;
  13891. if (!doNotCloneChildren) {
  13892. // Children
  13893. for (index = 0; index < scene.meshes.length; index++) {
  13894. var mesh = scene.meshes[index];
  13895. if (mesh.parent === source) {
  13896. // doNotCloneChildren is always going to be False
  13897. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13898. }
  13899. }
  13900. }
  13901. // Particles
  13902. for (index = 0; index < scene.particleSystems.length; index++) {
  13903. var system = scene.particleSystems[index];
  13904. if (system.emitter === source) {
  13905. system.clone(system.name, this);
  13906. }
  13907. }
  13908. this.computeWorldMatrix(true);
  13909. }
  13910. // Parent
  13911. if (parent !== null) {
  13912. this.parent = parent;
  13913. }
  13914. }
  13915. Object.defineProperty(Mesh, "FRONTSIDE", {
  13916. get: function () {
  13917. return Mesh._FRONTSIDE;
  13918. },
  13919. enumerable: true,
  13920. configurable: true
  13921. });
  13922. Object.defineProperty(Mesh, "BACKSIDE", {
  13923. get: function () {
  13924. return Mesh._BACKSIDE;
  13925. },
  13926. enumerable: true,
  13927. configurable: true
  13928. });
  13929. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13930. get: function () {
  13931. return Mesh._DOUBLESIDE;
  13932. },
  13933. enumerable: true,
  13934. configurable: true
  13935. });
  13936. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13937. get: function () {
  13938. return Mesh._DEFAULTSIDE;
  13939. },
  13940. enumerable: true,
  13941. configurable: true
  13942. });
  13943. Object.defineProperty(Mesh, "NO_CAP", {
  13944. get: function () {
  13945. return Mesh._NO_CAP;
  13946. },
  13947. enumerable: true,
  13948. configurable: true
  13949. });
  13950. Object.defineProperty(Mesh, "CAP_START", {
  13951. get: function () {
  13952. return Mesh._CAP_START;
  13953. },
  13954. enumerable: true,
  13955. configurable: true
  13956. });
  13957. Object.defineProperty(Mesh, "CAP_END", {
  13958. get: function () {
  13959. return Mesh._CAP_END;
  13960. },
  13961. enumerable: true,
  13962. configurable: true
  13963. });
  13964. Object.defineProperty(Mesh, "CAP_ALL", {
  13965. get: function () {
  13966. return Mesh._CAP_ALL;
  13967. },
  13968. enumerable: true,
  13969. configurable: true
  13970. });
  13971. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13972. // Methods
  13973. get: function () {
  13974. return this._LODLevels.length > 0;
  13975. },
  13976. enumerable: true,
  13977. configurable: true
  13978. });
  13979. Mesh.prototype._sortLODLevels = function () {
  13980. this._LODLevels.sort(function (a, b) {
  13981. if (a.distance < b.distance) {
  13982. return 1;
  13983. }
  13984. if (a.distance > b.distance) {
  13985. return -1;
  13986. }
  13987. return 0;
  13988. });
  13989. };
  13990. /**
  13991. * Add a mesh as LOD level triggered at the given distance.
  13992. * @param {number} distance - the distance from the center of the object to show this level
  13993. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13994. * @return {BABYLON.Mesh} this mesh (for chaining)
  13995. */
  13996. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13997. if (mesh && mesh._masterMesh) {
  13998. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13999. return this;
  14000. }
  14001. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14002. this._LODLevels.push(level);
  14003. if (mesh) {
  14004. mesh._masterMesh = this;
  14005. }
  14006. this._sortLODLevels();
  14007. return this;
  14008. };
  14009. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14010. for (var index = 0; index < this._LODLevels.length; index++) {
  14011. var level = this._LODLevels[index];
  14012. if (level.distance === distance) {
  14013. return level.mesh;
  14014. }
  14015. }
  14016. return null;
  14017. };
  14018. /**
  14019. * Remove a mesh from the LOD array
  14020. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14021. * @return {BABYLON.Mesh} this mesh (for chaining)
  14022. */
  14023. Mesh.prototype.removeLODLevel = function (mesh) {
  14024. for (var index = 0; index < this._LODLevels.length; index++) {
  14025. if (this._LODLevels[index].mesh === mesh) {
  14026. this._LODLevels.splice(index, 1);
  14027. if (mesh) {
  14028. mesh._masterMesh = null;
  14029. }
  14030. }
  14031. }
  14032. this._sortLODLevels();
  14033. return this;
  14034. };
  14035. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14036. if (!this._LODLevels || this._LODLevels.length === 0) {
  14037. return this;
  14038. }
  14039. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14040. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14041. if (this.onLODLevelSelection) {
  14042. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14043. }
  14044. return this;
  14045. }
  14046. for (var index = 0; index < this._LODLevels.length; index++) {
  14047. var level = this._LODLevels[index];
  14048. if (level.distance < distanceToCamera) {
  14049. if (level.mesh) {
  14050. level.mesh._preActivate();
  14051. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14052. }
  14053. if (this.onLODLevelSelection) {
  14054. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14055. }
  14056. return level.mesh;
  14057. }
  14058. }
  14059. if (this.onLODLevelSelection) {
  14060. this.onLODLevelSelection(distanceToCamera, this, this);
  14061. }
  14062. return this;
  14063. };
  14064. Object.defineProperty(Mesh.prototype, "geometry", {
  14065. get: function () {
  14066. return this._geometry;
  14067. },
  14068. enumerable: true,
  14069. configurable: true
  14070. });
  14071. Mesh.prototype.getTotalVertices = function () {
  14072. if (!this._geometry) {
  14073. return 0;
  14074. }
  14075. return this._geometry.getTotalVertices();
  14076. };
  14077. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14078. if (!this._geometry) {
  14079. return null;
  14080. }
  14081. return this._geometry.getVerticesData(kind, copyWhenShared);
  14082. };
  14083. Mesh.prototype.getVertexBuffer = function (kind) {
  14084. if (!this._geometry) {
  14085. return undefined;
  14086. }
  14087. return this._geometry.getVertexBuffer(kind);
  14088. };
  14089. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14090. if (!this._geometry) {
  14091. if (this._delayInfo) {
  14092. return this._delayInfo.indexOf(kind) !== -1;
  14093. }
  14094. return false;
  14095. }
  14096. return this._geometry.isVerticesDataPresent(kind);
  14097. };
  14098. Mesh.prototype.getVerticesDataKinds = function () {
  14099. if (!this._geometry) {
  14100. var result = [];
  14101. if (this._delayInfo) {
  14102. for (var kind in this._delayInfo) {
  14103. result.push(kind);
  14104. }
  14105. }
  14106. return result;
  14107. }
  14108. return this._geometry.getVerticesDataKinds();
  14109. };
  14110. Mesh.prototype.getTotalIndices = function () {
  14111. if (!this._geometry) {
  14112. return 0;
  14113. }
  14114. return this._geometry.getTotalIndices();
  14115. };
  14116. Mesh.prototype.getIndices = function (copyWhenShared) {
  14117. if (!this._geometry) {
  14118. return [];
  14119. }
  14120. return this._geometry.getIndices(copyWhenShared);
  14121. };
  14122. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14123. get: function () {
  14124. return this._masterMesh !== null && this._masterMesh !== undefined;
  14125. },
  14126. enumerable: true,
  14127. configurable: true
  14128. });
  14129. Mesh.prototype.isReady = function () {
  14130. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14131. return false;
  14132. }
  14133. return _super.prototype.isReady.call(this);
  14134. };
  14135. Mesh.prototype.isDisposed = function () {
  14136. return this._isDisposed;
  14137. };
  14138. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14139. get: function () {
  14140. return this._sideOrientation;
  14141. },
  14142. set: function (sideO) {
  14143. this._sideOrientation = sideO;
  14144. },
  14145. enumerable: true,
  14146. configurable: true
  14147. });
  14148. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14149. get: function () {
  14150. return this._areNormalsFrozen;
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14156. Mesh.prototype.freezeNormals = function () {
  14157. this._areNormalsFrozen = true;
  14158. };
  14159. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14160. Mesh.prototype.unfreezeNormals = function () {
  14161. this._areNormalsFrozen = false;
  14162. };
  14163. // Methods
  14164. Mesh.prototype._preActivate = function () {
  14165. var sceneRenderId = this.getScene().getRenderId();
  14166. if (this._preActivateId === sceneRenderId) {
  14167. return;
  14168. }
  14169. this._preActivateId = sceneRenderId;
  14170. this._visibleInstances = null;
  14171. };
  14172. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14173. if (!this._visibleInstances) {
  14174. this._visibleInstances = {};
  14175. this._visibleInstances.defaultRenderId = renderId;
  14176. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14177. }
  14178. if (!this._visibleInstances[renderId]) {
  14179. this._visibleInstances[renderId] = new Array();
  14180. }
  14181. this._visibleInstances[renderId].push(instance);
  14182. };
  14183. Mesh.prototype.refreshBoundingInfo = function () {
  14184. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14185. if (data) {
  14186. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14187. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14188. }
  14189. if (this.subMeshes) {
  14190. for (var index = 0; index < this.subMeshes.length; index++) {
  14191. this.subMeshes[index].refreshBoundingInfo();
  14192. }
  14193. }
  14194. this._updateBoundingInfo();
  14195. };
  14196. Mesh.prototype._createGlobalSubMesh = function () {
  14197. var totalVertices = this.getTotalVertices();
  14198. if (!totalVertices || !this.getIndices()) {
  14199. return null;
  14200. }
  14201. this.releaseSubMeshes();
  14202. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14203. };
  14204. Mesh.prototype.subdivide = function (count) {
  14205. if (count < 1) {
  14206. return;
  14207. }
  14208. var totalIndices = this.getTotalIndices();
  14209. var subdivisionSize = (totalIndices / count) | 0;
  14210. var offset = 0;
  14211. // Ensure that subdivisionSize is a multiple of 3
  14212. while (subdivisionSize % 3 !== 0) {
  14213. subdivisionSize++;
  14214. }
  14215. this.releaseSubMeshes();
  14216. for (var index = 0; index < count; index++) {
  14217. if (offset >= totalIndices) {
  14218. break;
  14219. }
  14220. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14221. offset += subdivisionSize;
  14222. }
  14223. this.synchronizeInstances();
  14224. };
  14225. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14226. if (!this._geometry) {
  14227. var vertexData = new BABYLON.VertexData();
  14228. vertexData.set(data, kind);
  14229. var scene = this.getScene();
  14230. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14231. }
  14232. else {
  14233. this._geometry.setVerticesData(kind, data, updatable, stride);
  14234. }
  14235. };
  14236. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14237. if (!this._geometry) {
  14238. return;
  14239. }
  14240. if (!makeItUnique) {
  14241. this._geometry.updateVerticesData(kind, data, updateExtends);
  14242. }
  14243. else {
  14244. this.makeGeometryUnique();
  14245. this.updateVerticesData(kind, data, updateExtends, false);
  14246. }
  14247. };
  14248. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14249. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14250. if (!this._geometry) {
  14251. return;
  14252. }
  14253. if (!makeItUnique) {
  14254. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14255. }
  14256. else {
  14257. this.makeGeometryUnique();
  14258. this.updateVerticesDataDirectly(kind, data, offset, false);
  14259. }
  14260. };
  14261. // Mesh positions update function :
  14262. // updates the mesh positions according to the positionFunction returned values.
  14263. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14264. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14265. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14266. if (computeNormals === void 0) { computeNormals = true; }
  14267. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14268. positionFunction(positions);
  14269. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14270. if (computeNormals) {
  14271. var indices = this.getIndices();
  14272. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14273. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14274. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14275. }
  14276. };
  14277. Mesh.prototype.makeGeometryUnique = function () {
  14278. if (!this._geometry) {
  14279. return;
  14280. }
  14281. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14282. geometry.applyToMesh(this);
  14283. };
  14284. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14285. if (!this._geometry) {
  14286. var vertexData = new BABYLON.VertexData();
  14287. vertexData.indices = indices;
  14288. var scene = this.getScene();
  14289. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14290. }
  14291. else {
  14292. this._geometry.setIndices(indices, totalVertices);
  14293. }
  14294. };
  14295. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14296. var engine = this.getScene().getEngine();
  14297. // Wireframe
  14298. var indexToBind;
  14299. switch (fillMode) {
  14300. case BABYLON.Material.PointFillMode:
  14301. indexToBind = null;
  14302. break;
  14303. case BABYLON.Material.WireFrameFillMode:
  14304. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14305. break;
  14306. default:
  14307. case BABYLON.Material.TriangleFillMode:
  14308. indexToBind = this._geometry.getIndexBuffer();
  14309. break;
  14310. }
  14311. // VBOs
  14312. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14313. };
  14314. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14315. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14316. return;
  14317. }
  14318. var engine = this.getScene().getEngine();
  14319. // Draw order
  14320. switch (fillMode) {
  14321. case BABYLON.Material.PointFillMode:
  14322. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14323. break;
  14324. case BABYLON.Material.WireFrameFillMode:
  14325. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14326. break;
  14327. default:
  14328. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14329. }
  14330. };
  14331. Mesh.prototype.registerBeforeRender = function (func) {
  14332. this._onBeforeRenderCallbacks.push(func);
  14333. };
  14334. Mesh.prototype.unregisterBeforeRender = function (func) {
  14335. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14336. if (index > -1) {
  14337. this._onBeforeRenderCallbacks.splice(index, 1);
  14338. }
  14339. };
  14340. Mesh.prototype.registerAfterRender = function (func) {
  14341. this._onAfterRenderCallbacks.push(func);
  14342. };
  14343. Mesh.prototype.unregisterAfterRender = function (func) {
  14344. var index = this._onAfterRenderCallbacks.indexOf(func);
  14345. if (index > -1) {
  14346. this._onAfterRenderCallbacks.splice(index, 1);
  14347. }
  14348. };
  14349. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14350. var scene = this.getScene();
  14351. this._batchCache.mustReturn = false;
  14352. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14353. this._batchCache.visibleInstances[subMeshId] = null;
  14354. if (this._visibleInstances) {
  14355. var currentRenderId = scene.getRenderId();
  14356. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14357. var selfRenderId = this._renderId;
  14358. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14359. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14360. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14361. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14362. }
  14363. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14364. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14365. this._batchCache.mustReturn = true;
  14366. return this._batchCache;
  14367. }
  14368. if (currentRenderId !== selfRenderId) {
  14369. this._batchCache.renderSelf[subMeshId] = false;
  14370. }
  14371. }
  14372. this._renderIdForInstances[subMeshId] = currentRenderId;
  14373. }
  14374. return this._batchCache;
  14375. };
  14376. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14377. var visibleInstances = batch.visibleInstances[subMesh._id];
  14378. var matricesCount = visibleInstances.length + 1;
  14379. var bufferSize = matricesCount * 16 * 4;
  14380. while (this._instancesBufferSize < bufferSize) {
  14381. this._instancesBufferSize *= 2;
  14382. }
  14383. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14384. if (this._worldMatricesInstancesBuffer) {
  14385. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14386. }
  14387. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14388. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14389. }
  14390. var offset = 0;
  14391. var instancesCount = 0;
  14392. var world = this.getWorldMatrix();
  14393. if (batch.renderSelf[subMesh._id]) {
  14394. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14395. offset += 16;
  14396. instancesCount++;
  14397. }
  14398. if (visibleInstances) {
  14399. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14400. var instance = visibleInstances[instanceIndex];
  14401. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14402. offset += 16;
  14403. instancesCount++;
  14404. }
  14405. }
  14406. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14407. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14408. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14409. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14410. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14411. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14412. this._draw(subMesh, fillMode, instancesCount);
  14413. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14414. };
  14415. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14416. var scene = this.getScene();
  14417. var engine = scene.getEngine();
  14418. if (hardwareInstancedRendering) {
  14419. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14420. }
  14421. else {
  14422. if (batch.renderSelf[subMesh._id]) {
  14423. // Draw
  14424. if (onBeforeDraw) {
  14425. onBeforeDraw(false, this.getWorldMatrix());
  14426. }
  14427. this._draw(subMesh, fillMode);
  14428. }
  14429. if (batch.visibleInstances[subMesh._id]) {
  14430. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14431. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14432. // World
  14433. var world = instance.getWorldMatrix();
  14434. if (onBeforeDraw) {
  14435. onBeforeDraw(true, world);
  14436. }
  14437. // Draw
  14438. this._draw(subMesh, fillMode);
  14439. }
  14440. }
  14441. }
  14442. };
  14443. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14444. var scene = this.getScene();
  14445. // Managing instances
  14446. var batch = this._getInstancesRenderList(subMesh._id);
  14447. if (batch.mustReturn) {
  14448. return;
  14449. }
  14450. // Checking geometry state
  14451. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14452. return;
  14453. }
  14454. var callbackIndex;
  14455. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14456. this._onBeforeRenderCallbacks[callbackIndex](this);
  14457. }
  14458. var engine = scene.getEngine();
  14459. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14460. // Material
  14461. var effectiveMaterial = subMesh.getMaterial();
  14462. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14463. return;
  14464. }
  14465. // Outline - step 1
  14466. var savedDepthWrite = engine.getDepthWrite();
  14467. if (this.renderOutline) {
  14468. engine.setDepthWrite(false);
  14469. scene.getOutlineRenderer().render(subMesh, batch);
  14470. engine.setDepthWrite(savedDepthWrite);
  14471. }
  14472. effectiveMaterial._preBind();
  14473. var effect = effectiveMaterial.getEffect();
  14474. // Bind
  14475. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14476. this._bind(subMesh, effect, fillMode);
  14477. var world = this.getWorldMatrix();
  14478. effectiveMaterial.bind(world, this);
  14479. // Alpha mode
  14480. if (enableAlphaMode) {
  14481. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14482. }
  14483. // Draw
  14484. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14485. if (isInstance) {
  14486. effectiveMaterial.bindOnlyWorldMatrix(world);
  14487. }
  14488. });
  14489. // Unbind
  14490. effectiveMaterial.unbind();
  14491. // Outline - step 2
  14492. if (this.renderOutline && savedDepthWrite) {
  14493. engine.setDepthWrite(true);
  14494. engine.setColorWrite(false);
  14495. scene.getOutlineRenderer().render(subMesh, batch);
  14496. engine.setColorWrite(true);
  14497. }
  14498. // Overlay
  14499. if (this.renderOverlay) {
  14500. var currentMode = engine.getAlphaMode();
  14501. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14502. scene.getOutlineRenderer().render(subMesh, batch, true);
  14503. engine.setAlphaMode(currentMode);
  14504. }
  14505. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14506. this._onAfterRenderCallbacks[callbackIndex](this);
  14507. }
  14508. };
  14509. Mesh.prototype.getEmittedParticleSystems = function () {
  14510. var results = new Array();
  14511. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14512. var particleSystem = this.getScene().particleSystems[index];
  14513. if (particleSystem.emitter === this) {
  14514. results.push(particleSystem);
  14515. }
  14516. }
  14517. return results;
  14518. };
  14519. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14520. var results = new Array();
  14521. var descendants = this.getDescendants();
  14522. descendants.push(this);
  14523. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14524. var particleSystem = this.getScene().particleSystems[index];
  14525. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14526. results.push(particleSystem);
  14527. }
  14528. }
  14529. return results;
  14530. };
  14531. Mesh.prototype.getChildren = function () {
  14532. var results = [];
  14533. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14534. var mesh = this.getScene().meshes[index];
  14535. if (mesh.parent === this) {
  14536. results.push(mesh);
  14537. }
  14538. }
  14539. return results;
  14540. };
  14541. Mesh.prototype._checkDelayState = function () {
  14542. var _this = this;
  14543. var that = this;
  14544. var scene = this.getScene();
  14545. if (this._geometry) {
  14546. this._geometry.load(scene);
  14547. }
  14548. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14549. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14550. scene._addPendingData(that);
  14551. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14552. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14553. if (data instanceof ArrayBuffer) {
  14554. _this._delayLoadingFunction(data, _this);
  14555. }
  14556. else {
  14557. _this._delayLoadingFunction(JSON.parse(data), _this);
  14558. }
  14559. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14560. scene._removePendingData(_this);
  14561. }, function () { }, scene.database, getBinaryData);
  14562. }
  14563. };
  14564. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14565. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14566. return false;
  14567. }
  14568. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14569. return false;
  14570. }
  14571. this._checkDelayState();
  14572. return true;
  14573. };
  14574. Mesh.prototype.setMaterialByID = function (id) {
  14575. var materials = this.getScene().materials;
  14576. var index;
  14577. for (index = 0; index < materials.length; index++) {
  14578. if (materials[index].id === id) {
  14579. this.material = materials[index];
  14580. return;
  14581. }
  14582. }
  14583. // Multi
  14584. var multiMaterials = this.getScene().multiMaterials;
  14585. for (index = 0; index < multiMaterials.length; index++) {
  14586. if (multiMaterials[index].id === id) {
  14587. this.material = multiMaterials[index];
  14588. return;
  14589. }
  14590. }
  14591. };
  14592. Mesh.prototype.getAnimatables = function () {
  14593. var results = [];
  14594. if (this.material) {
  14595. results.push(this.material);
  14596. }
  14597. if (this.skeleton) {
  14598. results.push(this.skeleton);
  14599. }
  14600. return results;
  14601. };
  14602. // Geometry
  14603. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14604. // Position
  14605. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14606. return;
  14607. }
  14608. this._resetPointsArrayCache();
  14609. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14610. var temp = [];
  14611. var index;
  14612. for (index = 0; index < data.length; index += 3) {
  14613. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14614. }
  14615. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14616. // Normals
  14617. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14618. return;
  14619. }
  14620. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14621. temp = [];
  14622. for (index = 0; index < data.length; index += 3) {
  14623. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14624. }
  14625. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14626. // flip faces?
  14627. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14628. this.flipFaces();
  14629. }
  14630. };
  14631. // Will apply current transform to mesh and reset world matrix
  14632. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14633. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14634. this.scaling.copyFromFloats(1, 1, 1);
  14635. this.position.copyFromFloats(0, 0, 0);
  14636. this.rotation.copyFromFloats(0, 0, 0);
  14637. //only if quaternion is already set
  14638. if (this.rotationQuaternion) {
  14639. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  14640. }
  14641. this._worldMatrix = BABYLON.Matrix.Identity();
  14642. };
  14643. // Cache
  14644. Mesh.prototype._resetPointsArrayCache = function () {
  14645. this._positions = null;
  14646. };
  14647. Mesh.prototype._generatePointsArray = function () {
  14648. if (this._positions)
  14649. return true;
  14650. this._positions = [];
  14651. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14652. if (!data) {
  14653. return false;
  14654. }
  14655. for (var index = 0; index < data.length; index += 3) {
  14656. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14657. }
  14658. return true;
  14659. };
  14660. // Clone
  14661. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14662. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14663. };
  14664. // Dispose
  14665. Mesh.prototype.dispose = function (doNotRecurse) {
  14666. if (this._geometry) {
  14667. this._geometry.releaseForMesh(this, true);
  14668. }
  14669. // Instances
  14670. if (this._worldMatricesInstancesBuffer) {
  14671. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14672. this._worldMatricesInstancesBuffer = null;
  14673. }
  14674. while (this.instances.length) {
  14675. this.instances[0].dispose();
  14676. }
  14677. _super.prototype.dispose.call(this, doNotRecurse);
  14678. };
  14679. // Geometric tools
  14680. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14681. var _this = this;
  14682. var scene = this.getScene();
  14683. var onload = function (img) {
  14684. // Getting height map data
  14685. var canvas = document.createElement("canvas");
  14686. var context = canvas.getContext("2d");
  14687. var heightMapWidth = img.width;
  14688. var heightMapHeight = img.height;
  14689. canvas.width = heightMapWidth;
  14690. canvas.height = heightMapHeight;
  14691. context.drawImage(img, 0, 0);
  14692. // Create VertexData from map data
  14693. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14694. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14695. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14696. //execute success callback, if set
  14697. if (onSuccess) {
  14698. onSuccess(_this);
  14699. }
  14700. };
  14701. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14702. };
  14703. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14704. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14705. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14706. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14707. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14708. return;
  14709. }
  14710. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14711. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14712. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14713. var position = BABYLON.Vector3.Zero();
  14714. var normal = BABYLON.Vector3.Zero();
  14715. var uv = BABYLON.Vector2.Zero();
  14716. for (var index = 0; index < positions.length; index += 3) {
  14717. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14718. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14719. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14720. // Compute height
  14721. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14722. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14723. var pos = (u + v * heightMapWidth) * 4;
  14724. var r = buffer[pos] / 255.0;
  14725. var g = buffer[pos + 1] / 255.0;
  14726. var b = buffer[pos + 2] / 255.0;
  14727. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14728. normal.normalize();
  14729. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14730. position = position.add(normal);
  14731. position.toArray(positions, index);
  14732. }
  14733. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14734. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14735. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14736. };
  14737. Mesh.prototype.convertToFlatShadedMesh = function () {
  14738. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14739. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14740. var kinds = this.getVerticesDataKinds();
  14741. var vbs = [];
  14742. var data = [];
  14743. var newdata = [];
  14744. var updatableNormals = false;
  14745. var kindIndex;
  14746. var kind;
  14747. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14748. kind = kinds[kindIndex];
  14749. var vertexBuffer = this.getVertexBuffer(kind);
  14750. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14751. updatableNormals = vertexBuffer.isUpdatable();
  14752. kinds.splice(kindIndex, 1);
  14753. kindIndex--;
  14754. continue;
  14755. }
  14756. vbs[kind] = vertexBuffer;
  14757. data[kind] = vbs[kind].getData();
  14758. newdata[kind] = [];
  14759. }
  14760. // Save previous submeshes
  14761. var previousSubmeshes = this.subMeshes.slice(0);
  14762. var indices = this.getIndices();
  14763. var totalIndices = this.getTotalIndices();
  14764. // Generating unique vertices per face
  14765. var index;
  14766. for (index = 0; index < totalIndices; index++) {
  14767. var vertexIndex = indices[index];
  14768. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14769. kind = kinds[kindIndex];
  14770. var stride = vbs[kind].getStrideSize();
  14771. for (var offset = 0; offset < stride; offset++) {
  14772. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14773. }
  14774. }
  14775. }
  14776. // Updating faces & normal
  14777. var normals = [];
  14778. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14779. for (index = 0; index < totalIndices; index += 3) {
  14780. indices[index] = index;
  14781. indices[index + 1] = index + 1;
  14782. indices[index + 2] = index + 2;
  14783. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14784. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14785. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14786. var p1p2 = p1.subtract(p2);
  14787. var p3p2 = p3.subtract(p2);
  14788. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14789. // Store same normals for every vertex
  14790. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14791. normals.push(normal.x);
  14792. normals.push(normal.y);
  14793. normals.push(normal.z);
  14794. }
  14795. }
  14796. this.setIndices(indices);
  14797. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14798. // Updating vertex buffers
  14799. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14800. kind = kinds[kindIndex];
  14801. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14802. }
  14803. // Updating submeshes
  14804. this.releaseSubMeshes();
  14805. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14806. var previousOne = previousSubmeshes[submeshIndex];
  14807. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14808. }
  14809. this.synchronizeInstances();
  14810. };
  14811. // will inverse faces orientations, and invert normals too if specified
  14812. Mesh.prototype.flipFaces = function (flipNormals) {
  14813. if (flipNormals === void 0) { flipNormals = false; }
  14814. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  14815. var i;
  14816. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14817. for (i = 0; i < vertex_data.normals.length; i++) {
  14818. vertex_data.normals[i] *= -1;
  14819. }
  14820. }
  14821. var temp;
  14822. for (i = 0; i < vertex_data.indices.length; i += 3) {
  14823. // reassign indices
  14824. temp = vertex_data.indices[i + 1];
  14825. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  14826. vertex_data.indices[i + 2] = temp;
  14827. }
  14828. vertex_data.applyToMesh(this);
  14829. };
  14830. // Instances
  14831. Mesh.prototype.createInstance = function (name) {
  14832. return new BABYLON.InstancedMesh(name, this);
  14833. };
  14834. Mesh.prototype.synchronizeInstances = function () {
  14835. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14836. var instance = this.instances[instanceIndex];
  14837. instance._syncSubMeshes();
  14838. }
  14839. };
  14840. /**
  14841. * Simplify the mesh according to the given array of settings.
  14842. * Function will return immediately and will simplify async.
  14843. * @param settings a collection of simplification settings.
  14844. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14845. * @param type the type of simplification to run.
  14846. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14847. */
  14848. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14849. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14850. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14851. this.getScene().simplificationQueue.addTask({
  14852. settings: settings,
  14853. parallelProcessing: parallelProcessing,
  14854. mesh: this,
  14855. simplificationType: simplificationType,
  14856. successCallback: successCallback
  14857. });
  14858. };
  14859. /**
  14860. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14861. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14862. * This should be used together with the simplification to avoid disappearing triangles.
  14863. * @param successCallback an optional success callback to be called after the optimization finished.
  14864. */
  14865. Mesh.prototype.optimizeIndices = function (successCallback) {
  14866. var _this = this;
  14867. var indices = this.getIndices();
  14868. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14869. var vectorPositions = [];
  14870. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14871. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14872. }
  14873. var dupes = [];
  14874. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14875. var realPos = vectorPositions.length - 1 - iteration;
  14876. var testedPosition = vectorPositions[realPos];
  14877. for (var j = 0; j < realPos; ++j) {
  14878. var againstPosition = vectorPositions[j];
  14879. if (testedPosition.equals(againstPosition)) {
  14880. dupes[realPos] = j;
  14881. break;
  14882. }
  14883. }
  14884. }, function () {
  14885. for (var i = 0; i < indices.length; ++i) {
  14886. indices[i] = dupes[indices[i]] || indices[i];
  14887. }
  14888. //indices are now reordered
  14889. var originalSubMeshes = _this.subMeshes.slice(0);
  14890. _this.setIndices(indices);
  14891. _this.subMeshes = originalSubMeshes;
  14892. if (successCallback) {
  14893. successCallback(_this);
  14894. }
  14895. });
  14896. };
  14897. Mesh.CreateRibbon = function (name, options, closeArrayOrScene, closePath, offset, scene, updatable, sideOrientation, instance) {
  14898. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14899. if (instance === void 0) { instance = null; }
  14900. var pathArray;
  14901. var closeArray;
  14902. if (Array.isArray(options)) {
  14903. pathArray = options;
  14904. closeArray = closeArrayOrScene;
  14905. if (!instance) {
  14906. options = {
  14907. pathArray: pathArray,
  14908. closeArray: closeArray,
  14909. closePath: closePath,
  14910. offset: offset,
  14911. updatable: updatable,
  14912. sideOrientation: sideOrientation
  14913. };
  14914. }
  14915. }
  14916. else {
  14917. scene = closeArrayOrScene;
  14918. pathArray = options.pathArray;
  14919. closeArray = options.closeArray;
  14920. closePath = options.closePath;
  14921. offset = options.offset;
  14922. sideOrientation = options.sideOrientation;
  14923. instance = options.instance;
  14924. updatable = options.updatable;
  14925. }
  14926. if (instance) {
  14927. // positionFunction : ribbon case
  14928. // only pathArray and sideOrientation parameters are taken into account for positions update
  14929. var positionFunction = function (positions) {
  14930. var minlg = pathArray[0].length;
  14931. var i = 0;
  14932. var ns = (instance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  14933. for (var si = 1; si <= ns; si++) {
  14934. for (var p = 0; p < pathArray.length; p++) {
  14935. var path = pathArray[p];
  14936. var l = path.length;
  14937. minlg = (minlg < l) ? minlg : l;
  14938. var j = 0;
  14939. while (j < minlg) {
  14940. positions[i] = path[j].x;
  14941. positions[i + 1] = path[j].y;
  14942. positions[i + 2] = path[j].z;
  14943. j++;
  14944. i += 3;
  14945. }
  14946. if (instance._closePath) {
  14947. positions[i] = path[0].x;
  14948. positions[i + 1] = path[0].y;
  14949. positions[i + 2] = path[0].z;
  14950. i += 3;
  14951. }
  14952. }
  14953. }
  14954. };
  14955. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14956. positionFunction(positions);
  14957. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14958. if (!(instance.areNormalsFrozen)) {
  14959. var indices = instance.getIndices();
  14960. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14961. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14962. if (instance._closePath) {
  14963. var indexFirst = 0;
  14964. var indexLast = 0;
  14965. for (var p = 0; p < pathArray.length; p++) {
  14966. indexFirst = instance._idx[p] * 3;
  14967. if (p + 1 < pathArray.length) {
  14968. indexLast = (instance._idx[p + 1] - 1) * 3;
  14969. }
  14970. else {
  14971. indexLast = normals.length - 3;
  14972. }
  14973. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  14974. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  14975. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  14976. normals[indexLast] = normals[indexFirst];
  14977. normals[indexLast + 1] = normals[indexFirst + 1];
  14978. normals[indexLast + 2] = normals[indexFirst + 2];
  14979. }
  14980. }
  14981. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14982. }
  14983. return instance;
  14984. }
  14985. else {
  14986. var ribbon = new Mesh(name, scene);
  14987. ribbon.sideOrientation = sideOrientation;
  14988. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  14989. if (closePath) {
  14990. ribbon._idx = vertexData._idx;
  14991. }
  14992. ribbon._closePath = closePath;
  14993. ribbon._closeArray = closeArray;
  14994. vertexData.applyToMesh(ribbon, updatable);
  14995. return ribbon;
  14996. }
  14997. };
  14998. Mesh.CreateDisc = function (name, options, tessellationOrScene, scene, updatable, sideOrientation) {
  14999. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15000. if (tessellationOrScene instanceof BABYLON.Scene) {
  15001. scene = tessellationOrScene;
  15002. }
  15003. else {
  15004. var radius = options;
  15005. options = {
  15006. radius: radius,
  15007. tessellation: tessellationOrScene,
  15008. sideOrientation: sideOrientation
  15009. };
  15010. }
  15011. var disc = new Mesh(name, scene);
  15012. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15013. vertexData.applyToMesh(disc, updatable || options.updatable);
  15014. return disc;
  15015. };
  15016. Mesh.CreateBox = function (name, options, scene, updatable, sideOrientation) {
  15017. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15018. // Check parameters
  15019. updatable = updatable || options.updatable;
  15020. if (typeof options === 'number') {
  15021. var size = options;
  15022. options = {
  15023. size: size,
  15024. sideOrientation: sideOrientation
  15025. };
  15026. }
  15027. var box = new Mesh(name, scene);
  15028. var vertexData = BABYLON.VertexData.CreateBox(options);
  15029. vertexData.applyToMesh(box, updatable);
  15030. return box;
  15031. };
  15032. Mesh.CreateSphere = function (name, options, diameterOrScene, scene, updatable, sideOrientation) {
  15033. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15034. if (diameterOrScene instanceof BABYLON.Scene) {
  15035. scene = diameterOrScene;
  15036. updatable = options.updatable;
  15037. }
  15038. else {
  15039. var segments = options;
  15040. options = {
  15041. segments: segments,
  15042. diameterX: diameterOrScene,
  15043. diameterY: diameterOrScene,
  15044. diameterZ: diameterOrScene,
  15045. sideOrientation: sideOrientation
  15046. };
  15047. }
  15048. var sphere = new Mesh(name, scene);
  15049. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15050. vertexData.applyToMesh(sphere, updatable);
  15051. return sphere;
  15052. };
  15053. Mesh.CreateCylinder = function (name, options, diameterTopOrScene, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15054. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15055. if (diameterTopOrScene instanceof BABYLON.Scene) {
  15056. scene = diameterTopOrScene;
  15057. updatable = options.updatable;
  15058. }
  15059. else {
  15060. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15061. if (scene !== undefined) {
  15062. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15063. updatable = scene;
  15064. }
  15065. scene = subdivisions;
  15066. subdivisions = 1;
  15067. }
  15068. var height = options;
  15069. options = {
  15070. height: height,
  15071. diameterTop: diameterTopOrScene,
  15072. diameterBottom: diameterBottom,
  15073. tessellation: tessellation,
  15074. subdivisions: subdivisions,
  15075. sideOrientation: sideOrientation
  15076. };
  15077. }
  15078. var cylinder = new Mesh(name, scene);
  15079. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15080. vertexData.applyToMesh(cylinder, updatable);
  15081. return cylinder;
  15082. };
  15083. Mesh.CreateTorus = function (name, options, thicknessOrScene, tessellation, scene, updatable, sideOrientation) {
  15084. if (thicknessOrScene instanceof BABYLON.Scene) {
  15085. scene = thicknessOrScene;
  15086. updatable = options.updatable;
  15087. }
  15088. else {
  15089. var diameter = options;
  15090. options = {
  15091. diameter: diameter,
  15092. thickness: thicknessOrScene,
  15093. tessellation: tessellation,
  15094. sideOrientation: sideOrientation
  15095. };
  15096. }
  15097. var torus = new Mesh(name, scene);
  15098. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15099. vertexData.applyToMesh(torus, updatable);
  15100. return torus;
  15101. };
  15102. Mesh.CreateTorusKnot = function (name, options, tubeOrScene, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15103. if (tubeOrScene instanceof BABYLON.Scene) {
  15104. scene = tubeOrScene;
  15105. updatable = options.updatable;
  15106. }
  15107. else {
  15108. var radius = options;
  15109. options = {
  15110. radius: radius,
  15111. tube: tubeOrScene,
  15112. radialSegments: radialSegments,
  15113. tubularSegments: tubularSegments,
  15114. p: p,
  15115. q: q,
  15116. sideOrientation: sideOrientation
  15117. };
  15118. }
  15119. var torusKnot = new Mesh(name, scene);
  15120. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15121. vertexData.applyToMesh(torusKnot, updatable);
  15122. return torusKnot;
  15123. };
  15124. Mesh.CreateLines = function (name, options, scene, updatable, instance) {
  15125. var points;
  15126. if (Array.isArray(options)) {
  15127. points = options;
  15128. if (!instance) {
  15129. options = {
  15130. points: points
  15131. };
  15132. }
  15133. }
  15134. else {
  15135. instance = options.instance;
  15136. points = options.points;
  15137. }
  15138. if (instance) {
  15139. var positionFunction = function (positions) {
  15140. var i = 0;
  15141. for (var p = 0; p < points.length; p++) {
  15142. positions[i] = points[p].x;
  15143. positions[i + 1] = points[p].y;
  15144. positions[i + 2] = points[p].z;
  15145. i += 3;
  15146. }
  15147. };
  15148. instance.updateMeshPositions(positionFunction, false);
  15149. return instance;
  15150. }
  15151. // lines creation
  15152. var lines = new BABYLON.LinesMesh(name, scene);
  15153. var vertexData = BABYLON.VertexData.CreateLines(options);
  15154. vertexData.applyToMesh(lines, updatable || options.updatable);
  15155. return lines;
  15156. };
  15157. Mesh.CreateDashedLines = function (name, options, dashSizeOrScene, gapSize, dashNb, scene, updatable, instance) {
  15158. var points;
  15159. var dashSize;
  15160. if (Array.isArray(options)) {
  15161. points = options;
  15162. dashSize = dashSizeOrScene;
  15163. if (!instance) {
  15164. options = {
  15165. points: points,
  15166. dashSize: dashSize,
  15167. gapSize: gapSize,
  15168. dashNb: dashNb
  15169. };
  15170. }
  15171. }
  15172. else {
  15173. scene = dashSizeOrScene,
  15174. points = options.points;
  15175. instance = options.instance;
  15176. gapSize = options.gapSize;
  15177. dashNb = options.dashNb;
  15178. dashSize = options.dashSize;
  15179. }
  15180. if (instance) {
  15181. var positionFunction = function (positions) {
  15182. var curvect = BABYLON.Vector3.Zero();
  15183. var nbSeg = positions.length / 6;
  15184. var lg = 0;
  15185. var nb = 0;
  15186. var shft = 0;
  15187. var dashshft = 0;
  15188. var curshft = 0;
  15189. var p = 0;
  15190. var i = 0;
  15191. var j = 0;
  15192. for (i = 0; i < points.length - 1; i++) {
  15193. points[i + 1].subtractToRef(points[i], curvect);
  15194. lg += curvect.length();
  15195. }
  15196. shft = lg / nbSeg;
  15197. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15198. for (i = 0; i < points.length - 1; i++) {
  15199. points[i + 1].subtractToRef(points[i], curvect);
  15200. nb = Math.floor(curvect.length() / shft);
  15201. curvect.normalize();
  15202. j = 0;
  15203. while (j < nb && p < positions.length) {
  15204. curshft = shft * j;
  15205. positions[p] = points[i].x + curshft * curvect.x;
  15206. positions[p + 1] = points[i].y + curshft * curvect.y;
  15207. positions[p + 2] = points[i].z + curshft * curvect.z;
  15208. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15209. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15210. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15211. p += 6;
  15212. j++;
  15213. }
  15214. }
  15215. while (p < positions.length) {
  15216. positions[p] = points[i].x;
  15217. positions[p + 1] = points[i].y;
  15218. positions[p + 2] = points[i].z;
  15219. p += 3;
  15220. }
  15221. };
  15222. instance.updateMeshPositions(positionFunction, false);
  15223. return instance;
  15224. }
  15225. // dashed lines creation
  15226. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15227. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15228. vertexData.applyToMesh(dashedLines, updatable || options.updatable);
  15229. dashedLines.dashSize = dashSize;
  15230. dashedLines.gapSize = gapSize;
  15231. return dashedLines;
  15232. };
  15233. Mesh.ExtrudeShape = function (name, options, pathOrScene, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15234. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15235. if (instance === void 0) { instance = null; }
  15236. var path;
  15237. var shape;
  15238. if (Array.isArray(options)) {
  15239. shape = options;
  15240. path = pathOrScene;
  15241. scale = scale || 1;
  15242. rotation = rotation || 0;
  15243. cap = (cap === 0) ? 0 : cap || Mesh.NO_CAP;
  15244. }
  15245. else {
  15246. scene = pathOrScene;
  15247. path = options.path;
  15248. shape = options.shape;
  15249. scale = options.scale || 1;
  15250. rotation = options.rotation || 0;
  15251. cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  15252. updatable = options.updatable;
  15253. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  15254. instance = options.instance;
  15255. }
  15256. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15257. return extruded;
  15258. };
  15259. Mesh.ExtrudeShapeCustom = function (name, options, pathOrScene, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15260. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15261. if (instance === void 0) { instance = null; }
  15262. var path;
  15263. var shape;
  15264. if (Array.isArray(options)) {
  15265. shape = options;
  15266. path = pathOrScene;
  15267. ribbonCloseArray = ribbonCloseArray || false;
  15268. ribbonClosePath = ribbonClosePath || false;
  15269. cap = (cap === 0) ? 0 : cap || Mesh.NO_CAP;
  15270. }
  15271. else {
  15272. scene = pathOrScene;
  15273. path = options.path;
  15274. shape = options.shape;
  15275. scaleFunction = options.scaleFunction || (function (i, distance) { return 1; });
  15276. rotationFunction = options.rotationFunction || (function (i, distance) { return 0; });
  15277. ribbonCloseArray = options.ribbonCloseArray || false;
  15278. ribbonClosePath = options.ribbonClosePath || false;
  15279. cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  15280. updatable = options.updatable;
  15281. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  15282. instance = options.instance;
  15283. }
  15284. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  15285. return extrudedCustom;
  15286. };
  15287. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15288. // extrusion geometry
  15289. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15290. var tangents = path3D.getTangents();
  15291. var normals = path3D.getNormals();
  15292. var binormals = path3D.getBinormals();
  15293. var distances = path3D.getDistances();
  15294. var angle = 0;
  15295. var returnScale = function (i, distance) { return scale; };
  15296. var returnRotation = function (i, distance) { return rotation; };
  15297. var rotate = custom ? rotateFunction : returnRotation;
  15298. var scl = custom ? scaleFunction : returnScale;
  15299. var index = (cap === Mesh.NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  15300. var rotationMatrix = BABYLON.Matrix.Zero();
  15301. for (var i = 0; i < curve.length; i++) {
  15302. var shapePath = new Array();
  15303. var angleStep = rotate(i, distances[i]);
  15304. var scaleRatio = scl(i, distances[i]);
  15305. for (var p = 0; p < shape.length; p++) {
  15306. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  15307. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15308. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15309. shapePath.push(rotated);
  15310. }
  15311. shapePaths[index] = shapePath;
  15312. angle += angleStep;
  15313. index++;
  15314. }
  15315. // cap
  15316. var capPath = function (shapePath) {
  15317. var pointCap = Array();
  15318. var barycenter = BABYLON.Vector3.Zero();
  15319. var i;
  15320. for (i = 0; i < shapePath.length; i++) {
  15321. barycenter.addInPlace(shapePath[i]);
  15322. }
  15323. barycenter.scaleInPlace(1 / shapePath.length);
  15324. for (i = 0; i < shapePath.length; i++) {
  15325. pointCap.push(barycenter);
  15326. }
  15327. return pointCap;
  15328. };
  15329. switch (cap) {
  15330. case Mesh.NO_CAP:
  15331. break;
  15332. case Mesh.CAP_START:
  15333. shapePaths[0] = capPath(shapePaths[2]);
  15334. shapePaths[1] = shapePaths[2].slice(0);
  15335. break;
  15336. case Mesh.CAP_END:
  15337. shapePaths[index] = shapePaths[index - 1];
  15338. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  15339. break;
  15340. case Mesh.CAP_ALL:
  15341. shapePaths[0] = capPath(shapePaths[2]);
  15342. shapePaths[1] = shapePaths[2].slice(0);
  15343. shapePaths[index] = shapePaths[index - 1];
  15344. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  15345. break;
  15346. default:
  15347. break;
  15348. }
  15349. return shapePaths;
  15350. };
  15351. var path3D;
  15352. var pathArray;
  15353. if (instance) {
  15354. path3D = (instance.path3D).update(curve);
  15355. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15356. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15357. return instance;
  15358. }
  15359. // extruded shape creation
  15360. path3D = new BABYLON.Path3D(curve);
  15361. var newShapePaths = new Array();
  15362. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15363. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15364. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15365. extrudedGeneric.pathArray = pathArray;
  15366. extrudedGeneric.path3D = path3D;
  15367. extrudedGeneric.cap = cap;
  15368. return extrudedGeneric;
  15369. };
  15370. Mesh.CreateLathe = function (name, options, radiusOrScene, tessellation, scene, updatable, sideOrientation) {
  15371. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15372. var shape;
  15373. var radius;
  15374. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  15375. var closed = (options.closed === undefined) ? true : options.closed;
  15376. if (Array.isArray(options)) {
  15377. shape = options;
  15378. radius = radiusOrScene || 1;
  15379. tessellation = tessellation || 64;
  15380. }
  15381. else {
  15382. scene = radiusOrScene;
  15383. shape = options.shape;
  15384. radius = options.radius || 1;
  15385. tessellation = options.tessellation || 64;
  15386. updatable = options.updatable;
  15387. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  15388. }
  15389. var pi2 = Math.PI * 2;
  15390. var shapeLathe = new Array();
  15391. // first rotatable point
  15392. var i = 0;
  15393. while (shape[i].x === 0) {
  15394. i++;
  15395. }
  15396. var pt = shape[i];
  15397. for (i = 0; i < shape.length; i++) {
  15398. shapeLathe.push(shape[i].subtract(pt));
  15399. }
  15400. // circle path
  15401. var step = pi2 / tessellation * arc;
  15402. var rotated;
  15403. var path = new Array();
  15404. ;
  15405. for (i = 0; i <= tessellation; i++) {
  15406. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15407. path.push(rotated);
  15408. }
  15409. if (closed) {
  15410. path.push(path[0]);
  15411. }
  15412. // extrusion
  15413. var scaleFunction = function () { return 1; };
  15414. var rotateFunction = function () { return 0; };
  15415. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15416. return lathe;
  15417. };
  15418. Mesh.CreatePlane = function (name, options, scene, updatable, sideOrientation) {
  15419. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15420. if (typeof options === 'number') {
  15421. var size = options;
  15422. options = {
  15423. size: size,
  15424. width: size,
  15425. height: size,
  15426. sideOrientation: sideOrientation
  15427. };
  15428. }
  15429. var plane = new Mesh(name, scene);
  15430. var vertexData = BABYLON.VertexData.CreatePlane(options);
  15431. vertexData.applyToMesh(plane, updatable || options.updatable);
  15432. return plane;
  15433. };
  15434. Mesh.CreateGround = function (name, options, heightOrScene, subdivisions, scene, updatable) {
  15435. if (heightOrScene instanceof BABYLON.Scene) {
  15436. scene = heightOrScene;
  15437. updatable = options.updatable;
  15438. }
  15439. else {
  15440. var width = options;
  15441. options = {
  15442. width: width,
  15443. height: heightOrScene,
  15444. subdivisions: subdivisions
  15445. };
  15446. }
  15447. var ground = new BABYLON.GroundMesh(name, scene);
  15448. ground._setReady(false);
  15449. ground._subdivisions = options.subdivisions || 1;
  15450. var vertexData = BABYLON.VertexData.CreateGround(options);
  15451. vertexData.applyToMesh(ground, updatable || options.updatable);
  15452. ground._setReady(true);
  15453. return ground;
  15454. };
  15455. Mesh.CreateTiledGround = function (name, options, zminOrScene, xmax, zmax, subdivisions, precision, scene, updatable) {
  15456. var xmin;
  15457. var zmin;
  15458. if (typeof options === 'number') {
  15459. xmin = options || -1;
  15460. zmin = zminOrScene || -1;
  15461. xmax = xmax || 1;
  15462. zmax = zmax || 1;
  15463. subdivisions = subdivisions || { w: 6, h: 6 };
  15464. precision = precision || { w: 2, h: 2 };
  15465. }
  15466. else {
  15467. scene = zminOrScene;
  15468. xmin = options.xmin || -1;
  15469. zmin = options.zmin || -1;
  15470. xmax = options.xmax || 1;
  15471. zmax = options.zmax || 1;
  15472. subdivisions = options.subdivisions || { w: 6, h: 6 };
  15473. precision = options.precision || { w: 2, h: 2 };
  15474. }
  15475. var tiledGround = new Mesh(name, scene);
  15476. var vertexData = BABYLON.VertexData.CreateTiledGround({ xmin: xmin, zmin: zmin, xmax: xmax, zmax: zmax, subdivisions: subdivisions, precision: precision });
  15477. vertexData.applyToMesh(tiledGround, updatable);
  15478. return tiledGround;
  15479. };
  15480. Mesh.CreateGroundFromHeightMap = function (name, url, widthOrOptions, heightorScene, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15481. var width;
  15482. var height;
  15483. if (typeof widthOrOptions === "number") {
  15484. width = widthOrOptions;
  15485. height = heightorScene;
  15486. }
  15487. else {
  15488. width = widthOrOptions.width || 10;
  15489. height = widthOrOptions.height || 10;
  15490. subdivisions = widthOrOptions.subdivisions || 1;
  15491. minHeight = widthOrOptions.minHeight;
  15492. maxHeight = widthOrOptions.maxHeight || 10;
  15493. updatable = widthOrOptions.updatable;
  15494. onReady = widthOrOptions.onReady;
  15495. scene = heightorScene;
  15496. }
  15497. var ground = new BABYLON.GroundMesh(name, scene);
  15498. ground._subdivisions = subdivisions;
  15499. ground._setReady(false);
  15500. var onload = function (img) {
  15501. // Getting height map data
  15502. var canvas = document.createElement("canvas");
  15503. var context = canvas.getContext("2d");
  15504. var bufferWidth = img.width;
  15505. var bufferHeight = img.height;
  15506. canvas.width = bufferWidth;
  15507. canvas.height = bufferHeight;
  15508. context.drawImage(img, 0, 0);
  15509. // Create VertexData from map data
  15510. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15511. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  15512. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  15513. width: width, height: height,
  15514. subdivisions: subdivisions,
  15515. minHeight: minHeight, maxHeight: maxHeight,
  15516. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  15517. });
  15518. vertexData.applyToMesh(ground, updatable);
  15519. ground._setReady(true);
  15520. //execute ready callback, if set
  15521. if (onReady) {
  15522. onReady(ground);
  15523. }
  15524. };
  15525. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15526. return ground;
  15527. };
  15528. Mesh.CreateTube = function (name, options, radiusOrScene, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15529. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15530. if (instance === void 0) { instance = null; }
  15531. var path;
  15532. var radius;
  15533. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  15534. ;
  15535. if (Array.isArray(options)) {
  15536. path = options;
  15537. radius = radiusOrScene;
  15538. }
  15539. else {
  15540. scene = radiusOrScene;
  15541. path = options.path;
  15542. radius = options.radius || 1;
  15543. tessellation = options.tessellation || 64;
  15544. radiusFunction = options.radiusFunction;
  15545. cap = options.cap || Mesh.NO_CAP,
  15546. updatable = options.updatable;
  15547. sideOrientation = options.sideOrientation || Mesh.DEFAULTSIDE,
  15548. instance = options.instance;
  15549. }
  15550. // tube geometry
  15551. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  15552. var tangents = path3D.getTangents();
  15553. var normals = path3D.getNormals();
  15554. var distances = path3D.getDistances();
  15555. var pi2 = Math.PI * 2;
  15556. var step = pi2 / tessellation * arc;
  15557. var returnRadius = function (i, distance) { return radius; };
  15558. var radiusFunctionFinal = radiusFunction || returnRadius;
  15559. var circlePath;
  15560. var rad;
  15561. var normal;
  15562. var rotated;
  15563. var rotationMatrix = BABYLON.Matrix.Zero();
  15564. var index = (cap === Mesh._NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  15565. for (var i = 0; i < path.length; i++) {
  15566. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15567. circlePath = Array(); // current circle array
  15568. normal = normals[i]; // current normal
  15569. for (var t = 0; t < tessellation; t++) {
  15570. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  15571. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15572. circlePath.push(rotated);
  15573. }
  15574. circlePaths[index] = circlePath;
  15575. index++;
  15576. }
  15577. // cap
  15578. var capPath = function (nbPoints, pathIndex) {
  15579. var pointCap = Array();
  15580. for (var i = 0; i < nbPoints; i++) {
  15581. pointCap.push(path[pathIndex]);
  15582. }
  15583. return pointCap;
  15584. };
  15585. switch (cap) {
  15586. case Mesh.NO_CAP:
  15587. break;
  15588. case Mesh.CAP_START:
  15589. circlePaths[0] = capPath(tessellation, 0);
  15590. circlePaths[1] = circlePaths[2].slice(0);
  15591. break;
  15592. case Mesh.CAP_END:
  15593. circlePaths[index] = circlePaths[index - 1].slice(0);
  15594. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15595. break;
  15596. case Mesh.CAP_ALL:
  15597. circlePaths[0] = capPath(tessellation, 0);
  15598. circlePaths[1] = circlePaths[2].slice(0);
  15599. circlePaths[index] = circlePaths[index - 1].slice(0);
  15600. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15601. break;
  15602. default:
  15603. break;
  15604. }
  15605. return circlePaths;
  15606. };
  15607. var path3D;
  15608. var pathArray;
  15609. if (instance) {
  15610. arc = arc || instance.arc;
  15611. path3D = (instance.path3D).update(path);
  15612. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  15613. instance = Mesh.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  15614. instance.path3D = path3D;
  15615. instance.pathArray = pathArray;
  15616. instance.arc = arc;
  15617. return instance;
  15618. }
  15619. // tube creation
  15620. path3D = new BABYLON.Path3D(path);
  15621. var newPathArray = new Array();
  15622. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15623. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, arc);
  15624. var tube = Mesh.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  15625. tube.pathArray = pathArray;
  15626. tube.path3D = path3D;
  15627. tube.tessellation = tessellation;
  15628. tube.cap = cap;
  15629. tube.arc = arc;
  15630. return tube;
  15631. };
  15632. Mesh.CreatePolyhedron = function (name, options, scene) {
  15633. var polyhedron = new Mesh(name, scene);
  15634. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  15635. vertexData.applyToMesh(polyhedron, options.updatable);
  15636. return polyhedron;
  15637. };
  15638. Mesh.CreateDecal = function (name, sourceMesh, positionOrOptions, normal, size, angle) {
  15639. if (angle === void 0) { angle = 0; }
  15640. var indices = sourceMesh.getIndices();
  15641. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15642. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15643. var position;
  15644. if (positionOrOptions instanceof BABYLON.Vector3) {
  15645. position = positionOrOptions;
  15646. }
  15647. else {
  15648. position = positionOrOptions.position || BABYLON.Vector3.Zero();
  15649. normal = positionOrOptions.normal || BABYLON.Vector3.Up();
  15650. size = positionOrOptions.size || new BABYLON.Vector3(1, 1, 1);
  15651. angle = positionOrOptions.angle;
  15652. }
  15653. // Getting correct rotation
  15654. if (!normal) {
  15655. var target = new BABYLON.Vector3(0, 0, 1);
  15656. var camera = sourceMesh.getScene().activeCamera;
  15657. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15658. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15659. }
  15660. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15661. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15662. var pitch = Math.atan2(normal.y, len);
  15663. // Matrix
  15664. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15665. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15666. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15667. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15668. var vertexData = new BABYLON.VertexData();
  15669. vertexData.indices = [];
  15670. vertexData.positions = [];
  15671. vertexData.normals = [];
  15672. vertexData.uvs = [];
  15673. var currentVertexDataIndex = 0;
  15674. var extractDecalVector3 = function (indexId) {
  15675. var vertexId = indices[indexId];
  15676. var result = new BABYLON.PositionNormalVertex();
  15677. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15678. // Send vector to decal local world
  15679. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15680. // Get normal
  15681. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15682. return result;
  15683. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15684. var clip = function (vertices, axis) {
  15685. if (vertices.length === 0) {
  15686. return vertices;
  15687. }
  15688. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15689. var clipVertices = function (v0, v1) {
  15690. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15691. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15692. };
  15693. var result = new Array();
  15694. for (var index = 0; index < vertices.length; index += 3) {
  15695. var v1Out;
  15696. var v2Out;
  15697. var v3Out;
  15698. var total = 0;
  15699. var nV1, nV2, nV3, nV4;
  15700. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15701. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15702. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15703. v1Out = d1 > 0;
  15704. v2Out = d2 > 0;
  15705. v3Out = d3 > 0;
  15706. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15707. switch (total) {
  15708. case 0:
  15709. result.push(vertices[index]);
  15710. result.push(vertices[index + 1]);
  15711. result.push(vertices[index + 2]);
  15712. break;
  15713. case 1:
  15714. if (v1Out) {
  15715. nV1 = vertices[index + 1];
  15716. nV2 = vertices[index + 2];
  15717. nV3 = clipVertices(vertices[index], nV1);
  15718. nV4 = clipVertices(vertices[index], nV2);
  15719. }
  15720. if (v2Out) {
  15721. nV1 = vertices[index];
  15722. nV2 = vertices[index + 2];
  15723. nV3 = clipVertices(vertices[index + 1], nV1);
  15724. nV4 = clipVertices(vertices[index + 1], nV2);
  15725. result.push(nV3);
  15726. result.push(nV2.clone());
  15727. result.push(nV1.clone());
  15728. result.push(nV2.clone());
  15729. result.push(nV3.clone());
  15730. result.push(nV4);
  15731. break;
  15732. }
  15733. if (v3Out) {
  15734. nV1 = vertices[index];
  15735. nV2 = vertices[index + 1];
  15736. nV3 = clipVertices(vertices[index + 2], nV1);
  15737. nV4 = clipVertices(vertices[index + 2], nV2);
  15738. }
  15739. result.push(nV1.clone());
  15740. result.push(nV2.clone());
  15741. result.push(nV3);
  15742. result.push(nV4);
  15743. result.push(nV3.clone());
  15744. result.push(nV2.clone());
  15745. break;
  15746. case 2:
  15747. if (!v1Out) {
  15748. nV1 = vertices[index].clone();
  15749. nV2 = clipVertices(nV1, vertices[index + 1]);
  15750. nV3 = clipVertices(nV1, vertices[index + 2]);
  15751. result.push(nV1);
  15752. result.push(nV2);
  15753. result.push(nV3);
  15754. }
  15755. if (!v2Out) {
  15756. nV1 = vertices[index + 1].clone();
  15757. nV2 = clipVertices(nV1, vertices[index + 2]);
  15758. nV3 = clipVertices(nV1, vertices[index]);
  15759. result.push(nV1);
  15760. result.push(nV2);
  15761. result.push(nV3);
  15762. }
  15763. if (!v3Out) {
  15764. nV1 = vertices[index + 2].clone();
  15765. nV2 = clipVertices(nV1, vertices[index]);
  15766. nV3 = clipVertices(nV1, vertices[index + 1]);
  15767. result.push(nV1);
  15768. result.push(nV2);
  15769. result.push(nV3);
  15770. }
  15771. break;
  15772. case 3:
  15773. break;
  15774. }
  15775. }
  15776. return result;
  15777. };
  15778. for (var index = 0; index < indices.length; index += 3) {
  15779. var faceVertices = new Array();
  15780. faceVertices.push(extractDecalVector3(index));
  15781. faceVertices.push(extractDecalVector3(index + 1));
  15782. faceVertices.push(extractDecalVector3(index + 2));
  15783. // Clip
  15784. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15785. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15786. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15787. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15788. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15789. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15790. if (faceVertices.length === 0) {
  15791. continue;
  15792. }
  15793. // Add UVs and get back to world
  15794. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15795. var vertex = faceVertices[vIndex];
  15796. vertexData.indices.push(currentVertexDataIndex);
  15797. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15798. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15799. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15800. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15801. currentVertexDataIndex++;
  15802. }
  15803. }
  15804. // Return mesh
  15805. var decal = new Mesh(name, sourceMesh.getScene());
  15806. vertexData.applyToMesh(decal);
  15807. decal.position = position.clone();
  15808. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15809. return decal;
  15810. };
  15811. // Skeletons
  15812. /**
  15813. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15814. */
  15815. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15816. var source;
  15817. if (!this._sourcePositions) {
  15818. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15819. this._sourcePositions = new Float32Array(source);
  15820. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15821. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15822. }
  15823. }
  15824. return this._sourcePositions;
  15825. };
  15826. /**
  15827. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15828. */
  15829. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15830. var source;
  15831. if (!this._sourceNormals) {
  15832. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15833. this._sourceNormals = new Float32Array(source);
  15834. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15835. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15836. }
  15837. }
  15838. return this._sourceNormals;
  15839. };
  15840. /**
  15841. * Update the vertex buffers by applying transformation from the bones
  15842. * @param {skeleton} skeleton to apply
  15843. */
  15844. Mesh.prototype.applySkeleton = function (skeleton) {
  15845. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15846. return this;
  15847. }
  15848. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15849. return this;
  15850. }
  15851. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15852. return this;
  15853. }
  15854. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15855. return this;
  15856. }
  15857. if (!this._sourcePositions) {
  15858. this.setPositionsForCPUSkinning();
  15859. }
  15860. if (!this._sourceNormals) {
  15861. this.setNormalsForCPUSkinning();
  15862. }
  15863. // positionsData checks for not being Float32Array will only pass at most once
  15864. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15865. if (!(positionsData instanceof Float32Array)) {
  15866. positionsData = new Float32Array(positionsData);
  15867. }
  15868. // normalsData checks for not being Float32Array will only pass at most once
  15869. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15870. if (!(normalsData instanceof Float32Array)) {
  15871. normalsData = new Float32Array(normalsData);
  15872. }
  15873. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15874. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15875. var skeletonMatrices = skeleton.getTransformMatrices();
  15876. var tempVector3 = BABYLON.Vector3.Zero();
  15877. var finalMatrix = new BABYLON.Matrix();
  15878. var tempMatrix = new BABYLON.Matrix();
  15879. for (var index = 0; index < positionsData.length; index += 3) {
  15880. var index4 = (index / 3) * 4;
  15881. var matricesWeight0 = matricesWeightsData[index4];
  15882. var matricesWeight1 = matricesWeightsData[index4 + 1];
  15883. var matricesWeight2 = matricesWeightsData[index4 + 2];
  15884. var matricesWeight3 = matricesWeightsData[index4 + 3];
  15885. if (matricesWeight0 > 0) {
  15886. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  15887. finalMatrix.addToSelf(tempMatrix);
  15888. }
  15889. if (matricesWeight1 > 0) {
  15890. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  15891. finalMatrix.addToSelf(tempMatrix);
  15892. }
  15893. if (matricesWeight2 > 0) {
  15894. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  15895. finalMatrix.addToSelf(tempMatrix);
  15896. }
  15897. if (matricesWeight3 > 0) {
  15898. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  15899. finalMatrix.addToSelf(tempMatrix);
  15900. }
  15901. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15902. tempVector3.toArray(positionsData, index);
  15903. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15904. tempVector3.toArray(normalsData, index);
  15905. finalMatrix.reset();
  15906. }
  15907. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15908. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15909. return this;
  15910. };
  15911. // Tools
  15912. Mesh.MinMax = function (meshes) {
  15913. var minVector = null;
  15914. var maxVector = null;
  15915. for (var i in meshes) {
  15916. var mesh = meshes[i];
  15917. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15918. if (!minVector) {
  15919. minVector = boundingBox.minimumWorld;
  15920. maxVector = boundingBox.maximumWorld;
  15921. continue;
  15922. }
  15923. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15924. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15925. }
  15926. return {
  15927. min: minVector,
  15928. max: maxVector
  15929. };
  15930. };
  15931. Mesh.Center = function (meshesOrMinMaxVector) {
  15932. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15933. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15934. };
  15935. /**
  15936. * Merge the array of meshes into a single mesh for performance reasons.
  15937. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15938. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15939. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15940. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15941. */
  15942. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15943. if (disposeSource === void 0) { disposeSource = true; }
  15944. var index;
  15945. if (!allow32BitsIndices) {
  15946. var totalVertices = 0;
  15947. // Counting vertices
  15948. for (index = 0; index < meshes.length; index++) {
  15949. if (meshes[index]) {
  15950. totalVertices += meshes[index].getTotalVertices();
  15951. if (totalVertices > 65536) {
  15952. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15953. return null;
  15954. }
  15955. }
  15956. }
  15957. }
  15958. // Merge
  15959. var vertexData;
  15960. var otherVertexData;
  15961. var source;
  15962. for (index = 0; index < meshes.length; index++) {
  15963. if (meshes[index]) {
  15964. meshes[index].computeWorldMatrix(true);
  15965. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15966. otherVertexData.transform(meshes[index].getWorldMatrix());
  15967. if (vertexData) {
  15968. vertexData.merge(otherVertexData);
  15969. }
  15970. else {
  15971. vertexData = otherVertexData;
  15972. source = meshes[index];
  15973. }
  15974. }
  15975. }
  15976. if (!meshSubclass) {
  15977. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15978. }
  15979. vertexData.applyToMesh(meshSubclass);
  15980. // Setting properties
  15981. meshSubclass.material = source.material;
  15982. meshSubclass.checkCollisions = source.checkCollisions;
  15983. // Cleaning
  15984. if (disposeSource) {
  15985. for (index = 0; index < meshes.length; index++) {
  15986. if (meshes[index]) {
  15987. meshes[index].dispose();
  15988. }
  15989. }
  15990. }
  15991. return meshSubclass;
  15992. };
  15993. // Consts
  15994. Mesh._FRONTSIDE = 0;
  15995. Mesh._BACKSIDE = 1;
  15996. Mesh._DOUBLESIDE = 2;
  15997. Mesh._DEFAULTSIDE = 0;
  15998. Mesh._NO_CAP = 0;
  15999. Mesh._CAP_START = 1;
  16000. Mesh._CAP_END = 2;
  16001. Mesh._CAP_ALL = 3;
  16002. return Mesh;
  16003. })(BABYLON.AbstractMesh);
  16004. BABYLON.Mesh = Mesh;
  16005. })(BABYLON || (BABYLON = {}));
  16006. var BABYLON;
  16007. (function (BABYLON) {
  16008. var SubMesh = (function () {
  16009. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16010. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16011. this.materialIndex = materialIndex;
  16012. this.verticesStart = verticesStart;
  16013. this.verticesCount = verticesCount;
  16014. this.indexStart = indexStart;
  16015. this.indexCount = indexCount;
  16016. this._renderId = 0;
  16017. this._mesh = mesh;
  16018. this._renderingMesh = renderingMesh || mesh;
  16019. mesh.subMeshes.push(this);
  16020. this._trianglePlanes = [];
  16021. this._id = mesh.subMeshes.length - 1;
  16022. if (createBoundingBox) {
  16023. this.refreshBoundingInfo();
  16024. mesh.computeWorldMatrix(true);
  16025. }
  16026. }
  16027. SubMesh.prototype.getBoundingInfo = function () {
  16028. return this._boundingInfo;
  16029. };
  16030. SubMesh.prototype.getMesh = function () {
  16031. return this._mesh;
  16032. };
  16033. SubMesh.prototype.getRenderingMesh = function () {
  16034. return this._renderingMesh;
  16035. };
  16036. SubMesh.prototype.getMaterial = function () {
  16037. var rootMaterial = this._renderingMesh.material;
  16038. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16039. var multiMaterial = rootMaterial;
  16040. return multiMaterial.getSubMaterial(this.materialIndex);
  16041. }
  16042. if (!rootMaterial) {
  16043. return this._mesh.getScene().defaultMaterial;
  16044. }
  16045. return rootMaterial;
  16046. };
  16047. // Methods
  16048. SubMesh.prototype.refreshBoundingInfo = function () {
  16049. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16050. if (!data) {
  16051. this._boundingInfo = this._mesh._boundingInfo;
  16052. return;
  16053. }
  16054. var indices = this._renderingMesh.getIndices();
  16055. var extend;
  16056. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16057. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16058. }
  16059. else {
  16060. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16061. }
  16062. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16063. };
  16064. SubMesh.prototype._checkCollision = function (collider) {
  16065. return this._boundingInfo._checkCollision(collider);
  16066. };
  16067. SubMesh.prototype.updateBoundingInfo = function (world) {
  16068. if (!this._boundingInfo) {
  16069. this.refreshBoundingInfo();
  16070. }
  16071. this._boundingInfo._update(world);
  16072. };
  16073. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16074. return this._boundingInfo.isInFrustum(frustumPlanes);
  16075. };
  16076. SubMesh.prototype.render = function (enableAlphaMode) {
  16077. this._renderingMesh.render(this, enableAlphaMode);
  16078. };
  16079. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16080. if (!this._linesIndexBuffer) {
  16081. var linesIndices = [];
  16082. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16083. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16084. }
  16085. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16086. this.linesIndexCount = linesIndices.length;
  16087. }
  16088. return this._linesIndexBuffer;
  16089. };
  16090. SubMesh.prototype.canIntersects = function (ray) {
  16091. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16092. };
  16093. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16094. var intersectInfo = null;
  16095. // Triangles test
  16096. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16097. var p0 = positions[indices[index]];
  16098. var p1 = positions[indices[index + 1]];
  16099. var p2 = positions[indices[index + 2]];
  16100. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16101. if (currentIntersectInfo) {
  16102. if (currentIntersectInfo.distance < 0) {
  16103. continue;
  16104. }
  16105. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16106. intersectInfo = currentIntersectInfo;
  16107. intersectInfo.faceId = index / 3;
  16108. if (fastCheck) {
  16109. break;
  16110. }
  16111. }
  16112. }
  16113. }
  16114. return intersectInfo;
  16115. };
  16116. // Clone
  16117. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16118. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16119. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16120. return result;
  16121. };
  16122. // Dispose
  16123. SubMesh.prototype.dispose = function () {
  16124. if (this._linesIndexBuffer) {
  16125. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16126. this._linesIndexBuffer = null;
  16127. }
  16128. // Remove from mesh
  16129. var index = this._mesh.subMeshes.indexOf(this);
  16130. this._mesh.subMeshes.splice(index, 1);
  16131. };
  16132. // Statics
  16133. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16134. var minVertexIndex = Number.MAX_VALUE;
  16135. var maxVertexIndex = -Number.MAX_VALUE;
  16136. renderingMesh = renderingMesh || mesh;
  16137. var indices = renderingMesh.getIndices();
  16138. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16139. var vertexIndex = indices[index];
  16140. if (vertexIndex < minVertexIndex)
  16141. minVertexIndex = vertexIndex;
  16142. if (vertexIndex > maxVertexIndex)
  16143. maxVertexIndex = vertexIndex;
  16144. }
  16145. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16146. };
  16147. return SubMesh;
  16148. })();
  16149. BABYLON.SubMesh = SubMesh;
  16150. })(BABYLON || (BABYLON = {}));
  16151. var BABYLON;
  16152. (function (BABYLON) {
  16153. var BaseTexture = (function () {
  16154. function BaseTexture(scene) {
  16155. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16156. this.hasAlpha = false;
  16157. this.getAlphaFromRGB = false;
  16158. this.level = 1;
  16159. this.isCube = false;
  16160. this.isRenderTarget = false;
  16161. this.animations = new Array();
  16162. this.coordinatesIndex = 0;
  16163. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16164. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16165. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16166. this.anisotropicFilteringLevel = 4;
  16167. this._scene = scene;
  16168. this._scene.textures.push(this);
  16169. }
  16170. BaseTexture.prototype.getScene = function () {
  16171. return this._scene;
  16172. };
  16173. BaseTexture.prototype.getTextureMatrix = function () {
  16174. return null;
  16175. };
  16176. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16177. return null;
  16178. };
  16179. BaseTexture.prototype.getInternalTexture = function () {
  16180. return this._texture;
  16181. };
  16182. BaseTexture.prototype.isReady = function () {
  16183. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16184. return true;
  16185. }
  16186. if (this._texture) {
  16187. return this._texture.isReady;
  16188. }
  16189. return false;
  16190. };
  16191. BaseTexture.prototype.getSize = function () {
  16192. if (this._texture._width) {
  16193. return { width: this._texture._width, height: this._texture._height };
  16194. }
  16195. if (this._texture._size) {
  16196. return { width: this._texture._size, height: this._texture._size };
  16197. }
  16198. return { width: 0, height: 0 };
  16199. };
  16200. BaseTexture.prototype.getBaseSize = function () {
  16201. if (!this.isReady())
  16202. return { width: 0, height: 0 };
  16203. if (this._texture._size) {
  16204. return { width: this._texture._size, height: this._texture._size };
  16205. }
  16206. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16207. };
  16208. BaseTexture.prototype.scale = function (ratio) {
  16209. };
  16210. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16211. get: function () {
  16212. return false;
  16213. },
  16214. enumerable: true,
  16215. configurable: true
  16216. });
  16217. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16218. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16219. for (var index = 0; index < texturesCache.length; index++) {
  16220. var texturesCacheEntry = texturesCache[index];
  16221. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16222. texturesCache.splice(index, 1);
  16223. return;
  16224. }
  16225. }
  16226. };
  16227. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16228. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16229. for (var index = 0; index < texturesCache.length; index++) {
  16230. var texturesCacheEntry = texturesCache[index];
  16231. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16232. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16233. texturesCacheEntry.references++;
  16234. return texturesCacheEntry;
  16235. }
  16236. }
  16237. }
  16238. return null;
  16239. };
  16240. BaseTexture.prototype.delayLoad = function () {
  16241. };
  16242. BaseTexture.prototype.clone = function () {
  16243. return null;
  16244. };
  16245. BaseTexture.prototype.releaseInternalTexture = function () {
  16246. if (this._texture) {
  16247. this._scene.getEngine().releaseInternalTexture(this._texture);
  16248. delete this._texture;
  16249. }
  16250. };
  16251. BaseTexture.prototype.dispose = function () {
  16252. // Remove from scene
  16253. var index = this._scene.textures.indexOf(this);
  16254. if (index >= 0) {
  16255. this._scene.textures.splice(index, 1);
  16256. }
  16257. if (this._texture === undefined) {
  16258. return;
  16259. }
  16260. // Callback
  16261. if (this.onDispose) {
  16262. this.onDispose();
  16263. }
  16264. };
  16265. return BaseTexture;
  16266. })();
  16267. BABYLON.BaseTexture = BaseTexture;
  16268. })(BABYLON || (BABYLON = {}));
  16269. var BABYLON;
  16270. (function (BABYLON) {
  16271. var Texture = (function (_super) {
  16272. __extends(Texture, _super);
  16273. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16274. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16275. if (onLoad === void 0) { onLoad = null; }
  16276. if (onError === void 0) { onError = null; }
  16277. if (buffer === void 0) { buffer = null; }
  16278. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16279. _super.call(this, scene);
  16280. this.uOffset = 0;
  16281. this.vOffset = 0;
  16282. this.uScale = 1.0;
  16283. this.vScale = 1.0;
  16284. this.uAng = 0;
  16285. this.vAng = 0;
  16286. this.wAng = 0;
  16287. this.name = url;
  16288. this.url = url;
  16289. this._noMipmap = noMipmap;
  16290. this._invertY = invertY;
  16291. this._samplingMode = samplingMode;
  16292. this._buffer = buffer;
  16293. this._deleteBuffer = deleteBuffer;
  16294. if (!url) {
  16295. return;
  16296. }
  16297. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16298. if (!this._texture) {
  16299. if (!scene.useDelayedTextureLoading) {
  16300. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16301. if (deleteBuffer) {
  16302. delete this._buffer;
  16303. }
  16304. }
  16305. else {
  16306. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16307. }
  16308. }
  16309. else {
  16310. BABYLON.Tools.SetImmediate(function () {
  16311. if (onLoad) {
  16312. onLoad();
  16313. }
  16314. });
  16315. }
  16316. }
  16317. Texture.prototype.delayLoad = function () {
  16318. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16319. return;
  16320. }
  16321. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16322. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16323. if (!this._texture) {
  16324. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16325. if (this._deleteBuffer) {
  16326. delete this._buffer;
  16327. }
  16328. }
  16329. };
  16330. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16331. if (!this._texture) {
  16332. return;
  16333. }
  16334. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16335. };
  16336. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16337. x *= this.uScale;
  16338. y *= this.vScale;
  16339. x -= 0.5 * this.uScale;
  16340. y -= 0.5 * this.vScale;
  16341. z -= 0.5;
  16342. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16343. t.x += 0.5 * this.uScale + this.uOffset;
  16344. t.y += 0.5 * this.vScale + this.vOffset;
  16345. t.z += 0.5;
  16346. };
  16347. Texture.prototype.getTextureMatrix = function () {
  16348. if (this.uOffset === this._cachedUOffset &&
  16349. this.vOffset === this._cachedVOffset &&
  16350. this.uScale === this._cachedUScale &&
  16351. this.vScale === this._cachedVScale &&
  16352. this.uAng === this._cachedUAng &&
  16353. this.vAng === this._cachedVAng &&
  16354. this.wAng === this._cachedWAng) {
  16355. return this._cachedTextureMatrix;
  16356. }
  16357. this._cachedUOffset = this.uOffset;
  16358. this._cachedVOffset = this.vOffset;
  16359. this._cachedUScale = this.uScale;
  16360. this._cachedVScale = this.vScale;
  16361. this._cachedUAng = this.uAng;
  16362. this._cachedVAng = this.vAng;
  16363. this._cachedWAng = this.wAng;
  16364. if (!this._cachedTextureMatrix) {
  16365. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16366. this._rowGenerationMatrix = new BABYLON.Matrix();
  16367. this._t0 = BABYLON.Vector3.Zero();
  16368. this._t1 = BABYLON.Vector3.Zero();
  16369. this._t2 = BABYLON.Vector3.Zero();
  16370. }
  16371. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16372. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16373. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16374. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16375. this._t1.subtractInPlace(this._t0);
  16376. this._t2.subtractInPlace(this._t0);
  16377. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16378. this._cachedTextureMatrix.m[0] = this._t1.x;
  16379. this._cachedTextureMatrix.m[1] = this._t1.y;
  16380. this._cachedTextureMatrix.m[2] = this._t1.z;
  16381. this._cachedTextureMatrix.m[4] = this._t2.x;
  16382. this._cachedTextureMatrix.m[5] = this._t2.y;
  16383. this._cachedTextureMatrix.m[6] = this._t2.z;
  16384. this._cachedTextureMatrix.m[8] = this._t0.x;
  16385. this._cachedTextureMatrix.m[9] = this._t0.y;
  16386. this._cachedTextureMatrix.m[10] = this._t0.z;
  16387. return this._cachedTextureMatrix;
  16388. };
  16389. Texture.prototype.getReflectionTextureMatrix = function () {
  16390. if (this.uOffset === this._cachedUOffset &&
  16391. this.vOffset === this._cachedVOffset &&
  16392. this.uScale === this._cachedUScale &&
  16393. this.vScale === this._cachedVScale &&
  16394. this.coordinatesMode === this._cachedCoordinatesMode) {
  16395. return this._cachedTextureMatrix;
  16396. }
  16397. if (!this._cachedTextureMatrix) {
  16398. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16399. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16400. }
  16401. this._cachedCoordinatesMode = this.coordinatesMode;
  16402. switch (this.coordinatesMode) {
  16403. case Texture.SPHERICAL_MODE:
  16404. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16405. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16406. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16407. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16408. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16409. break;
  16410. case Texture.PLANAR_MODE:
  16411. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16412. this._cachedTextureMatrix[0] = this.uScale;
  16413. this._cachedTextureMatrix[5] = this.vScale;
  16414. this._cachedTextureMatrix[12] = this.uOffset;
  16415. this._cachedTextureMatrix[13] = this.vOffset;
  16416. break;
  16417. case Texture.PROJECTION_MODE:
  16418. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16419. this._projectionModeMatrix.m[0] = 0.5;
  16420. this._projectionModeMatrix.m[5] = -0.5;
  16421. this._projectionModeMatrix.m[10] = 0.0;
  16422. this._projectionModeMatrix.m[12] = 0.5;
  16423. this._projectionModeMatrix.m[13] = 0.5;
  16424. this._projectionModeMatrix.m[14] = 1.0;
  16425. this._projectionModeMatrix.m[15] = 1.0;
  16426. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16427. break;
  16428. default:
  16429. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16430. break;
  16431. }
  16432. return this._cachedTextureMatrix;
  16433. };
  16434. Texture.prototype.clone = function () {
  16435. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16436. // Base texture
  16437. newTexture.hasAlpha = this.hasAlpha;
  16438. newTexture.level = this.level;
  16439. newTexture.wrapU = this.wrapU;
  16440. newTexture.wrapV = this.wrapV;
  16441. newTexture.coordinatesIndex = this.coordinatesIndex;
  16442. newTexture.coordinatesMode = this.coordinatesMode;
  16443. // Texture
  16444. newTexture.uOffset = this.uOffset;
  16445. newTexture.vOffset = this.vOffset;
  16446. newTexture.uScale = this.uScale;
  16447. newTexture.vScale = this.vScale;
  16448. newTexture.uAng = this.uAng;
  16449. newTexture.vAng = this.vAng;
  16450. newTexture.wAng = this.wAng;
  16451. return newTexture;
  16452. };
  16453. // Statics
  16454. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16455. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16456. if (onLoad === void 0) { onLoad = null; }
  16457. if (onError === void 0) { onError = null; }
  16458. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16459. };
  16460. // Constants
  16461. Texture.NEAREST_SAMPLINGMODE = 1;
  16462. Texture.BILINEAR_SAMPLINGMODE = 2;
  16463. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16464. Texture.EXPLICIT_MODE = 0;
  16465. Texture.SPHERICAL_MODE = 1;
  16466. Texture.PLANAR_MODE = 2;
  16467. Texture.CUBIC_MODE = 3;
  16468. Texture.PROJECTION_MODE = 4;
  16469. Texture.SKYBOX_MODE = 5;
  16470. Texture.INVCUBIC_MODE = 6;
  16471. Texture.CLAMP_ADDRESSMODE = 0;
  16472. Texture.WRAP_ADDRESSMODE = 1;
  16473. Texture.MIRROR_ADDRESSMODE = 2;
  16474. return Texture;
  16475. })(BABYLON.BaseTexture);
  16476. BABYLON.Texture = Texture;
  16477. })(BABYLON || (BABYLON = {}));
  16478. var BABYLON;
  16479. (function (BABYLON) {
  16480. var CubeTexture = (function (_super) {
  16481. __extends(CubeTexture, _super);
  16482. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16483. _super.call(this, scene);
  16484. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16485. this.name = rootUrl;
  16486. this.url = rootUrl;
  16487. this._noMipmap = noMipmap;
  16488. this.hasAlpha = false;
  16489. if (!rootUrl) {
  16490. return;
  16491. }
  16492. this._texture = this._getFromCache(rootUrl, noMipmap);
  16493. if (!extensions) {
  16494. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16495. }
  16496. this._extensions = extensions;
  16497. if (!this._texture) {
  16498. if (!scene.useDelayedTextureLoading) {
  16499. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16500. }
  16501. else {
  16502. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16503. }
  16504. }
  16505. this.isCube = true;
  16506. this._textureMatrix = BABYLON.Matrix.Identity();
  16507. }
  16508. CubeTexture.prototype.clone = function () {
  16509. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16510. // Base texture
  16511. newTexture.level = this.level;
  16512. newTexture.wrapU = this.wrapU;
  16513. newTexture.wrapV = this.wrapV;
  16514. newTexture.coordinatesIndex = this.coordinatesIndex;
  16515. newTexture.coordinatesMode = this.coordinatesMode;
  16516. return newTexture;
  16517. };
  16518. // Methods
  16519. CubeTexture.prototype.delayLoad = function () {
  16520. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16521. return;
  16522. }
  16523. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16524. this._texture = this._getFromCache(this.url, this._noMipmap);
  16525. if (!this._texture) {
  16526. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16527. }
  16528. };
  16529. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16530. return this._textureMatrix;
  16531. };
  16532. return CubeTexture;
  16533. })(BABYLON.BaseTexture);
  16534. BABYLON.CubeTexture = CubeTexture;
  16535. })(BABYLON || (BABYLON = {}));
  16536. var BABYLON;
  16537. (function (BABYLON) {
  16538. var RenderTargetTexture = (function (_super) {
  16539. __extends(RenderTargetTexture, _super);
  16540. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  16541. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16542. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16543. if (isCube === void 0) { isCube = false; }
  16544. _super.call(this, null, scene, !generateMipMaps);
  16545. this.isCube = isCube;
  16546. this.renderList = new Array();
  16547. this.renderParticles = true;
  16548. this.renderSprites = false;
  16549. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16550. this._currentRefreshId = -1;
  16551. this._refreshRate = 1;
  16552. this.name = name;
  16553. this.isRenderTarget = true;
  16554. this._size = size;
  16555. this._generateMipMaps = generateMipMaps;
  16556. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16557. if (isCube) {
  16558. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  16559. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  16560. this._textureMatrix = BABYLON.Matrix.Identity();
  16561. }
  16562. else {
  16563. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16564. }
  16565. // Rendering groups
  16566. this._renderingManager = new BABYLON.RenderingManager(scene);
  16567. }
  16568. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONCE", {
  16569. get: function () {
  16570. return RenderTargetTexture._REFRESHRATE_RENDERONCE;
  16571. },
  16572. enumerable: true,
  16573. configurable: true
  16574. });
  16575. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONEVERYFRAME", {
  16576. get: function () {
  16577. return RenderTargetTexture._REFRESHRATE_RENDERONEVERYFRAME;
  16578. },
  16579. enumerable: true,
  16580. configurable: true
  16581. });
  16582. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONEVERYTWOFRAME", {
  16583. get: function () {
  16584. return RenderTargetTexture._REFRESHRATE_RENDERONEVERYTWOFRAME;
  16585. },
  16586. enumerable: true,
  16587. configurable: true
  16588. });
  16589. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16590. this._currentRefreshId = -1;
  16591. };
  16592. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16593. get: function () {
  16594. return this._refreshRate;
  16595. },
  16596. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16597. set: function (value) {
  16598. this._refreshRate = value;
  16599. this.resetRefreshCounter();
  16600. },
  16601. enumerable: true,
  16602. configurable: true
  16603. });
  16604. RenderTargetTexture.prototype._shouldRender = function () {
  16605. if (this._currentRefreshId === -1) {
  16606. this._currentRefreshId = 1;
  16607. return true;
  16608. }
  16609. if (this.refreshRate === this._currentRefreshId) {
  16610. this._currentRefreshId = 1;
  16611. return true;
  16612. }
  16613. this._currentRefreshId++;
  16614. return false;
  16615. };
  16616. RenderTargetTexture.prototype.isReady = function () {
  16617. if (!this.getScene().renderTargetsEnabled) {
  16618. return false;
  16619. }
  16620. return _super.prototype.isReady.call(this);
  16621. };
  16622. RenderTargetTexture.prototype.getRenderSize = function () {
  16623. return this._size;
  16624. };
  16625. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16626. get: function () {
  16627. return true;
  16628. },
  16629. enumerable: true,
  16630. configurable: true
  16631. });
  16632. RenderTargetTexture.prototype.scale = function (ratio) {
  16633. var newSize = this._size * ratio;
  16634. this.resize(newSize, this._generateMipMaps);
  16635. };
  16636. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  16637. if (this.isCube) {
  16638. return this._textureMatrix;
  16639. }
  16640. return _super.prototype.getReflectionTextureMatrix.call(this);
  16641. };
  16642. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16643. this.releaseInternalTexture();
  16644. if (this.isCube) {
  16645. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  16646. }
  16647. else {
  16648. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16649. }
  16650. };
  16651. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16652. var scene = this.getScene();
  16653. if (this._waitingRenderList) {
  16654. this.renderList = [];
  16655. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16656. var id = this._waitingRenderList[index];
  16657. this.renderList.push(scene.getMeshByID(id));
  16658. }
  16659. delete this._waitingRenderList;
  16660. }
  16661. if (this.renderList && this.renderList.length === 0) {
  16662. return;
  16663. }
  16664. // Prepare renderingManager
  16665. this._renderingManager.reset();
  16666. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16667. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16668. var mesh = currentRenderList[meshIndex];
  16669. if (mesh) {
  16670. if (!mesh.isReady()) {
  16671. // Reset _currentRefreshId
  16672. this.resetRefreshCounter();
  16673. continue;
  16674. }
  16675. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16676. mesh._activate(scene.getRenderId());
  16677. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16678. var subMesh = mesh.subMeshes[subIndex];
  16679. scene._activeIndices += subMesh.indexCount;
  16680. this._renderingManager.dispatch(subMesh);
  16681. }
  16682. }
  16683. }
  16684. }
  16685. if (this.isCube) {
  16686. for (var face = 0; face < 6; face++) {
  16687. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  16688. }
  16689. }
  16690. else {
  16691. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  16692. }
  16693. if (this.onAfterUnbind) {
  16694. this.onAfterUnbind();
  16695. }
  16696. scene.resetCachedMaterial();
  16697. };
  16698. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  16699. var scene = this.getScene();
  16700. var engine = scene.getEngine();
  16701. // Bind
  16702. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16703. if (this.isCube) {
  16704. engine.bindFramebuffer(this._texture, faceIndex);
  16705. }
  16706. else {
  16707. engine.bindFramebuffer(this._texture);
  16708. }
  16709. }
  16710. if (this.onBeforeRender) {
  16711. this.onBeforeRender(faceIndex);
  16712. }
  16713. // Clear
  16714. if (this.onClear) {
  16715. this.onClear(engine);
  16716. }
  16717. else {
  16718. engine.clear(scene.clearColor, true, true);
  16719. }
  16720. if (!this._doNotChangeAspectRatio) {
  16721. scene.updateTransformMatrix(true);
  16722. }
  16723. // Render
  16724. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16725. if (useCameraPostProcess) {
  16726. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  16727. }
  16728. if (!this._doNotChangeAspectRatio) {
  16729. scene.updateTransformMatrix(true);
  16730. }
  16731. if (this.onAfterRender) {
  16732. this.onAfterRender(faceIndex);
  16733. }
  16734. // Dump ?
  16735. if (dumpForDebug) {
  16736. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16737. }
  16738. // Unbind
  16739. if (!this.isCube || faceIndex === 5) {
  16740. if (this.isCube) {
  16741. if (faceIndex === 5) {
  16742. engine.generateMipMapsForCubemap(this._texture);
  16743. }
  16744. }
  16745. engine.unBindFramebuffer(this._texture, true);
  16746. }
  16747. };
  16748. RenderTargetTexture.prototype.clone = function () {
  16749. var textureSize = this.getSize();
  16750. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16751. // Base texture
  16752. newTexture.hasAlpha = this.hasAlpha;
  16753. newTexture.level = this.level;
  16754. // RenderTarget Texture
  16755. newTexture.coordinatesMode = this.coordinatesMode;
  16756. newTexture.renderList = this.renderList.slice(0);
  16757. return newTexture;
  16758. };
  16759. RenderTargetTexture._REFRESHRATE_RENDERONCE = 0;
  16760. RenderTargetTexture._REFRESHRATE_RENDERONEVERYFRAME = 1;
  16761. RenderTargetTexture._REFRESHRATE_RENDERONEVERYTWOFRAME = 2;
  16762. return RenderTargetTexture;
  16763. })(BABYLON.Texture);
  16764. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16765. })(BABYLON || (BABYLON = {}));
  16766. var BABYLON;
  16767. (function (BABYLON) {
  16768. var ProceduralTexture = (function (_super) {
  16769. __extends(ProceduralTexture, _super);
  16770. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16771. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16772. _super.call(this, null, scene, !generateMipMaps);
  16773. this.isEnabled = true;
  16774. this._currentRefreshId = -1;
  16775. this._refreshRate = 1;
  16776. this._vertexDeclaration = [2];
  16777. this._vertexStrideSize = 2 * 4;
  16778. this._uniforms = new Array();
  16779. this._samplers = new Array();
  16780. this._textures = new Array();
  16781. this._floats = new Array();
  16782. this._floatsArrays = {};
  16783. this._colors3 = new Array();
  16784. this._colors4 = new Array();
  16785. this._vectors2 = new Array();
  16786. this._vectors3 = new Array();
  16787. this._matrices = new Array();
  16788. this._fallbackTextureUsed = false;
  16789. scene._proceduralTextures.push(this);
  16790. this.name = name;
  16791. this.isRenderTarget = true;
  16792. this._size = size;
  16793. this._generateMipMaps = generateMipMaps;
  16794. this.setFragment(fragment);
  16795. this._fallbackTexture = fallbackTexture;
  16796. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16797. // VBO
  16798. var vertices = [];
  16799. vertices.push(1, 1);
  16800. vertices.push(-1, 1);
  16801. vertices.push(-1, -1);
  16802. vertices.push(1, -1);
  16803. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16804. // Indices
  16805. var indices = [];
  16806. indices.push(0);
  16807. indices.push(1);
  16808. indices.push(2);
  16809. indices.push(0);
  16810. indices.push(2);
  16811. indices.push(3);
  16812. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16813. }
  16814. ProceduralTexture.prototype.reset = function () {
  16815. if (this._effect === undefined) {
  16816. return;
  16817. }
  16818. var engine = this.getScene().getEngine();
  16819. engine._releaseEffect(this._effect);
  16820. };
  16821. ProceduralTexture.prototype.isReady = function () {
  16822. var _this = this;
  16823. var engine = this.getScene().getEngine();
  16824. var shaders;
  16825. if (!this._fragment) {
  16826. return false;
  16827. }
  16828. if (this._fallbackTextureUsed) {
  16829. return true;
  16830. }
  16831. if (this._fragment.fragmentElement !== undefined) {
  16832. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16833. }
  16834. else {
  16835. shaders = { vertex: "procedural", fragment: this._fragment };
  16836. }
  16837. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16838. _this.releaseInternalTexture();
  16839. if (_this._fallbackTexture) {
  16840. _this._texture = _this._fallbackTexture._texture;
  16841. _this._texture.references++;
  16842. }
  16843. _this._fallbackTextureUsed = true;
  16844. });
  16845. return this._effect.isReady();
  16846. };
  16847. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16848. this._currentRefreshId = -1;
  16849. };
  16850. ProceduralTexture.prototype.setFragment = function (fragment) {
  16851. this._fragment = fragment;
  16852. };
  16853. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16854. get: function () {
  16855. return this._refreshRate;
  16856. },
  16857. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16858. set: function (value) {
  16859. this._refreshRate = value;
  16860. this.resetRefreshCounter();
  16861. },
  16862. enumerable: true,
  16863. configurable: true
  16864. });
  16865. ProceduralTexture.prototype._shouldRender = function () {
  16866. if (!this.isEnabled || !this.isReady() || !this._texture) {
  16867. return false;
  16868. }
  16869. if (this._fallbackTextureUsed) {
  16870. return false;
  16871. }
  16872. if (this._currentRefreshId === -1) {
  16873. this._currentRefreshId = 1;
  16874. return true;
  16875. }
  16876. if (this.refreshRate === this._currentRefreshId) {
  16877. this._currentRefreshId = 1;
  16878. return true;
  16879. }
  16880. this._currentRefreshId++;
  16881. return false;
  16882. };
  16883. ProceduralTexture.prototype.getRenderSize = function () {
  16884. return this._size;
  16885. };
  16886. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16887. if (this._fallbackTextureUsed) {
  16888. return;
  16889. }
  16890. this.releaseInternalTexture();
  16891. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16892. };
  16893. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16894. if (this._uniforms.indexOf(uniformName) === -1) {
  16895. this._uniforms.push(uniformName);
  16896. }
  16897. };
  16898. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16899. if (this._samplers.indexOf(name) === -1) {
  16900. this._samplers.push(name);
  16901. }
  16902. this._textures[name] = texture;
  16903. return this;
  16904. };
  16905. ProceduralTexture.prototype.setFloat = function (name, value) {
  16906. this._checkUniform(name);
  16907. this._floats[name] = value;
  16908. return this;
  16909. };
  16910. ProceduralTexture.prototype.setFloats = function (name, value) {
  16911. this._checkUniform(name);
  16912. this._floatsArrays[name] = value;
  16913. return this;
  16914. };
  16915. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16916. this._checkUniform(name);
  16917. this._colors3[name] = value;
  16918. return this;
  16919. };
  16920. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16921. this._checkUniform(name);
  16922. this._colors4[name] = value;
  16923. return this;
  16924. };
  16925. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16926. this._checkUniform(name);
  16927. this._vectors2[name] = value;
  16928. return this;
  16929. };
  16930. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16931. this._checkUniform(name);
  16932. this._vectors3[name] = value;
  16933. return this;
  16934. };
  16935. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16936. this._checkUniform(name);
  16937. this._matrices[name] = value;
  16938. return this;
  16939. };
  16940. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16941. var scene = this.getScene();
  16942. var engine = scene.getEngine();
  16943. engine.bindFramebuffer(this._texture);
  16944. // Clear
  16945. engine.clear(scene.clearColor, true, true);
  16946. // Render
  16947. engine.enableEffect(this._effect);
  16948. engine.setState(false);
  16949. // Texture
  16950. for (var name in this._textures) {
  16951. this._effect.setTexture(name, this._textures[name]);
  16952. }
  16953. // Float
  16954. for (name in this._floats) {
  16955. this._effect.setFloat(name, this._floats[name]);
  16956. }
  16957. // Floats
  16958. for (name in this._floatsArrays) {
  16959. this._effect.setArray(name, this._floatsArrays[name]);
  16960. }
  16961. // Color3
  16962. for (name in this._colors3) {
  16963. this._effect.setColor3(name, this._colors3[name]);
  16964. }
  16965. // Color4
  16966. for (name in this._colors4) {
  16967. var color = this._colors4[name];
  16968. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16969. }
  16970. // Vector2
  16971. for (name in this._vectors2) {
  16972. this._effect.setVector2(name, this._vectors2[name]);
  16973. }
  16974. // Vector3
  16975. for (name in this._vectors3) {
  16976. this._effect.setVector3(name, this._vectors3[name]);
  16977. }
  16978. // Matrix
  16979. for (name in this._matrices) {
  16980. this._effect.setMatrix(name, this._matrices[name]);
  16981. }
  16982. // VBOs
  16983. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16984. // Draw order
  16985. engine.draw(true, 0, 6);
  16986. // Unbind
  16987. engine.unBindFramebuffer(this._texture);
  16988. };
  16989. ProceduralTexture.prototype.clone = function () {
  16990. var textureSize = this.getSize();
  16991. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16992. // Base texture
  16993. newTexture.hasAlpha = this.hasAlpha;
  16994. newTexture.level = this.level;
  16995. // RenderTarget Texture
  16996. newTexture.coordinatesMode = this.coordinatesMode;
  16997. return newTexture;
  16998. };
  16999. ProceduralTexture.prototype.dispose = function () {
  17000. var index = this.getScene()._proceduralTextures.indexOf(this);
  17001. if (index >= 0) {
  17002. this.getScene()._proceduralTextures.splice(index, 1);
  17003. }
  17004. _super.prototype.dispose.call(this);
  17005. };
  17006. return ProceduralTexture;
  17007. })(BABYLON.Texture);
  17008. BABYLON.ProceduralTexture = ProceduralTexture;
  17009. })(BABYLON || (BABYLON = {}));
  17010. var BABYLON;
  17011. (function (BABYLON) {
  17012. var MirrorTexture = (function (_super) {
  17013. __extends(MirrorTexture, _super);
  17014. function MirrorTexture(name, size, scene, generateMipMaps) {
  17015. var _this = this;
  17016. _super.call(this, name, size, scene, generateMipMaps, true);
  17017. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17018. this._transformMatrix = BABYLON.Matrix.Zero();
  17019. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17020. this.onBeforeRender = function () {
  17021. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17022. _this._savedViewMatrix = scene.getViewMatrix();
  17023. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17024. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17025. scene.clipPlane = _this.mirrorPlane;
  17026. scene.getEngine().cullBackFaces = false;
  17027. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17028. };
  17029. this.onAfterRender = function () {
  17030. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17031. scene.getEngine().cullBackFaces = true;
  17032. scene._mirroredCameraPosition = null;
  17033. delete scene.clipPlane;
  17034. };
  17035. }
  17036. MirrorTexture.prototype.clone = function () {
  17037. var textureSize = this.getSize();
  17038. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17039. // Base texture
  17040. newTexture.hasAlpha = this.hasAlpha;
  17041. newTexture.level = this.level;
  17042. // Mirror Texture
  17043. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17044. newTexture.renderList = this.renderList.slice(0);
  17045. return newTexture;
  17046. };
  17047. return MirrorTexture;
  17048. })(BABYLON.RenderTargetTexture);
  17049. BABYLON.MirrorTexture = MirrorTexture;
  17050. })(BABYLON || (BABYLON = {}));
  17051. var BABYLON;
  17052. (function (BABYLON) {
  17053. var DynamicTexture = (function (_super) {
  17054. __extends(DynamicTexture, _super);
  17055. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17057. _super.call(this, null, scene, !generateMipMaps);
  17058. this.name = name;
  17059. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17060. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17061. this._generateMipMaps = generateMipMaps;
  17062. if (options.getContext) {
  17063. this._canvas = options;
  17064. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17065. }
  17066. else {
  17067. this._canvas = document.createElement("canvas");
  17068. if (options.width) {
  17069. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17070. }
  17071. else {
  17072. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17073. }
  17074. }
  17075. var textureSize = this.getSize();
  17076. this._canvas.width = textureSize.width;
  17077. this._canvas.height = textureSize.height;
  17078. this._context = this._canvas.getContext("2d");
  17079. }
  17080. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17081. get: function () {
  17082. return true;
  17083. },
  17084. enumerable: true,
  17085. configurable: true
  17086. });
  17087. DynamicTexture.prototype.scale = function (ratio) {
  17088. var textureSize = this.getSize();
  17089. textureSize.width *= ratio;
  17090. textureSize.height *= ratio;
  17091. this._canvas.width = textureSize.width;
  17092. this._canvas.height = textureSize.height;
  17093. this.releaseInternalTexture();
  17094. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17095. };
  17096. DynamicTexture.prototype.getContext = function () {
  17097. return this._context;
  17098. };
  17099. DynamicTexture.prototype.clear = function () {
  17100. var size = this.getSize();
  17101. this._context.fillRect(0, 0, size.width, size.height);
  17102. };
  17103. DynamicTexture.prototype.update = function (invertY) {
  17104. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17105. };
  17106. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17107. if (update === void 0) { update = true; }
  17108. var size = this.getSize();
  17109. if (clearColor) {
  17110. this._context.fillStyle = clearColor;
  17111. this._context.fillRect(0, 0, size.width, size.height);
  17112. }
  17113. this._context.font = font;
  17114. if (x === null) {
  17115. var textSize = this._context.measureText(text);
  17116. x = (size.width - textSize.width) / 2;
  17117. }
  17118. this._context.fillStyle = color;
  17119. this._context.fillText(text, x, y);
  17120. if (update) {
  17121. this.update(invertY);
  17122. }
  17123. };
  17124. DynamicTexture.prototype.clone = function () {
  17125. var textureSize = this.getSize();
  17126. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17127. // Base texture
  17128. newTexture.hasAlpha = this.hasAlpha;
  17129. newTexture.level = this.level;
  17130. // Dynamic Texture
  17131. newTexture.wrapU = this.wrapU;
  17132. newTexture.wrapV = this.wrapV;
  17133. return newTexture;
  17134. };
  17135. return DynamicTexture;
  17136. })(BABYLON.Texture);
  17137. BABYLON.DynamicTexture = DynamicTexture;
  17138. })(BABYLON || (BABYLON = {}));
  17139. var BABYLON;
  17140. (function (BABYLON) {
  17141. var VideoTexture = (function (_super) {
  17142. __extends(VideoTexture, _super);
  17143. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17144. var _this = this;
  17145. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17146. if (invertY === void 0) { invertY = false; }
  17147. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17148. _super.call(this, null, scene, !generateMipMaps, invertY);
  17149. this._autoLaunch = true;
  17150. this.name = name;
  17151. this.video = document.createElement("video");
  17152. this.video.autoplay = false;
  17153. this.video.loop = true;
  17154. this.video.addEventListener("canplaythrough", function () {
  17155. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17156. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17157. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17158. }
  17159. else {
  17160. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17161. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17162. generateMipMaps = false;
  17163. }
  17164. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17165. _this._texture.isReady = true;
  17166. });
  17167. urls.forEach(function (url) {
  17168. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17169. var source = document.createElement("source");
  17170. source.src = url;
  17171. _this.video.appendChild(source);
  17172. });
  17173. this._lastUpdate = BABYLON.Tools.Now;
  17174. }
  17175. VideoTexture.prototype.update = function () {
  17176. if (this._autoLaunch) {
  17177. this._autoLaunch = false;
  17178. this.video.play();
  17179. }
  17180. var now = BABYLON.Tools.Now;
  17181. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17182. return false;
  17183. }
  17184. this._lastUpdate = now;
  17185. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17186. return true;
  17187. };
  17188. return VideoTexture;
  17189. })(BABYLON.Texture);
  17190. BABYLON.VideoTexture = VideoTexture;
  17191. })(BABYLON || (BABYLON = {}));
  17192. var BABYLON;
  17193. (function (BABYLON) {
  17194. var CustomProceduralTexture = (function (_super) {
  17195. __extends(CustomProceduralTexture, _super);
  17196. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17197. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17198. this._animate = true;
  17199. this._time = 0;
  17200. this._texturePath = texturePath;
  17201. //Try to load json
  17202. this.loadJson(texturePath);
  17203. this.refreshRate = 1;
  17204. }
  17205. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17206. var _this = this;
  17207. var that = this;
  17208. function noConfigFile() {
  17209. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17210. try {
  17211. that.setFragment(that._texturePath);
  17212. }
  17213. catch (ex) {
  17214. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17215. }
  17216. }
  17217. var configFileUrl = jsonUrl + "/config.json";
  17218. var xhr = new XMLHttpRequest();
  17219. xhr.open("GET", configFileUrl, true);
  17220. xhr.addEventListener("load", function () {
  17221. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17222. try {
  17223. _this._config = JSON.parse(xhr.response);
  17224. _this.updateShaderUniforms();
  17225. _this.updateTextures();
  17226. _this.setFragment(_this._texturePath + "/custom");
  17227. _this._animate = _this._config.animate;
  17228. _this.refreshRate = _this._config.refreshrate;
  17229. }
  17230. catch (ex) {
  17231. noConfigFile();
  17232. }
  17233. }
  17234. else {
  17235. noConfigFile();
  17236. }
  17237. }, false);
  17238. xhr.addEventListener("error", function () {
  17239. noConfigFile();
  17240. }, false);
  17241. try {
  17242. xhr.send();
  17243. }
  17244. catch (ex) {
  17245. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17246. }
  17247. };
  17248. CustomProceduralTexture.prototype.isReady = function () {
  17249. if (!_super.prototype.isReady.call(this)) {
  17250. return false;
  17251. }
  17252. for (var name in this._textures) {
  17253. var texture = this._textures[name];
  17254. if (!texture.isReady()) {
  17255. return false;
  17256. }
  17257. }
  17258. return true;
  17259. };
  17260. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17261. if (this._animate) {
  17262. this._time += this.getScene().getAnimationRatio() * 0.03;
  17263. this.updateShaderUniforms();
  17264. }
  17265. _super.prototype.render.call(this, useCameraPostProcess);
  17266. };
  17267. CustomProceduralTexture.prototype.updateTextures = function () {
  17268. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17269. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17270. }
  17271. };
  17272. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17273. if (this._config) {
  17274. for (var j = 0; j < this._config.uniforms.length; j++) {
  17275. var uniform = this._config.uniforms[j];
  17276. switch (uniform.type) {
  17277. case "float":
  17278. this.setFloat(uniform.name, uniform.value);
  17279. break;
  17280. case "color3":
  17281. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17282. break;
  17283. case "color4":
  17284. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17285. break;
  17286. case "vector2":
  17287. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17288. break;
  17289. case "vector3":
  17290. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17291. break;
  17292. }
  17293. }
  17294. }
  17295. this.setFloat("time", this._time);
  17296. };
  17297. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17298. get: function () {
  17299. return this._animate;
  17300. },
  17301. set: function (value) {
  17302. this._animate = value;
  17303. },
  17304. enumerable: true,
  17305. configurable: true
  17306. });
  17307. return CustomProceduralTexture;
  17308. })(BABYLON.ProceduralTexture);
  17309. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17310. })(BABYLON || (BABYLON = {}));
  17311. var BABYLON;
  17312. (function (BABYLON) {
  17313. var WoodProceduralTexture = (function (_super) {
  17314. __extends(WoodProceduralTexture, _super);
  17315. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17316. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17317. this._ampScale = 100.0;
  17318. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17319. this.updateShaderUniforms();
  17320. this.refreshRate = 0;
  17321. }
  17322. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17323. this.setFloat("ampScale", this._ampScale);
  17324. this.setColor3("woodColor", this._woodColor);
  17325. };
  17326. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17327. get: function () {
  17328. return this._ampScale;
  17329. },
  17330. set: function (value) {
  17331. this._ampScale = value;
  17332. this.updateShaderUniforms();
  17333. },
  17334. enumerable: true,
  17335. configurable: true
  17336. });
  17337. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17338. get: function () {
  17339. return this._woodColor;
  17340. },
  17341. set: function (value) {
  17342. this._woodColor = value;
  17343. this.updateShaderUniforms();
  17344. },
  17345. enumerable: true,
  17346. configurable: true
  17347. });
  17348. return WoodProceduralTexture;
  17349. })(BABYLON.ProceduralTexture);
  17350. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17351. var FireProceduralTexture = (function (_super) {
  17352. __extends(FireProceduralTexture, _super);
  17353. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17354. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17355. this._time = 0.0;
  17356. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17357. this._autoGenerateTime = true;
  17358. this._alphaThreshold = 0.5;
  17359. this._fireColors = FireProceduralTexture.RedFireColors;
  17360. this.updateShaderUniforms();
  17361. this.refreshRate = 1;
  17362. }
  17363. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17364. this.setFloat("time", this._time);
  17365. this.setVector2("speed", this._speed);
  17366. this.setColor3("c1", this._fireColors[0]);
  17367. this.setColor3("c2", this._fireColors[1]);
  17368. this.setColor3("c3", this._fireColors[2]);
  17369. this.setColor3("c4", this._fireColors[3]);
  17370. this.setColor3("c5", this._fireColors[4]);
  17371. this.setColor3("c6", this._fireColors[5]);
  17372. this.setFloat("alphaThreshold", this._alphaThreshold);
  17373. };
  17374. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17375. if (this._autoGenerateTime) {
  17376. this._time += this.getScene().getAnimationRatio() * 0.03;
  17377. this.updateShaderUniforms();
  17378. }
  17379. _super.prototype.render.call(this, useCameraPostProcess);
  17380. };
  17381. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17382. get: function () {
  17383. return [
  17384. new BABYLON.Color3(0.5, 0.0, 1.0),
  17385. new BABYLON.Color3(0.9, 0.0, 1.0),
  17386. new BABYLON.Color3(0.2, 0.0, 1.0),
  17387. new BABYLON.Color3(1.0, 0.9, 1.0),
  17388. new BABYLON.Color3(0.1, 0.1, 1.0),
  17389. new BABYLON.Color3(0.9, 0.9, 1.0)
  17390. ];
  17391. },
  17392. enumerable: true,
  17393. configurable: true
  17394. });
  17395. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17396. get: function () {
  17397. return [
  17398. new BABYLON.Color3(0.5, 1.0, 0.0),
  17399. new BABYLON.Color3(0.5, 1.0, 0.0),
  17400. new BABYLON.Color3(0.3, 0.4, 0.0),
  17401. new BABYLON.Color3(0.5, 1.0, 0.0),
  17402. new BABYLON.Color3(0.2, 0.0, 0.0),
  17403. new BABYLON.Color3(0.5, 1.0, 0.0)
  17404. ];
  17405. },
  17406. enumerable: true,
  17407. configurable: true
  17408. });
  17409. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17410. get: function () {
  17411. return [
  17412. new BABYLON.Color3(0.5, 0.0, 0.1),
  17413. new BABYLON.Color3(0.9, 0.0, 0.0),
  17414. new BABYLON.Color3(0.2, 0.0, 0.0),
  17415. new BABYLON.Color3(1.0, 0.9, 0.0),
  17416. new BABYLON.Color3(0.1, 0.1, 0.1),
  17417. new BABYLON.Color3(0.9, 0.9, 0.9)
  17418. ];
  17419. },
  17420. enumerable: true,
  17421. configurable: true
  17422. });
  17423. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17424. get: function () {
  17425. return [
  17426. new BABYLON.Color3(0.1, 0.0, 0.5),
  17427. new BABYLON.Color3(0.0, 0.0, 0.5),
  17428. new BABYLON.Color3(0.1, 0.0, 0.2),
  17429. new BABYLON.Color3(0.0, 0.0, 1.0),
  17430. new BABYLON.Color3(0.1, 0.2, 0.3),
  17431. new BABYLON.Color3(0.0, 0.2, 0.9)
  17432. ];
  17433. },
  17434. enumerable: true,
  17435. configurable: true
  17436. });
  17437. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17438. get: function () {
  17439. return this._fireColors;
  17440. },
  17441. set: function (value) {
  17442. this._fireColors = value;
  17443. this.updateShaderUniforms();
  17444. },
  17445. enumerable: true,
  17446. configurable: true
  17447. });
  17448. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17449. get: function () {
  17450. return this._time;
  17451. },
  17452. set: function (value) {
  17453. this._time = value;
  17454. this.updateShaderUniforms();
  17455. },
  17456. enumerable: true,
  17457. configurable: true
  17458. });
  17459. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17460. get: function () {
  17461. return this._speed;
  17462. },
  17463. set: function (value) {
  17464. this._speed = value;
  17465. this.updateShaderUniforms();
  17466. },
  17467. enumerable: true,
  17468. configurable: true
  17469. });
  17470. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17471. get: function () {
  17472. return this._alphaThreshold;
  17473. },
  17474. set: function (value) {
  17475. this._alphaThreshold = value;
  17476. this.updateShaderUniforms();
  17477. },
  17478. enumerable: true,
  17479. configurable: true
  17480. });
  17481. return FireProceduralTexture;
  17482. })(BABYLON.ProceduralTexture);
  17483. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17484. var CloudProceduralTexture = (function (_super) {
  17485. __extends(CloudProceduralTexture, _super);
  17486. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17487. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17488. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17489. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17490. this.updateShaderUniforms();
  17491. this.refreshRate = 0;
  17492. }
  17493. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17494. this.setColor4("skyColor", this._skyColor);
  17495. this.setColor4("cloudColor", this._cloudColor);
  17496. };
  17497. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17498. get: function () {
  17499. return this._skyColor;
  17500. },
  17501. set: function (value) {
  17502. this._skyColor = value;
  17503. this.updateShaderUniforms();
  17504. },
  17505. enumerable: true,
  17506. configurable: true
  17507. });
  17508. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17509. get: function () {
  17510. return this._cloudColor;
  17511. },
  17512. set: function (value) {
  17513. this._cloudColor = value;
  17514. this.updateShaderUniforms();
  17515. },
  17516. enumerable: true,
  17517. configurable: true
  17518. });
  17519. return CloudProceduralTexture;
  17520. })(BABYLON.ProceduralTexture);
  17521. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17522. var GrassProceduralTexture = (function (_super) {
  17523. __extends(GrassProceduralTexture, _super);
  17524. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17525. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17526. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17527. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17528. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17529. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17530. this._grassColors = [
  17531. new BABYLON.Color3(0.29, 0.38, 0.02),
  17532. new BABYLON.Color3(0.36, 0.49, 0.09),
  17533. new BABYLON.Color3(0.51, 0.6, 0.28)
  17534. ];
  17535. this.updateShaderUniforms();
  17536. this.refreshRate = 0;
  17537. }
  17538. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17539. this.setColor3("herb1Color", this._grassColors[0]);
  17540. this.setColor3("herb2Color", this._grassColors[1]);
  17541. this.setColor3("herb3Color", this._grassColors[2]);
  17542. this.setColor3("groundColor", this._groundColor);
  17543. };
  17544. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17545. get: function () {
  17546. return this._grassColors;
  17547. },
  17548. set: function (value) {
  17549. this._grassColors = value;
  17550. this.updateShaderUniforms();
  17551. },
  17552. enumerable: true,
  17553. configurable: true
  17554. });
  17555. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17556. get: function () {
  17557. return this._groundColor;
  17558. },
  17559. set: function (value) {
  17560. this.groundColor = value;
  17561. this.updateShaderUniforms();
  17562. },
  17563. enumerable: true,
  17564. configurable: true
  17565. });
  17566. return GrassProceduralTexture;
  17567. })(BABYLON.ProceduralTexture);
  17568. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17569. var RoadProceduralTexture = (function (_super) {
  17570. __extends(RoadProceduralTexture, _super);
  17571. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17572. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17573. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17574. this.updateShaderUniforms();
  17575. this.refreshRate = 0;
  17576. }
  17577. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17578. this.setColor3("roadColor", this._roadColor);
  17579. };
  17580. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17581. get: function () {
  17582. return this._roadColor;
  17583. },
  17584. set: function (value) {
  17585. this._roadColor = value;
  17586. this.updateShaderUniforms();
  17587. },
  17588. enumerable: true,
  17589. configurable: true
  17590. });
  17591. return RoadProceduralTexture;
  17592. })(BABYLON.ProceduralTexture);
  17593. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17594. var BrickProceduralTexture = (function (_super) {
  17595. __extends(BrickProceduralTexture, _super);
  17596. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17597. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17598. this._numberOfBricksHeight = 15;
  17599. this._numberOfBricksWidth = 5;
  17600. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17601. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17602. this.updateShaderUniforms();
  17603. this.refreshRate = 0;
  17604. }
  17605. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17606. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17607. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17608. this.setColor3("brickColor", this._brickColor);
  17609. this.setColor3("jointColor", this._jointColor);
  17610. };
  17611. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17612. get: function () {
  17613. return this._numberOfBricksHeight;
  17614. },
  17615. set: function (value) {
  17616. this._numberOfBricksHeight = value;
  17617. this.updateShaderUniforms();
  17618. },
  17619. enumerable: true,
  17620. configurable: true
  17621. });
  17622. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17623. get: function () {
  17624. return this._numberOfBricksWidth;
  17625. },
  17626. set: function (value) {
  17627. this._numberOfBricksWidth = value;
  17628. this.updateShaderUniforms();
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17634. get: function () {
  17635. return this._jointColor;
  17636. },
  17637. set: function (value) {
  17638. this._jointColor = value;
  17639. this.updateShaderUniforms();
  17640. },
  17641. enumerable: true,
  17642. configurable: true
  17643. });
  17644. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17645. get: function () {
  17646. return this._brickColor;
  17647. },
  17648. set: function (value) {
  17649. this._brickColor = value;
  17650. this.updateShaderUniforms();
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. return BrickProceduralTexture;
  17656. })(BABYLON.ProceduralTexture);
  17657. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17658. var MarbleProceduralTexture = (function (_super) {
  17659. __extends(MarbleProceduralTexture, _super);
  17660. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17661. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17662. this._numberOfTilesHeight = 3;
  17663. this._numberOfTilesWidth = 3;
  17664. this._amplitude = 9.0;
  17665. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17666. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17667. this.updateShaderUniforms();
  17668. this.refreshRate = 0;
  17669. }
  17670. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17671. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17672. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17673. this.setFloat("amplitude", this._amplitude);
  17674. this.setColor3("marbleColor", this._marbleColor);
  17675. this.setColor3("jointColor", this._jointColor);
  17676. };
  17677. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17678. get: function () {
  17679. return this._numberOfTilesHeight;
  17680. },
  17681. set: function (value) {
  17682. this._numberOfTilesHeight = value;
  17683. this.updateShaderUniforms();
  17684. },
  17685. enumerable: true,
  17686. configurable: true
  17687. });
  17688. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17689. get: function () {
  17690. return this._numberOfTilesWidth;
  17691. },
  17692. set: function (value) {
  17693. this._numberOfTilesWidth = value;
  17694. this.updateShaderUniforms();
  17695. },
  17696. enumerable: true,
  17697. configurable: true
  17698. });
  17699. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17700. get: function () {
  17701. return this._jointColor;
  17702. },
  17703. set: function (value) {
  17704. this._jointColor = value;
  17705. this.updateShaderUniforms();
  17706. },
  17707. enumerable: true,
  17708. configurable: true
  17709. });
  17710. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17711. get: function () {
  17712. return this._marbleColor;
  17713. },
  17714. set: function (value) {
  17715. this._marbleColor = value;
  17716. this.updateShaderUniforms();
  17717. },
  17718. enumerable: true,
  17719. configurable: true
  17720. });
  17721. return MarbleProceduralTexture;
  17722. })(BABYLON.ProceduralTexture);
  17723. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17724. })(BABYLON || (BABYLON = {}));
  17725. var BABYLON;
  17726. (function (BABYLON) {
  17727. var EffectFallbacks = (function () {
  17728. function EffectFallbacks() {
  17729. this._defines = {};
  17730. this._currentRank = 32;
  17731. this._maxRank = -1;
  17732. }
  17733. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17734. if (!this._defines[rank]) {
  17735. if (rank < this._currentRank) {
  17736. this._currentRank = rank;
  17737. }
  17738. if (rank > this._maxRank) {
  17739. this._maxRank = rank;
  17740. }
  17741. this._defines[rank] = new Array();
  17742. }
  17743. this._defines[rank].push(define);
  17744. };
  17745. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17746. get: function () {
  17747. return this._currentRank <= this._maxRank;
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17753. var currentFallbacks = this._defines[this._currentRank];
  17754. for (var index = 0; index < currentFallbacks.length; index++) {
  17755. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17756. }
  17757. this._currentRank++;
  17758. return currentDefines;
  17759. };
  17760. return EffectFallbacks;
  17761. })();
  17762. BABYLON.EffectFallbacks = EffectFallbacks;
  17763. var Effect = (function () {
  17764. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17765. var _this = this;
  17766. this._isReady = false;
  17767. this._compilationError = "";
  17768. this._valueCache = [];
  17769. this._engine = engine;
  17770. this.name = baseName;
  17771. this.defines = defines;
  17772. this._uniformsNames = uniformsNames.concat(samplers);
  17773. this._samplers = samplers;
  17774. this._attributesNames = attributesNames;
  17775. this.onError = onError;
  17776. this.onCompiled = onCompiled;
  17777. var vertexSource;
  17778. var fragmentSource;
  17779. if (baseName.vertexElement) {
  17780. vertexSource = document.getElementById(baseName.vertexElement);
  17781. if (!vertexSource) {
  17782. vertexSource = baseName.vertexElement;
  17783. }
  17784. }
  17785. else {
  17786. vertexSource = baseName.vertex || baseName;
  17787. }
  17788. if (baseName.fragmentElement) {
  17789. fragmentSource = document.getElementById(baseName.fragmentElement);
  17790. if (!fragmentSource) {
  17791. fragmentSource = baseName.fragmentElement;
  17792. }
  17793. }
  17794. else {
  17795. fragmentSource = baseName.fragment || baseName;
  17796. }
  17797. this._loadVertexShader(vertexSource, function (vertexCode) {
  17798. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17799. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17800. });
  17801. });
  17802. }
  17803. // Properties
  17804. Effect.prototype.isReady = function () {
  17805. return this._isReady;
  17806. };
  17807. Effect.prototype.getProgram = function () {
  17808. return this._program;
  17809. };
  17810. Effect.prototype.getAttributesNames = function () {
  17811. return this._attributesNames;
  17812. };
  17813. Effect.prototype.getAttributeLocation = function (index) {
  17814. return this._attributes[index];
  17815. };
  17816. Effect.prototype.getAttributeLocationByName = function (name) {
  17817. var index = this._attributesNames.indexOf(name);
  17818. return this._attributes[index];
  17819. };
  17820. Effect.prototype.getAttributesCount = function () {
  17821. return this._attributes.length;
  17822. };
  17823. Effect.prototype.getUniformIndex = function (uniformName) {
  17824. return this._uniformsNames.indexOf(uniformName);
  17825. };
  17826. Effect.prototype.getUniform = function (uniformName) {
  17827. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17828. };
  17829. Effect.prototype.getSamplers = function () {
  17830. return this._samplers;
  17831. };
  17832. Effect.prototype.getCompilationError = function () {
  17833. return this._compilationError;
  17834. };
  17835. // Methods
  17836. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17837. // DOM element ?
  17838. if (vertex instanceof HTMLElement) {
  17839. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17840. callback(vertexCode);
  17841. return;
  17842. }
  17843. // Is in local store ?
  17844. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17845. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17846. return;
  17847. }
  17848. var vertexShaderUrl;
  17849. if (vertex[0] === "." || vertex[0] === "/") {
  17850. vertexShaderUrl = vertex;
  17851. }
  17852. else {
  17853. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17854. }
  17855. // Vertex shader
  17856. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17857. };
  17858. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17859. // DOM element ?
  17860. if (fragment instanceof HTMLElement) {
  17861. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17862. callback(fragmentCode);
  17863. return;
  17864. }
  17865. // Is in local store ?
  17866. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17867. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17868. return;
  17869. }
  17870. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17871. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17872. return;
  17873. }
  17874. var fragmentShaderUrl;
  17875. if (fragment[0] === "." || fragment[0] === "/") {
  17876. fragmentShaderUrl = fragment;
  17877. }
  17878. else {
  17879. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17880. }
  17881. // Fragment shader
  17882. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17883. };
  17884. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17885. try {
  17886. var engine = this._engine;
  17887. if (!engine.getCaps().highPrecisionShaderSupported) {
  17888. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17889. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17890. }
  17891. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17892. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17893. this._attributes = engine.getAttributes(this._program, attributesNames);
  17894. for (var index = 0; index < this._samplers.length; index++) {
  17895. var sampler = this.getUniform(this._samplers[index]);
  17896. if (sampler == null) {
  17897. this._samplers.splice(index, 1);
  17898. index--;
  17899. }
  17900. }
  17901. engine.bindSamplers(this);
  17902. this._isReady = true;
  17903. if (this.onCompiled) {
  17904. this.onCompiled(this);
  17905. }
  17906. }
  17907. catch (e) {
  17908. // Is it a problem with precision?
  17909. if (e.message.indexOf("highp") !== -1) {
  17910. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17911. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17912. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17913. return;
  17914. }
  17915. // Let's go through fallbacks then
  17916. if (fallbacks && fallbacks.isMoreFallbacks) {
  17917. defines = fallbacks.reduce(defines);
  17918. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17919. }
  17920. else {
  17921. BABYLON.Tools.Error("Unable to compile effect: ");
  17922. if (this.name.vertexElement) {
  17923. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17924. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17925. }
  17926. else if (this.name.vertex) {
  17927. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17928. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17929. }
  17930. else {
  17931. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17932. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17933. }
  17934. BABYLON.Tools.Error("Defines: " + defines);
  17935. BABYLON.Tools.Error("Error: " + e.message);
  17936. this._compilationError = e.message;
  17937. if (this.onError) {
  17938. this.onError(this, this._compilationError);
  17939. }
  17940. }
  17941. }
  17942. };
  17943. Effect.prototype._bindTexture = function (channel, texture) {
  17944. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17945. };
  17946. Effect.prototype.setTexture = function (channel, texture) {
  17947. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17948. };
  17949. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17950. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17951. };
  17952. //public _cacheMatrix(uniformName, matrix) {
  17953. // if (!this._valueCache[uniformName]) {
  17954. // this._valueCache[uniformName] = new BABYLON.Matrix();
  17955. // }
  17956. // for (var index = 0; index < 16; index++) {
  17957. // this._valueCache[uniformName].m[index] = matrix.m[index];
  17958. // }
  17959. //};
  17960. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17961. if (!this._valueCache[uniformName]) {
  17962. this._valueCache[uniformName] = [x, y];
  17963. return;
  17964. }
  17965. this._valueCache[uniformName][0] = x;
  17966. this._valueCache[uniformName][1] = y;
  17967. };
  17968. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17969. if (!this._valueCache[uniformName]) {
  17970. this._valueCache[uniformName] = [x, y, z];
  17971. return;
  17972. }
  17973. this._valueCache[uniformName][0] = x;
  17974. this._valueCache[uniformName][1] = y;
  17975. this._valueCache[uniformName][2] = z;
  17976. };
  17977. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17978. if (!this._valueCache[uniformName]) {
  17979. this._valueCache[uniformName] = [x, y, z, w];
  17980. return;
  17981. }
  17982. this._valueCache[uniformName][0] = x;
  17983. this._valueCache[uniformName][1] = y;
  17984. this._valueCache[uniformName][2] = z;
  17985. this._valueCache[uniformName][3] = w;
  17986. };
  17987. Effect.prototype.setArray = function (uniformName, array) {
  17988. this._engine.setArray(this.getUniform(uniformName), array);
  17989. return this;
  17990. };
  17991. Effect.prototype.setArray2 = function (uniformName, array) {
  17992. this._engine.setArray2(this.getUniform(uniformName), array);
  17993. return this;
  17994. };
  17995. Effect.prototype.setArray3 = function (uniformName, array) {
  17996. this._engine.setArray3(this.getUniform(uniformName), array);
  17997. return this;
  17998. };
  17999. Effect.prototype.setArray4 = function (uniformName, array) {
  18000. this._engine.setArray4(this.getUniform(uniformName), array);
  18001. return this;
  18002. };
  18003. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18004. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18005. return this;
  18006. };
  18007. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18008. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18009. // return;
  18010. //this._cacheMatrix(uniformName, matrix);
  18011. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18012. return this;
  18013. };
  18014. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18015. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18016. return this;
  18017. };
  18018. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18019. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18020. return this;
  18021. };
  18022. Effect.prototype.setFloat = function (uniformName, value) {
  18023. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18024. return this;
  18025. this._valueCache[uniformName] = value;
  18026. this._engine.setFloat(this.getUniform(uniformName), value);
  18027. return this;
  18028. };
  18029. Effect.prototype.setBool = function (uniformName, bool) {
  18030. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18031. return this;
  18032. this._valueCache[uniformName] = bool;
  18033. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18034. return this;
  18035. };
  18036. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18037. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18038. return this;
  18039. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18040. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18041. return this;
  18042. };
  18043. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18044. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18045. return this;
  18046. this._cacheFloat2(uniformName, x, y);
  18047. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18048. return this;
  18049. };
  18050. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18051. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18052. return this;
  18053. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18054. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18055. return this;
  18056. };
  18057. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18058. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18059. return this;
  18060. this._cacheFloat3(uniformName, x, y, z);
  18061. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18062. return this;
  18063. };
  18064. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18065. 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)
  18066. return this;
  18067. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18068. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18069. return this;
  18070. };
  18071. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18072. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18073. return this;
  18074. this._cacheFloat4(uniformName, x, y, z, w);
  18075. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18076. return this;
  18077. };
  18078. Effect.prototype.setColor3 = function (uniformName, color3) {
  18079. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18080. return this;
  18081. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18082. this._engine.setColor3(this.getUniform(uniformName), color3);
  18083. return this;
  18084. };
  18085. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18086. 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)
  18087. return this;
  18088. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18089. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18090. return this;
  18091. };
  18092. // Statics
  18093. Effect.ShadersStore = {};
  18094. return Effect;
  18095. })();
  18096. BABYLON.Effect = Effect;
  18097. })(BABYLON || (BABYLON = {}));
  18098. var BABYLON;
  18099. (function (BABYLON) {
  18100. var Material = (function () {
  18101. function Material(name, scene, doNotAdd) {
  18102. this.name = name;
  18103. this.checkReadyOnEveryCall = true;
  18104. this.checkReadyOnlyOnce = false;
  18105. this.state = "";
  18106. this.alpha = 1.0;
  18107. this.backFaceCulling = true;
  18108. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18109. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18110. this.disableDepthWrite = false;
  18111. this.fogEnabled = true;
  18112. this._wasPreviouslyReady = false;
  18113. this._fillMode = Material.TriangleFillMode;
  18114. this.pointSize = 1.0;
  18115. this.zOffset = 0;
  18116. this.id = name;
  18117. this._scene = scene;
  18118. if (!doNotAdd) {
  18119. scene.materials.push(this);
  18120. }
  18121. }
  18122. Object.defineProperty(Material, "TriangleFillMode", {
  18123. get: function () {
  18124. return Material._TriangleFillMode;
  18125. },
  18126. enumerable: true,
  18127. configurable: true
  18128. });
  18129. Object.defineProperty(Material, "WireFrameFillMode", {
  18130. get: function () {
  18131. return Material._WireFrameFillMode;
  18132. },
  18133. enumerable: true,
  18134. configurable: true
  18135. });
  18136. Object.defineProperty(Material, "PointFillMode", {
  18137. get: function () {
  18138. return Material._PointFillMode;
  18139. },
  18140. enumerable: true,
  18141. configurable: true
  18142. });
  18143. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18144. get: function () {
  18145. return Material._ClockWiseSideOrientation;
  18146. },
  18147. enumerable: true,
  18148. configurable: true
  18149. });
  18150. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18151. get: function () {
  18152. return Material._CounterClockWiseSideOrientation;
  18153. },
  18154. enumerable: true,
  18155. configurable: true
  18156. });
  18157. Object.defineProperty(Material.prototype, "wireframe", {
  18158. get: function () {
  18159. return this._fillMode === Material.WireFrameFillMode;
  18160. },
  18161. set: function (value) {
  18162. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18163. },
  18164. enumerable: true,
  18165. configurable: true
  18166. });
  18167. Object.defineProperty(Material.prototype, "pointsCloud", {
  18168. get: function () {
  18169. return this._fillMode === Material.PointFillMode;
  18170. },
  18171. set: function (value) {
  18172. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18173. },
  18174. enumerable: true,
  18175. configurable: true
  18176. });
  18177. Object.defineProperty(Material.prototype, "fillMode", {
  18178. get: function () {
  18179. return this._fillMode;
  18180. },
  18181. set: function (value) {
  18182. this._fillMode = value;
  18183. },
  18184. enumerable: true,
  18185. configurable: true
  18186. });
  18187. Material.prototype.isReady = function (mesh, useInstances) {
  18188. return true;
  18189. };
  18190. Material.prototype.getEffect = function () {
  18191. return this._effect;
  18192. };
  18193. Material.prototype.getScene = function () {
  18194. return this._scene;
  18195. };
  18196. Material.prototype.needAlphaBlending = function () {
  18197. return (this.alpha < 1.0);
  18198. };
  18199. Material.prototype.needAlphaTesting = function () {
  18200. return false;
  18201. };
  18202. Material.prototype.getAlphaTestTexture = function () {
  18203. return null;
  18204. };
  18205. Material.prototype.trackCreation = function (onCompiled, onError) {
  18206. };
  18207. Material.prototype._preBind = function () {
  18208. var engine = this._scene.getEngine();
  18209. engine.enableEffect(this._effect);
  18210. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18211. };
  18212. Material.prototype.bind = function (world, mesh) {
  18213. this._scene._cachedMaterial = this;
  18214. if (this.onBind) {
  18215. this.onBind(this, mesh);
  18216. }
  18217. if (this.disableDepthWrite) {
  18218. var engine = this._scene.getEngine();
  18219. this._cachedDepthWriteState = engine.getDepthWrite();
  18220. engine.setDepthWrite(false);
  18221. }
  18222. };
  18223. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18224. };
  18225. Material.prototype.unbind = function () {
  18226. if (this.disableDepthWrite) {
  18227. var engine = this._scene.getEngine();
  18228. engine.setDepthWrite(this._cachedDepthWriteState);
  18229. }
  18230. };
  18231. Material.prototype.clone = function (name) {
  18232. return null;
  18233. };
  18234. Material.prototype.getBindedMeshes = function () {
  18235. var result = new Array();
  18236. for (var index = 0; index < this._scene.meshes.length; index++) {
  18237. var mesh = this._scene.meshes[index];
  18238. if (mesh.material === this) {
  18239. result.push(mesh);
  18240. }
  18241. }
  18242. return result;
  18243. };
  18244. Material.prototype.dispose = function (forceDisposeEffect) {
  18245. // Remove from scene
  18246. var index = this._scene.materials.indexOf(this);
  18247. if (index >= 0) {
  18248. this._scene.materials.splice(index, 1);
  18249. }
  18250. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18251. if (forceDisposeEffect && this._effect) {
  18252. this._scene.getEngine()._releaseEffect(this._effect);
  18253. this._effect = null;
  18254. }
  18255. // Remove from meshes
  18256. for (index = 0; index < this._scene.meshes.length; index++) {
  18257. var mesh = this._scene.meshes[index];
  18258. if (mesh.material === this) {
  18259. mesh.material = null;
  18260. }
  18261. }
  18262. // Callback
  18263. if (this.onDispose) {
  18264. this.onDispose();
  18265. }
  18266. };
  18267. Material.prototype.copyTo = function (other) {
  18268. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18269. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18270. other.alpha = this.alpha;
  18271. other.fillMode = this.fillMode;
  18272. other.backFaceCulling = this.backFaceCulling;
  18273. other.wireframe = this.wireframe;
  18274. other.fogEnabled = this.fogEnabled;
  18275. other.wireframe = this.wireframe;
  18276. other.zOffset = this.zOffset;
  18277. other.alphaMode = this.alphaMode;
  18278. other.sideOrientation = this.sideOrientation;
  18279. other.disableDepthWrite = this.disableDepthWrite;
  18280. other.pointSize = this.pointSize;
  18281. other.pointsCloud = this.pointsCloud;
  18282. };
  18283. Material._TriangleFillMode = 0;
  18284. Material._WireFrameFillMode = 1;
  18285. Material._PointFillMode = 2;
  18286. Material._ClockWiseSideOrientation = 0;
  18287. Material._CounterClockWiseSideOrientation = 1;
  18288. return Material;
  18289. })();
  18290. BABYLON.Material = Material;
  18291. })(BABYLON || (BABYLON = {}));
  18292. var BABYLON;
  18293. (function (BABYLON) {
  18294. var maxSimultaneousLights = 4;
  18295. var FresnelParameters = (function () {
  18296. function FresnelParameters() {
  18297. this.isEnabled = true;
  18298. this.leftColor = BABYLON.Color3.White();
  18299. this.rightColor = BABYLON.Color3.Black();
  18300. this.bias = 0;
  18301. this.power = 1;
  18302. }
  18303. FresnelParameters.prototype.clone = function () {
  18304. var newFresnelParameters = new FresnelParameters();
  18305. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18306. return new FresnelParameters;
  18307. };
  18308. return FresnelParameters;
  18309. })();
  18310. BABYLON.FresnelParameters = FresnelParameters;
  18311. var StandardMaterialDefines = (function () {
  18312. function StandardMaterialDefines() {
  18313. this.DIFFUSE = false;
  18314. this.AMBIENT = false;
  18315. this.OPACITY = false;
  18316. this.OPACITYRGB = false;
  18317. this.REFLECTION = false;
  18318. this.EMISSIVE = false;
  18319. this.SPECULAR = false;
  18320. this.BUMP = false;
  18321. this.SPECULAROVERALPHA = false;
  18322. this.CLIPPLANE = false;
  18323. this.ALPHATEST = false;
  18324. this.ALPHAFROMDIFFUSE = false;
  18325. this.POINTSIZE = false;
  18326. this.FOG = false;
  18327. this.LIGHT0 = false;
  18328. this.LIGHT1 = false;
  18329. this.LIGHT2 = false;
  18330. this.LIGHT3 = false;
  18331. this.SPOTLIGHT0 = false;
  18332. this.SPOTLIGHT1 = false;
  18333. this.SPOTLIGHT2 = false;
  18334. this.SPOTLIGHT3 = false;
  18335. this.HEMILIGHT0 = false;
  18336. this.HEMILIGHT1 = false;
  18337. this.HEMILIGHT2 = false;
  18338. this.HEMILIGHT3 = false;
  18339. this.POINTDIRLIGHT0 = false;
  18340. this.POINTDIRLIGHT1 = false;
  18341. this.POINTDIRLIGHT2 = false;
  18342. this.POINTDIRLIGHT3 = false;
  18343. this.SPECULARTERM = false;
  18344. this.SHADOW0 = false;
  18345. this.SHADOW1 = false;
  18346. this.SHADOW2 = false;
  18347. this.SHADOW3 = false;
  18348. this.SHADOWS = false;
  18349. this.SHADOWVSM0 = false;
  18350. this.SHADOWVSM1 = false;
  18351. this.SHADOWVSM2 = false;
  18352. this.SHADOWVSM3 = false;
  18353. this.SHADOWPCF0 = false;
  18354. this.SHADOWPCF1 = false;
  18355. this.SHADOWPCF2 = false;
  18356. this.SHADOWPCF3 = false;
  18357. this.DIFFUSEFRESNEL = false;
  18358. this.OPACITYFRESNEL = false;
  18359. this.REFLECTIONFRESNEL = false;
  18360. this.EMISSIVEFRESNEL = false;
  18361. this.FRESNEL = false;
  18362. this.NORMAL = false;
  18363. this.UV1 = false;
  18364. this.UV2 = false;
  18365. this.VERTEXCOLOR = false;
  18366. this.VERTEXALPHA = false;
  18367. this.BONES = false;
  18368. this.BONES4 = false;
  18369. this.BonesPerMesh = 0;
  18370. this.INSTANCES = false;
  18371. this.GLOSSINESS = false;
  18372. this.ROUGHNESS = false;
  18373. this.EMISSIVEASILLUMINATION = false;
  18374. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18375. this.LIGHTMAP = false;
  18376. this.REFLECTIONMAP_3D = false;
  18377. this.REFLECTIONMAP_SPHERICAL = false;
  18378. this.REFLECTIONMAP_PLANAR = false;
  18379. this.REFLECTIONMAP_CUBIC = false;
  18380. this.REFLECTIONMAP_PROJECTION = false;
  18381. this.REFLECTIONMAP_SKYBOX = false;
  18382. this.REFLECTIONMAP_EXPLICIT = false;
  18383. this.INVERTCUBICMAP = false;
  18384. this._keys = Object.keys(this);
  18385. }
  18386. StandardMaterialDefines.prototype.isEqual = function (other) {
  18387. for (var index = 0; index < this._keys.length; index++) {
  18388. var prop = this._keys[index];
  18389. if (this[prop] !== other[prop]) {
  18390. return false;
  18391. }
  18392. }
  18393. return true;
  18394. };
  18395. StandardMaterialDefines.prototype.cloneTo = function (other) {
  18396. for (var index = 0; index < this._keys.length; index++) {
  18397. var prop = this._keys[index];
  18398. other[prop] = this[prop];
  18399. }
  18400. };
  18401. StandardMaterialDefines.prototype.reset = function () {
  18402. for (var index = 0; index < this._keys.length; index++) {
  18403. var prop = this._keys[index];
  18404. if (prop === "BonesPerMesh") {
  18405. this[prop] = 0;
  18406. continue;
  18407. }
  18408. this[prop] = false;
  18409. }
  18410. };
  18411. StandardMaterialDefines.prototype.toString = function () {
  18412. var result = "";
  18413. for (var index = 0; index < this._keys.length; index++) {
  18414. var prop = this._keys[index];
  18415. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18416. result += "#define BonesPerMesh " + this[prop] + "\n";
  18417. continue;
  18418. }
  18419. if (this[prop]) {
  18420. result += "#define " + prop + "\n";
  18421. }
  18422. }
  18423. return result;
  18424. };
  18425. return StandardMaterialDefines;
  18426. })();
  18427. var StandardMaterial = (function (_super) {
  18428. __extends(StandardMaterial, _super);
  18429. function StandardMaterial(name, scene) {
  18430. var _this = this;
  18431. _super.call(this, name, scene);
  18432. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18433. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18434. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18435. this.specularPower = 64;
  18436. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18437. this.useAlphaFromDiffuseTexture = false;
  18438. this.useEmissiveAsIllumination = false;
  18439. this.useReflectionFresnelFromSpecular = false;
  18440. this.useSpecularOverAlpha = true;
  18441. this.disableLighting = false;
  18442. this.roughness = 0;
  18443. this.lightmapThreshold = 0;
  18444. this.useGlossinessFromSpecularMapAlpha = false;
  18445. this._renderTargets = new BABYLON.SmartArray(16);
  18446. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18447. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18448. this._scaledDiffuse = new BABYLON.Color3();
  18449. this._scaledSpecular = new BABYLON.Color3();
  18450. this._defines = new StandardMaterialDefines();
  18451. this._cachedDefines = new StandardMaterialDefines();
  18452. this._cachedDefines.BonesPerMesh = -1;
  18453. this.getRenderTargetTextures = function () {
  18454. _this._renderTargets.reset();
  18455. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18456. _this._renderTargets.push(_this.reflectionTexture);
  18457. }
  18458. return _this._renderTargets;
  18459. };
  18460. }
  18461. StandardMaterial.prototype.needAlphaBlending = function () {
  18462. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18463. };
  18464. StandardMaterial.prototype.needAlphaTesting = function () {
  18465. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18466. };
  18467. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18468. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18469. };
  18470. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18471. return this.diffuseTexture;
  18472. };
  18473. // Methods
  18474. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18475. if (this.checkReadyOnlyOnce) {
  18476. if (this._wasPreviouslyReady) {
  18477. return true;
  18478. }
  18479. }
  18480. var scene = this.getScene();
  18481. if (!this.checkReadyOnEveryCall) {
  18482. if (this._renderId === scene.getRenderId()) {
  18483. return true;
  18484. }
  18485. }
  18486. var engine = scene.getEngine();
  18487. var needNormals = false;
  18488. var needUVs = false;
  18489. this._defines.reset();
  18490. // Textures
  18491. if (scene.texturesEnabled) {
  18492. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18493. if (!this.diffuseTexture.isReady()) {
  18494. return false;
  18495. }
  18496. else {
  18497. needUVs = true;
  18498. this._defines.DIFFUSE = true;
  18499. }
  18500. }
  18501. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18502. if (!this.ambientTexture.isReady()) {
  18503. return false;
  18504. }
  18505. else {
  18506. needUVs = true;
  18507. this._defines.AMBIENT = true;
  18508. }
  18509. }
  18510. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18511. if (!this.opacityTexture.isReady()) {
  18512. return false;
  18513. }
  18514. else {
  18515. needUVs = true;
  18516. this._defines.OPACITY = true;
  18517. if (this.opacityTexture.getAlphaFromRGB) {
  18518. this._defines.OPACITYRGB = true;
  18519. }
  18520. }
  18521. }
  18522. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18523. if (!this.reflectionTexture.isReady()) {
  18524. return false;
  18525. }
  18526. else {
  18527. needNormals = true;
  18528. this._defines.REFLECTION = true;
  18529. if (this.roughness > 0) {
  18530. this._defines.ROUGHNESS = true;
  18531. }
  18532. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  18533. this._defines.INVERTCUBICMAP = true;
  18534. }
  18535. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  18536. switch (this.reflectionTexture.coordinatesMode) {
  18537. case BABYLON.Texture.CUBIC_MODE:
  18538. case BABYLON.Texture.INVCUBIC_MODE:
  18539. this._defines.REFLECTIONMAP_CUBIC = true;
  18540. break;
  18541. case BABYLON.Texture.EXPLICIT_MODE:
  18542. this._defines.REFLECTIONMAP_EXPLICIT = true;
  18543. break;
  18544. case BABYLON.Texture.PLANAR_MODE:
  18545. this._defines.REFLECTIONMAP_PLANAR = true;
  18546. break;
  18547. case BABYLON.Texture.PROJECTION_MODE:
  18548. this._defines.REFLECTIONMAP_PROJECTION = true;
  18549. break;
  18550. case BABYLON.Texture.SKYBOX_MODE:
  18551. this._defines.REFLECTIONMAP_SKYBOX = true;
  18552. break;
  18553. case BABYLON.Texture.SPHERICAL_MODE:
  18554. this._defines.REFLECTIONMAP_SPHERICAL = true;
  18555. break;
  18556. }
  18557. }
  18558. }
  18559. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18560. if (!this.emissiveTexture.isReady()) {
  18561. return false;
  18562. }
  18563. else {
  18564. needUVs = true;
  18565. this._defines.EMISSIVE = true;
  18566. }
  18567. }
  18568. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18569. if (!this.lightmapTexture.isReady()) {
  18570. return false;
  18571. }
  18572. else {
  18573. needUVs = true;
  18574. this._defines.LIGHTMAP = true;
  18575. }
  18576. }
  18577. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18578. if (!this.specularTexture.isReady()) {
  18579. return false;
  18580. }
  18581. else {
  18582. needUVs = true;
  18583. this._defines.SPECULAR = true;
  18584. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18585. }
  18586. }
  18587. }
  18588. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18589. if (!this.bumpTexture.isReady()) {
  18590. return false;
  18591. }
  18592. else {
  18593. needUVs = true;
  18594. this._defines.BUMP = true;
  18595. }
  18596. }
  18597. // Effect
  18598. if (scene.clipPlane) {
  18599. this._defines.CLIPPLANE = true;
  18600. }
  18601. if (engine.getAlphaTesting()) {
  18602. this._defines.ALPHATEST = true;
  18603. }
  18604. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18605. this._defines.ALPHAFROMDIFFUSE = true;
  18606. }
  18607. if (this.useEmissiveAsIllumination) {
  18608. this._defines.EMISSIVEASILLUMINATION = true;
  18609. }
  18610. if (this.useReflectionFresnelFromSpecular) {
  18611. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18612. }
  18613. // Point size
  18614. if (this.pointsCloud || scene.forcePointsCloud) {
  18615. this._defines.POINTSIZE = true;
  18616. }
  18617. // Fog
  18618. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18619. this._defines.FOG = true;
  18620. }
  18621. var lightIndex = 0;
  18622. if (scene.lightsEnabled && !this.disableLighting) {
  18623. for (var index = 0; index < scene.lights.length; index++) {
  18624. var light = scene.lights[index];
  18625. if (!light.isEnabled()) {
  18626. continue;
  18627. }
  18628. // Excluded check
  18629. if (light._excludedMeshesIds.length > 0) {
  18630. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18631. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18632. if (excludedMesh) {
  18633. light.excludedMeshes.push(excludedMesh);
  18634. }
  18635. }
  18636. light._excludedMeshesIds = [];
  18637. }
  18638. // Included check
  18639. if (light._includedOnlyMeshesIds.length > 0) {
  18640. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18641. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18642. if (includedOnlyMesh) {
  18643. light.includedOnlyMeshes.push(includedOnlyMesh);
  18644. }
  18645. }
  18646. light._includedOnlyMeshesIds = [];
  18647. }
  18648. if (!light.canAffectMesh(mesh)) {
  18649. continue;
  18650. }
  18651. needNormals = true;
  18652. this._defines["LIGHT" + lightIndex] = true;
  18653. var type;
  18654. if (light instanceof BABYLON.SpotLight) {
  18655. type = "SPOTLIGHT" + lightIndex;
  18656. }
  18657. else if (light instanceof BABYLON.HemisphericLight) {
  18658. type = "HEMILIGHT" + lightIndex;
  18659. }
  18660. else {
  18661. type = "POINTDIRLIGHT" + lightIndex;
  18662. }
  18663. this._defines[type] = true;
  18664. // Specular
  18665. if (!light.specular.equalsFloats(0, 0, 0)) {
  18666. this._defines.SPECULARTERM = true;
  18667. }
  18668. // Shadows
  18669. if (scene.shadowsEnabled) {
  18670. var shadowGenerator = light.getShadowGenerator();
  18671. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18672. this._defines["SHADOW" + lightIndex] = true;
  18673. this._defines.SHADOWS = true;
  18674. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18675. this._defines["SHADOWVSM" + lightIndex] = true;
  18676. }
  18677. if (shadowGenerator.usePoissonSampling) {
  18678. this._defines["SHADOWPCF" + lightIndex] = true;
  18679. }
  18680. }
  18681. }
  18682. lightIndex++;
  18683. if (lightIndex === maxSimultaneousLights)
  18684. break;
  18685. }
  18686. }
  18687. if (StandardMaterial.FresnelEnabled) {
  18688. // Fresnel
  18689. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18690. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18691. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18692. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18693. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18694. this._defines.DIFFUSEFRESNEL = true;
  18695. }
  18696. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18697. this._defines.OPACITYFRESNEL = true;
  18698. }
  18699. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18700. this._defines.REFLECTIONFRESNEL = true;
  18701. }
  18702. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18703. this._defines.EMISSIVEFRESNEL = true;
  18704. }
  18705. needNormals = true;
  18706. this._defines.FRESNEL = true;
  18707. }
  18708. }
  18709. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18710. this._defines.SPECULAROVERALPHA = true;
  18711. }
  18712. // Attribs
  18713. if (mesh) {
  18714. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18715. this._defines.NORMAL = true;
  18716. }
  18717. if (needUVs) {
  18718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18719. this._defines.UV1 = true;
  18720. }
  18721. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18722. this._defines.UV2 = true;
  18723. }
  18724. }
  18725. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18726. this._defines.VERTEXCOLOR = true;
  18727. if (mesh.hasVertexAlpha) {
  18728. this._defines.VERTEXALPHA = true;
  18729. }
  18730. }
  18731. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18732. this._defines.BONES = true;
  18733. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18734. this._defines.BONES4 = true;
  18735. }
  18736. // Instances
  18737. if (useInstances) {
  18738. this._defines.INSTANCES = true;
  18739. }
  18740. }
  18741. // Get correct effect
  18742. if (!this._defines.isEqual(this._cachedDefines)) {
  18743. this._defines.cloneTo(this._cachedDefines);
  18744. scene.resetCachedMaterial();
  18745. // Fallbacks
  18746. var fallbacks = new BABYLON.EffectFallbacks();
  18747. if (this._defines.REFLECTION) {
  18748. fallbacks.addFallback(0, "REFLECTION");
  18749. }
  18750. if (this._defines.SPECULAR) {
  18751. fallbacks.addFallback(0, "SPECULAR");
  18752. }
  18753. if (this._defines.BUMP) {
  18754. fallbacks.addFallback(0, "BUMP");
  18755. }
  18756. if (this._defines.SPECULAROVERALPHA) {
  18757. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18758. }
  18759. if (this._defines.FOG) {
  18760. fallbacks.addFallback(1, "FOG");
  18761. }
  18762. for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18763. if (!this._defines["LIGHT" + lightIndex]) {
  18764. continue;
  18765. }
  18766. if (lightIndex > 0) {
  18767. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18768. }
  18769. if (this._defines["SHADOW" + lightIndex]) {
  18770. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18771. }
  18772. if (this._defines["SHADOWPCF" + lightIndex]) {
  18773. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18774. }
  18775. if (this._defines["SHADOWVSM" + lightIndex]) {
  18776. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18777. }
  18778. }
  18779. if (this._defines.SPECULARTERM) {
  18780. fallbacks.addFallback(0, "SPECULARTERM");
  18781. }
  18782. if (this._defines.DIFFUSEFRESNEL) {
  18783. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18784. }
  18785. if (this._defines.OPACITYFRESNEL) {
  18786. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18787. }
  18788. if (this._defines.REFLECTIONFRESNEL) {
  18789. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18790. }
  18791. if (this._defines.EMISSIVEFRESNEL) {
  18792. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18793. }
  18794. if (this._defines.FRESNEL) {
  18795. fallbacks.addFallback(4, "FRESNEL");
  18796. }
  18797. if (this._defines.BONES4) {
  18798. fallbacks.addFallback(0, "BONES4");
  18799. }
  18800. //Attributes
  18801. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18802. if (this._defines.NORMAL) {
  18803. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18804. }
  18805. if (this._defines.UV1) {
  18806. attribs.push(BABYLON.VertexBuffer.UVKind);
  18807. }
  18808. if (this._defines.UV2) {
  18809. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18810. }
  18811. if (this._defines.VERTEXCOLOR) {
  18812. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18813. }
  18814. if (this._defines.BONES) {
  18815. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18816. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18817. }
  18818. if (this._defines.INSTANCES) {
  18819. attribs.push("world0");
  18820. attribs.push("world1");
  18821. attribs.push("world2");
  18822. attribs.push("world3");
  18823. }
  18824. // Legacy browser patch
  18825. var shaderName = "default";
  18826. if (!scene.getEngine().getCaps().standardDerivatives) {
  18827. shaderName = "legacydefault";
  18828. }
  18829. var join = this._defines.toString();
  18830. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18831. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18832. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18833. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18834. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18835. "vFogInfos", "vFogColor", "pointSize",
  18836. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  18837. "mBones",
  18838. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  18839. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18840. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18841. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  18842. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18843. ], join, fallbacks, this.onCompiled, this.onError);
  18844. }
  18845. if (!this._effect.isReady()) {
  18846. return false;
  18847. }
  18848. this._renderId = scene.getRenderId();
  18849. this._wasPreviouslyReady = true;
  18850. return true;
  18851. };
  18852. StandardMaterial.prototype.unbind = function () {
  18853. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18854. this._effect.setTexture("reflection2DSampler", null);
  18855. }
  18856. _super.prototype.unbind.call(this);
  18857. };
  18858. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18859. this._effect.setMatrix("world", world);
  18860. };
  18861. StandardMaterial.prototype.bind = function (world, mesh) {
  18862. var scene = this.getScene();
  18863. // Matrices
  18864. this.bindOnlyWorldMatrix(world);
  18865. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18866. // Bones
  18867. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  18868. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18869. }
  18870. if (scene.getCachedMaterial() !== this) {
  18871. if (StandardMaterial.FresnelEnabled) {
  18872. // Fresnel
  18873. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18874. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18875. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18876. }
  18877. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18878. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18879. }
  18880. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18881. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18882. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18883. }
  18884. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18885. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18886. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18887. }
  18888. }
  18889. // Textures
  18890. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18891. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18892. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18893. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18894. }
  18895. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18896. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18897. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18898. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18899. }
  18900. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18901. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18902. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18903. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18904. }
  18905. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18906. if (this.reflectionTexture.isCube) {
  18907. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18908. }
  18909. else {
  18910. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18911. }
  18912. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18913. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  18914. }
  18915. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18916. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18917. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18918. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18919. }
  18920. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18921. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  18922. this._effect.setFloat3("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level, this.lightmapThreshold);
  18923. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  18924. }
  18925. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18926. this._effect.setTexture("specularSampler", this.specularTexture);
  18927. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18928. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18929. }
  18930. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18931. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18932. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18933. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18934. }
  18935. // Clip plane
  18936. if (scene.clipPlane) {
  18937. var clipPlane = scene.clipPlane;
  18938. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18939. }
  18940. // Point size
  18941. if (this.pointsCloud) {
  18942. this._effect.setFloat("pointSize", this.pointSize);
  18943. }
  18944. // Colors
  18945. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18946. // Scaling down color according to emissive
  18947. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18948. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18949. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18950. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  18951. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18952. if (this._defines.SPECULARTERM) {
  18953. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18954. }
  18955. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18956. }
  18957. // Scaling down color according to emissive
  18958. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18959. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18960. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18961. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18962. if (scene.lightsEnabled && !this.disableLighting) {
  18963. var lightIndex = 0;
  18964. for (var index = 0; index < scene.lights.length; index++) {
  18965. var light = scene.lights[index];
  18966. if (!light.isEnabled()) {
  18967. continue;
  18968. }
  18969. if (!light.canAffectMesh(mesh)) {
  18970. continue;
  18971. }
  18972. if (light instanceof BABYLON.PointLight) {
  18973. // Point Light
  18974. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18975. }
  18976. else if (light instanceof BABYLON.DirectionalLight) {
  18977. // Directional Light
  18978. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18979. }
  18980. else if (light instanceof BABYLON.SpotLight) {
  18981. // Spot Light
  18982. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18983. }
  18984. else if (light instanceof BABYLON.HemisphericLight) {
  18985. // Hemispheric Light
  18986. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18987. }
  18988. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18989. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18990. if (this._defines.SPECULARTERM) {
  18991. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18992. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18993. }
  18994. // Shadows
  18995. if (scene.shadowsEnabled) {
  18996. var shadowGenerator = light.getShadowGenerator();
  18997. if (mesh.receiveShadows && shadowGenerator) {
  18998. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18999. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19000. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19001. }
  19002. }
  19003. lightIndex++;
  19004. if (lightIndex === maxSimultaneousLights)
  19005. break;
  19006. }
  19007. }
  19008. // View
  19009. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19010. this._effect.setMatrix("view", scene.getViewMatrix());
  19011. }
  19012. // Fog
  19013. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19014. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19015. this._effect.setColor3("vFogColor", scene.fogColor);
  19016. }
  19017. _super.prototype.bind.call(this, world, mesh);
  19018. };
  19019. StandardMaterial.prototype.getAnimatables = function () {
  19020. var results = [];
  19021. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19022. results.push(this.diffuseTexture);
  19023. }
  19024. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19025. results.push(this.ambientTexture);
  19026. }
  19027. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19028. results.push(this.opacityTexture);
  19029. }
  19030. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19031. results.push(this.reflectionTexture);
  19032. }
  19033. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19034. results.push(this.emissiveTexture);
  19035. }
  19036. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19037. results.push(this.specularTexture);
  19038. }
  19039. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19040. results.push(this.bumpTexture);
  19041. }
  19042. return results;
  19043. };
  19044. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19045. if (this.diffuseTexture) {
  19046. this.diffuseTexture.dispose();
  19047. }
  19048. if (this.ambientTexture) {
  19049. this.ambientTexture.dispose();
  19050. }
  19051. if (this.opacityTexture) {
  19052. this.opacityTexture.dispose();
  19053. }
  19054. if (this.reflectionTexture) {
  19055. this.reflectionTexture.dispose();
  19056. }
  19057. if (this.emissiveTexture) {
  19058. this.emissiveTexture.dispose();
  19059. }
  19060. if (this.specularTexture) {
  19061. this.specularTexture.dispose();
  19062. }
  19063. if (this.bumpTexture) {
  19064. this.bumpTexture.dispose();
  19065. }
  19066. _super.prototype.dispose.call(this, forceDisposeEffect);
  19067. };
  19068. StandardMaterial.prototype.clone = function (name) {
  19069. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19070. // Base material
  19071. this.copyTo(newStandardMaterial);
  19072. // Standard material
  19073. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19074. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19075. }
  19076. if (this.ambientTexture && this.ambientTexture.clone) {
  19077. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19078. }
  19079. if (this.opacityTexture && this.opacityTexture.clone) {
  19080. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19081. }
  19082. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19083. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19084. }
  19085. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19086. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19087. }
  19088. if (this.specularTexture && this.specularTexture.clone) {
  19089. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19090. }
  19091. if (this.bumpTexture && this.bumpTexture.clone) {
  19092. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19093. }
  19094. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19095. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19096. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19097. newStandardMaterial.lightmapThreshold = this.lightmapThreshold;
  19098. }
  19099. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19100. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19101. newStandardMaterial.specularColor = this.specularColor.clone();
  19102. newStandardMaterial.specularPower = this.specularPower;
  19103. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19104. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19105. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19106. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19107. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19108. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19109. newStandardMaterial.roughness = this.roughness;
  19110. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19111. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19112. }
  19113. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19114. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19115. }
  19116. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19117. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19118. }
  19119. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19120. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19121. }
  19122. return newStandardMaterial;
  19123. };
  19124. // Statics
  19125. // Flags used to enable or disable a type of texture for all Standard Materials
  19126. StandardMaterial.DiffuseTextureEnabled = true;
  19127. StandardMaterial.AmbientTextureEnabled = true;
  19128. StandardMaterial.OpacityTextureEnabled = true;
  19129. StandardMaterial.ReflectionTextureEnabled = true;
  19130. StandardMaterial.EmissiveTextureEnabled = true;
  19131. StandardMaterial.SpecularTextureEnabled = true;
  19132. StandardMaterial.BumpTextureEnabled = true;
  19133. StandardMaterial.FresnelEnabled = true;
  19134. StandardMaterial.LightmapEnabled = true;
  19135. return StandardMaterial;
  19136. })(BABYLON.Material);
  19137. BABYLON.StandardMaterial = StandardMaterial;
  19138. })(BABYLON || (BABYLON = {}));
  19139. var BABYLON;
  19140. (function (BABYLON) {
  19141. var MultiMaterial = (function (_super) {
  19142. __extends(MultiMaterial, _super);
  19143. function MultiMaterial(name, scene) {
  19144. _super.call(this, name, scene, true);
  19145. this.subMaterials = new Array();
  19146. scene.multiMaterials.push(this);
  19147. }
  19148. // Properties
  19149. MultiMaterial.prototype.getSubMaterial = function (index) {
  19150. if (index < 0 || index >= this.subMaterials.length) {
  19151. return this.getScene().defaultMaterial;
  19152. }
  19153. return this.subMaterials[index];
  19154. };
  19155. // Methods
  19156. MultiMaterial.prototype.isReady = function (mesh) {
  19157. for (var index = 0; index < this.subMaterials.length; index++) {
  19158. var subMaterial = this.subMaterials[index];
  19159. if (subMaterial) {
  19160. if (!this.subMaterials[index].isReady(mesh)) {
  19161. return false;
  19162. }
  19163. }
  19164. }
  19165. return true;
  19166. };
  19167. MultiMaterial.prototype.clone = function (name) {
  19168. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19169. for (var index = 0; index < this.subMaterials.length; index++) {
  19170. var subMaterial = this.subMaterials[index];
  19171. newMultiMaterial.subMaterials.push(subMaterial);
  19172. }
  19173. return newMultiMaterial;
  19174. };
  19175. return MultiMaterial;
  19176. })(BABYLON.Material);
  19177. BABYLON.MultiMaterial = MultiMaterial;
  19178. })(BABYLON || (BABYLON = {}));
  19179. var BABYLON;
  19180. (function (BABYLON) {
  19181. var SceneLoader = (function () {
  19182. function SceneLoader() {
  19183. }
  19184. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19185. get: function () {
  19186. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19187. },
  19188. set: function (value) {
  19189. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19190. },
  19191. enumerable: true,
  19192. configurable: true
  19193. });
  19194. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19195. get: function () {
  19196. return SceneLoader._ShowLoadingScreen;
  19197. },
  19198. set: function (value) {
  19199. SceneLoader._ShowLoadingScreen = value;
  19200. },
  19201. enumerable: true,
  19202. configurable: true
  19203. });
  19204. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19205. var dotPosition = sceneFilename.lastIndexOf(".");
  19206. var queryStringPosition = sceneFilename.indexOf("?");
  19207. if (queryStringPosition === -1) {
  19208. queryStringPosition = sceneFilename.length;
  19209. }
  19210. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19211. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19212. var plugin = this._registeredPlugins[index];
  19213. if (plugin.extensions.indexOf(extension) !== -1) {
  19214. return plugin;
  19215. }
  19216. }
  19217. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19218. };
  19219. // Public functions
  19220. SceneLoader.RegisterPlugin = function (plugin) {
  19221. plugin.extensions = plugin.extensions.toLowerCase();
  19222. SceneLoader._registeredPlugins.push(plugin);
  19223. };
  19224. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19225. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19226. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19227. return;
  19228. }
  19229. var loadingToken = {};
  19230. scene._addPendingData(loadingToken);
  19231. var manifestChecked = function (success) {
  19232. scene.database = database;
  19233. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19234. var importMeshFromData = function (data) {
  19235. var meshes = [];
  19236. var particleSystems = [];
  19237. var skeletons = [];
  19238. try {
  19239. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19240. if (onerror) {
  19241. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19242. }
  19243. scene._removePendingData(loadingToken);
  19244. return;
  19245. }
  19246. }
  19247. catch (e) {
  19248. if (onerror) {
  19249. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19250. }
  19251. scene._removePendingData(loadingToken);
  19252. return;
  19253. }
  19254. if (onsuccess) {
  19255. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19256. onsuccess(meshes, particleSystems, skeletons);
  19257. scene._removePendingData(loadingToken);
  19258. }
  19259. };
  19260. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19261. // Direct load
  19262. importMeshFromData(sceneFilename.substr(5));
  19263. return;
  19264. }
  19265. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19266. importMeshFromData(data);
  19267. }, progressCallBack, database);
  19268. };
  19269. if (scene.getEngine().enableOfflineSupport) {
  19270. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19271. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19272. }
  19273. else {
  19274. manifestChecked(true);
  19275. }
  19276. };
  19277. /**
  19278. * Load a scene
  19279. * @param rootUrl a string that defines the root url for scene and resources
  19280. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19281. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19282. */
  19283. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19284. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19285. };
  19286. /**
  19287. * Append a scene
  19288. * @param rootUrl a string that defines the root url for scene and resources
  19289. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19290. * @param scene is the instance of BABYLON.Scene to append to
  19291. */
  19292. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19293. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19294. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19295. return;
  19296. }
  19297. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19298. var database;
  19299. var loadingToken = {};
  19300. scene._addPendingData(loadingToken);
  19301. if (SceneLoader.ShowLoadingScreen) {
  19302. scene.getEngine().displayLoadingUI();
  19303. }
  19304. var loadSceneFromData = function (data) {
  19305. scene.database = database;
  19306. if (!plugin.load(scene, data, rootUrl)) {
  19307. if (onerror) {
  19308. onerror(scene);
  19309. }
  19310. scene._removePendingData(loadingToken);
  19311. scene.getEngine().hideLoadingUI();
  19312. return;
  19313. }
  19314. if (onsuccess) {
  19315. onsuccess(scene);
  19316. }
  19317. scene._removePendingData(loadingToken);
  19318. if (SceneLoader.ShowLoadingScreen) {
  19319. scene.executeWhenReady(function () {
  19320. scene.getEngine().hideLoadingUI();
  19321. });
  19322. }
  19323. };
  19324. var manifestChecked = function (success) {
  19325. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19326. };
  19327. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19328. // Direct load
  19329. loadSceneFromData(sceneFilename.substr(5));
  19330. return;
  19331. }
  19332. if (rootUrl.indexOf("file:") === -1) {
  19333. if (scene.getEngine().enableOfflineSupport) {
  19334. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19335. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19336. }
  19337. else {
  19338. manifestChecked(true);
  19339. }
  19340. }
  19341. else {
  19342. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19343. }
  19344. };
  19345. // Flags
  19346. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19347. SceneLoader._ShowLoadingScreen = true;
  19348. // Members
  19349. SceneLoader._registeredPlugins = new Array();
  19350. return SceneLoader;
  19351. })();
  19352. BABYLON.SceneLoader = SceneLoader;
  19353. ;
  19354. })(BABYLON || (BABYLON = {}));
  19355. var BABYLON;
  19356. (function (BABYLON) {
  19357. var Internals;
  19358. (function (Internals) {
  19359. var checkColors4 = function (colors, count) {
  19360. // Check if color3 was used
  19361. if (colors.length === count * 3) {
  19362. var colors4 = [];
  19363. for (var index = 0; index < colors.length; index += 3) {
  19364. var newIndex = (index / 3) * 4;
  19365. colors4[newIndex] = colors[index];
  19366. colors4[newIndex + 1] = colors[index + 1];
  19367. colors4[newIndex + 2] = colors[index + 2];
  19368. colors4[newIndex + 3] = 1.0;
  19369. }
  19370. return colors4;
  19371. }
  19372. return colors;
  19373. };
  19374. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19375. var texture = null;
  19376. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19377. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19378. texture.name = parsedTexture.name;
  19379. texture.hasAlpha = parsedTexture.hasAlpha;
  19380. texture.level = parsedTexture.level;
  19381. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19382. }
  19383. return texture;
  19384. };
  19385. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19386. if (parsedTexture.isCube) {
  19387. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19388. }
  19389. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19390. return null;
  19391. }
  19392. var texture;
  19393. if (parsedTexture.mirrorPlane) {
  19394. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19395. texture._waitingRenderList = parsedTexture.renderList;
  19396. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19397. }
  19398. else if (parsedTexture.isRenderTarget) {
  19399. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19400. texture._waitingRenderList = parsedTexture.renderList;
  19401. }
  19402. else {
  19403. if (parsedTexture.base64String) {
  19404. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19405. }
  19406. else {
  19407. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19408. }
  19409. }
  19410. texture.name = parsedTexture.name;
  19411. texture.hasAlpha = parsedTexture.hasAlpha;
  19412. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19413. texture.level = parsedTexture.level;
  19414. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19415. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19416. texture.uOffset = parsedTexture.uOffset;
  19417. texture.vOffset = parsedTexture.vOffset;
  19418. texture.uScale = parsedTexture.uScale;
  19419. texture.vScale = parsedTexture.vScale;
  19420. texture.uAng = parsedTexture.uAng;
  19421. texture.vAng = parsedTexture.vAng;
  19422. texture.wAng = parsedTexture.wAng;
  19423. texture.wrapU = parsedTexture.wrapU;
  19424. texture.wrapV = parsedTexture.wrapV;
  19425. // Animations
  19426. if (parsedTexture.animations) {
  19427. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19428. var parsedAnimation = parsedTexture.animations[animationIndex];
  19429. texture.animations.push(parseAnimation(parsedAnimation));
  19430. }
  19431. }
  19432. return texture;
  19433. };
  19434. var parseSkeleton = function (parsedSkeleton, scene) {
  19435. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19436. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19437. var parsedBone = parsedSkeleton.bones[index];
  19438. var parentBone = null;
  19439. if (parsedBone.parentBoneIndex > -1) {
  19440. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19441. }
  19442. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19443. if (parsedBone.animation) {
  19444. bone.animations.push(parseAnimation(parsedBone.animation));
  19445. }
  19446. }
  19447. return skeleton;
  19448. };
  19449. var parseFresnelParameters = function (parsedFresnelParameters) {
  19450. var fresnelParameters = new BABYLON.FresnelParameters();
  19451. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19452. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19453. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19454. fresnelParameters.bias = parsedFresnelParameters.bias;
  19455. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19456. return fresnelParameters;
  19457. };
  19458. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19459. var material;
  19460. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19461. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19462. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19463. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19464. material.specularPower = parsedMaterial.specularPower;
  19465. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19466. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19467. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19468. material.alpha = parsedMaterial.alpha;
  19469. material.id = parsedMaterial.id;
  19470. if (parsedMaterial.disableDepthWrite) {
  19471. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19472. }
  19473. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19474. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19475. material.wireframe = parsedMaterial.wireframe;
  19476. if (parsedMaterial.diffuseTexture) {
  19477. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19478. }
  19479. if (parsedMaterial.diffuseFresnelParameters) {
  19480. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19481. }
  19482. if (parsedMaterial.ambientTexture) {
  19483. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19484. }
  19485. if (parsedMaterial.opacityTexture) {
  19486. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19487. }
  19488. if (parsedMaterial.opacityFresnelParameters) {
  19489. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19490. }
  19491. if (parsedMaterial.reflectionTexture) {
  19492. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19493. }
  19494. if (parsedMaterial.reflectionFresnelParameters) {
  19495. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19496. }
  19497. if (parsedMaterial.emissiveTexture) {
  19498. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19499. }
  19500. if (parsedMaterial.lightmapTexture) {
  19501. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19502. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19503. }
  19504. if (parsedMaterial.emissiveFresnelParameters) {
  19505. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19506. }
  19507. if (parsedMaterial.specularTexture) {
  19508. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19509. }
  19510. if (parsedMaterial.bumpTexture) {
  19511. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19512. }
  19513. if (parsedMaterial.checkReadyOnlyOnce) {
  19514. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19515. }
  19516. return material;
  19517. };
  19518. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19519. for (var index = 0; index < parsedData.materials.length; index++) {
  19520. var parsedMaterial = parsedData.materials[index];
  19521. if (parsedMaterial.id === id) {
  19522. return parseMaterial(parsedMaterial, scene, rootUrl);
  19523. }
  19524. }
  19525. return null;
  19526. };
  19527. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19528. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19529. multiMaterial.id = parsedMultiMaterial.id;
  19530. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19531. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19532. var subMatId = parsedMultiMaterial.materials[matIndex];
  19533. if (subMatId) {
  19534. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19535. }
  19536. else {
  19537. multiMaterial.subMaterials.push(null);
  19538. }
  19539. }
  19540. return multiMaterial;
  19541. };
  19542. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19543. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19544. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19545. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19546. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19547. var parsedFlare = parsedLensFlareSystem.flares[index];
  19548. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19549. }
  19550. return lensFlareSystem;
  19551. };
  19552. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19553. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19554. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19555. if (parsedParticleSystem.textureName) {
  19556. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19557. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19558. }
  19559. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19560. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19561. particleSystem.minSize = parsedParticleSystem.minSize;
  19562. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19563. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19564. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19565. particleSystem.emitter = emitter;
  19566. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19567. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19568. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19569. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19570. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19571. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19572. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19573. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19574. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19575. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19576. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19577. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19578. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19579. particleSystem.start();
  19580. return particleSystem;
  19581. };
  19582. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19583. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19584. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19585. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19586. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19587. shadowGenerator.getShadowMap().renderList.push(mesh);
  19588. }
  19589. if (parsedShadowGenerator.usePoissonSampling) {
  19590. shadowGenerator.usePoissonSampling = true;
  19591. }
  19592. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19593. shadowGenerator.useVarianceShadowMap = true;
  19594. }
  19595. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19596. shadowGenerator.useBlurVarianceShadowMap = true;
  19597. if (parsedShadowGenerator.blurScale) {
  19598. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19599. }
  19600. if (parsedShadowGenerator.blurBoxOffset) {
  19601. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19602. }
  19603. }
  19604. if (parsedShadowGenerator.bias !== undefined) {
  19605. shadowGenerator.bias = parsedShadowGenerator.bias;
  19606. }
  19607. return shadowGenerator;
  19608. };
  19609. var parseAnimation = function (parsedAnimation) {
  19610. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19611. var dataType = parsedAnimation.dataType;
  19612. var keys = [];
  19613. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19614. var key = parsedAnimation.keys[index];
  19615. var data;
  19616. switch (dataType) {
  19617. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19618. data = key.values[0];
  19619. break;
  19620. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19621. data = BABYLON.Quaternion.FromArray(key.values);
  19622. break;
  19623. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19624. data = BABYLON.Matrix.FromArray(key.values);
  19625. break;
  19626. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19627. default:
  19628. data = BABYLON.Vector3.FromArray(key.values);
  19629. break;
  19630. }
  19631. keys.push({
  19632. frame: key.frame,
  19633. value: data
  19634. });
  19635. }
  19636. animation.setKeys(keys);
  19637. return animation;
  19638. };
  19639. var parseLight = function (parsedLight, scene) {
  19640. var light;
  19641. switch (parsedLight.type) {
  19642. case 0:
  19643. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19644. break;
  19645. case 1:
  19646. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19647. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19648. break;
  19649. case 2:
  19650. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19651. break;
  19652. case 3:
  19653. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19654. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19655. break;
  19656. }
  19657. light.id = parsedLight.id;
  19658. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19659. if (parsedLight.intensity !== undefined) {
  19660. light.intensity = parsedLight.intensity;
  19661. }
  19662. if (parsedLight.range) {
  19663. light.range = parsedLight.range;
  19664. }
  19665. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19666. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19667. if (parsedLight.excludedMeshesIds) {
  19668. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19669. }
  19670. // Parent
  19671. if (parsedLight.parentId) {
  19672. light._waitingParentId = parsedLight.parentId;
  19673. }
  19674. if (parsedLight.includedOnlyMeshesIds) {
  19675. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19676. }
  19677. // Animations
  19678. if (parsedLight.animations) {
  19679. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19680. var parsedAnimation = parsedLight.animations[animationIndex];
  19681. light.animations.push(parseAnimation(parsedAnimation));
  19682. }
  19683. }
  19684. if (parsedLight.autoAnimate) {
  19685. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19686. }
  19687. };
  19688. var parseCamera = function (parsedCamera, scene) {
  19689. var camera;
  19690. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19691. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19692. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19693. var alpha = parsedCamera.alpha;
  19694. var beta = parsedCamera.beta;
  19695. var radius = parsedCamera.radius;
  19696. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19697. var interaxial_distance = parsedCamera.interaxial_distance;
  19698. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19699. }
  19700. else {
  19701. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19702. }
  19703. }
  19704. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19705. interaxial_distance = parsedCamera.interaxial_distance;
  19706. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19707. }
  19708. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19709. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19710. }
  19711. else if (parsedCamera.type === "FollowCamera") {
  19712. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19713. camera.heightOffset = parsedCamera.heightOffset;
  19714. camera.radius = parsedCamera.radius;
  19715. camera.rotationOffset = parsedCamera.rotationOffset;
  19716. if (lockedTargetMesh)
  19717. camera.target = lockedTargetMesh;
  19718. }
  19719. else if (parsedCamera.type === "GamepadCamera") {
  19720. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19721. }
  19722. else if (parsedCamera.type === "TouchCamera") {
  19723. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19724. }
  19725. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19726. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19727. }
  19728. else if (parsedCamera.type === "WebVRFreeCamera") {
  19729. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19730. }
  19731. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19732. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19733. }
  19734. else {
  19735. // Free Camera is the default value
  19736. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19737. }
  19738. // apply 3d rig, when found
  19739. if (parsedCamera.cameraRigMode) {
  19740. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19741. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19742. }
  19743. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19744. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19745. camera.lockedTarget = lockedTargetMesh;
  19746. }
  19747. camera.id = parsedCamera.id;
  19748. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19749. // Parent
  19750. if (parsedCamera.parentId) {
  19751. camera._waitingParentId = parsedCamera.parentId;
  19752. }
  19753. // Target
  19754. if (parsedCamera.target) {
  19755. if (camera.setTarget) {
  19756. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19757. }
  19758. else {
  19759. //For ArcRotate
  19760. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19761. }
  19762. }
  19763. else {
  19764. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19765. }
  19766. camera.fov = parsedCamera.fov;
  19767. camera.minZ = parsedCamera.minZ;
  19768. camera.maxZ = parsedCamera.maxZ;
  19769. camera.speed = parsedCamera.speed;
  19770. camera.inertia = parsedCamera.inertia;
  19771. camera.checkCollisions = parsedCamera.checkCollisions;
  19772. camera.applyGravity = parsedCamera.applyGravity;
  19773. if (parsedCamera.ellipsoid) {
  19774. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19775. }
  19776. // Animations
  19777. if (parsedCamera.animations) {
  19778. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19779. var parsedAnimation = parsedCamera.animations[animationIndex];
  19780. camera.animations.push(parseAnimation(parsedAnimation));
  19781. }
  19782. }
  19783. if (parsedCamera.autoAnimate) {
  19784. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19785. }
  19786. // Layer Mask
  19787. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19788. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19789. }
  19790. else {
  19791. camera.layerMask = 0x0FFFFFFF;
  19792. }
  19793. return camera;
  19794. };
  19795. var parseGeometry = function (parsedGeometry, scene) {
  19796. var id = parsedGeometry.id;
  19797. return scene.getGeometryByID(id);
  19798. };
  19799. var parseBox = function (parsedBox, scene) {
  19800. if (parseGeometry(parsedBox, scene)) {
  19801. return null; // null since geometry could be something else than a box...
  19802. }
  19803. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19804. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19805. scene.pushGeometry(box, true);
  19806. return box;
  19807. };
  19808. var parseSphere = function (parsedSphere, scene) {
  19809. if (parseGeometry(parsedSphere, scene)) {
  19810. return null; // null since geometry could be something else than a sphere...
  19811. }
  19812. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19813. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19814. scene.pushGeometry(sphere, true);
  19815. return sphere;
  19816. };
  19817. var parseCylinder = function (parsedCylinder, scene) {
  19818. if (parseGeometry(parsedCylinder, scene)) {
  19819. return null; // null since geometry could be something else than a cylinder...
  19820. }
  19821. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19822. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19823. scene.pushGeometry(cylinder, true);
  19824. return cylinder;
  19825. };
  19826. var parseTorus = function (parsedTorus, scene) {
  19827. if (parseGeometry(parsedTorus, scene)) {
  19828. return null; // null since geometry could be something else than a torus...
  19829. }
  19830. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19831. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19832. scene.pushGeometry(torus, true);
  19833. return torus;
  19834. };
  19835. var parseGround = function (parsedGround, scene) {
  19836. if (parseGeometry(parsedGround, scene)) {
  19837. return null; // null since geometry could be something else than a ground...
  19838. }
  19839. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19840. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19841. scene.pushGeometry(ground, true);
  19842. return ground;
  19843. };
  19844. var parsePlane = function (parsedPlane, scene) {
  19845. if (parseGeometry(parsedPlane, scene)) {
  19846. return null; // null since geometry could be something else than a plane...
  19847. }
  19848. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19849. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19850. scene.pushGeometry(plane, true);
  19851. return plane;
  19852. };
  19853. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19854. if (parseGeometry(parsedTorusKnot, scene)) {
  19855. return null; // null since geometry could be something else than a torusKnot...
  19856. }
  19857. 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);
  19858. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19859. scene.pushGeometry(torusKnot, true);
  19860. return torusKnot;
  19861. };
  19862. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19863. if (parseGeometry(parsedVertexData, scene)) {
  19864. return null; // null since geometry could be a primitive
  19865. }
  19866. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19867. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19868. if (parsedVertexData.delayLoadingFile) {
  19869. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19870. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19871. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19872. geometry._delayInfo = [];
  19873. if (parsedVertexData.hasUVs) {
  19874. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19875. }
  19876. if (parsedVertexData.hasUVs2) {
  19877. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19878. }
  19879. if (parsedVertexData.hasUVs3) {
  19880. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19881. }
  19882. if (parsedVertexData.hasUVs4) {
  19883. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19884. }
  19885. if (parsedVertexData.hasUVs5) {
  19886. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19887. }
  19888. if (parsedVertexData.hasUVs6) {
  19889. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19890. }
  19891. if (parsedVertexData.hasColors) {
  19892. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19893. }
  19894. if (parsedVertexData.hasMatricesIndices) {
  19895. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19896. }
  19897. if (parsedVertexData.hasMatricesWeights) {
  19898. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19899. }
  19900. geometry._delayLoadingFunction = importVertexData;
  19901. }
  19902. else {
  19903. importVertexData(parsedVertexData, geometry);
  19904. }
  19905. scene.pushGeometry(geometry, true);
  19906. return geometry;
  19907. };
  19908. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19909. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19910. mesh.id = parsedMesh.id;
  19911. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19912. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19913. if (parsedMesh.rotationQuaternion) {
  19914. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19915. }
  19916. else if (parsedMesh.rotation) {
  19917. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19918. }
  19919. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19920. if (parsedMesh.localMatrix) {
  19921. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19922. }
  19923. else if (parsedMesh.pivotMatrix) {
  19924. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19925. }
  19926. mesh.setEnabled(parsedMesh.isEnabled);
  19927. mesh.isVisible = parsedMesh.isVisible;
  19928. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19929. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19930. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19931. if (parsedMesh.applyFog !== undefined) {
  19932. mesh.applyFog = parsedMesh.applyFog;
  19933. }
  19934. if (parsedMesh.pickable !== undefined) {
  19935. mesh.isPickable = parsedMesh.pickable;
  19936. }
  19937. if (parsedMesh.alphaIndex !== undefined) {
  19938. mesh.alphaIndex = parsedMesh.alphaIndex;
  19939. }
  19940. mesh.receiveShadows = parsedMesh.receiveShadows;
  19941. mesh.billboardMode = parsedMesh.billboardMode;
  19942. if (parsedMesh.visibility !== undefined) {
  19943. mesh.visibility = parsedMesh.visibility;
  19944. }
  19945. mesh.checkCollisions = parsedMesh.checkCollisions;
  19946. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19947. // freezeWorldMatrix
  19948. if (parsedMesh.freezeWorldMatrix) {
  19949. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19950. }
  19951. // Parent
  19952. if (parsedMesh.parentId) {
  19953. mesh._waitingParentId = parsedMesh.parentId;
  19954. }
  19955. // Actions
  19956. if (parsedMesh.actions !== undefined) {
  19957. mesh._waitingActions = parsedMesh.actions;
  19958. }
  19959. // Geometry
  19960. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19961. if (parsedMesh.delayLoadingFile) {
  19962. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19963. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19964. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19965. if (parsedMesh._binaryInfo) {
  19966. mesh._binaryInfo = parsedMesh._binaryInfo;
  19967. }
  19968. mesh._delayInfo = [];
  19969. if (parsedMesh.hasUVs) {
  19970. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19971. }
  19972. if (parsedMesh.hasUVs2) {
  19973. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19974. }
  19975. if (parsedMesh.hasUVs3) {
  19976. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19977. }
  19978. if (parsedMesh.hasUVs4) {
  19979. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19980. }
  19981. if (parsedMesh.hasUVs5) {
  19982. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19983. }
  19984. if (parsedMesh.hasUVs6) {
  19985. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19986. }
  19987. if (parsedMesh.hasColors) {
  19988. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19989. }
  19990. if (parsedMesh.hasMatricesIndices) {
  19991. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19992. }
  19993. if (parsedMesh.hasMatricesWeights) {
  19994. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19995. }
  19996. mesh._delayLoadingFunction = importGeometry;
  19997. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19998. mesh._checkDelayState();
  19999. }
  20000. }
  20001. else {
  20002. importGeometry(parsedMesh, mesh);
  20003. }
  20004. // Material
  20005. if (parsedMesh.materialId) {
  20006. mesh.setMaterialByID(parsedMesh.materialId);
  20007. }
  20008. else {
  20009. mesh.material = null;
  20010. }
  20011. // Skeleton
  20012. if (parsedMesh.skeletonId > -1) {
  20013. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20014. }
  20015. // Physics
  20016. if (parsedMesh.physicsImpostor) {
  20017. if (!scene.isPhysicsEnabled()) {
  20018. scene.enablePhysics();
  20019. }
  20020. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20021. }
  20022. // Animations
  20023. if (parsedMesh.animations) {
  20024. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20025. var parsedAnimation = parsedMesh.animations[animationIndex];
  20026. mesh.animations.push(parseAnimation(parsedAnimation));
  20027. }
  20028. }
  20029. if (parsedMesh.autoAnimate) {
  20030. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20031. }
  20032. // Layer Mask
  20033. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20034. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20035. }
  20036. else {
  20037. mesh.layerMask = 0x0FFFFFFF;
  20038. }
  20039. // Instances
  20040. if (parsedMesh.instances) {
  20041. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20042. var parsedInstance = parsedMesh.instances[index];
  20043. var instance = mesh.createInstance(parsedInstance.name);
  20044. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20045. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20046. if (parsedInstance.rotationQuaternion) {
  20047. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20048. }
  20049. else if (parsedInstance.rotation) {
  20050. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20051. }
  20052. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20053. instance.checkCollisions = mesh.checkCollisions;
  20054. if (parsedMesh.animations) {
  20055. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20056. parsedAnimation = parsedMesh.animations[animationIndex];
  20057. instance.animations.push(parseAnimation(parsedAnimation));
  20058. }
  20059. }
  20060. }
  20061. }
  20062. return mesh;
  20063. };
  20064. var parseActions = function (parsedActions, object, scene) {
  20065. var actionManager = new BABYLON.ActionManager(scene);
  20066. if (object === null)
  20067. scene.actionManager = actionManager;
  20068. else
  20069. object.actionManager = actionManager;
  20070. // instanciate a new object
  20071. var instanciate = function (name, params) {
  20072. var newInstance = Object.create(BABYLON[name].prototype);
  20073. newInstance.constructor.apply(newInstance, params);
  20074. return newInstance;
  20075. };
  20076. var parseParameter = function (name, value, target, propertyPath) {
  20077. if (propertyPath === null) {
  20078. // String, boolean or float
  20079. var floatValue = parseFloat(value);
  20080. if (value === "true" || value === "false")
  20081. return value === "true";
  20082. else
  20083. return isNaN(floatValue) ? value : floatValue;
  20084. }
  20085. var effectiveTarget = propertyPath.split(".");
  20086. var values = value.split(",");
  20087. // Get effective Target
  20088. for (var i = 0; i < effectiveTarget.length; i++) {
  20089. target = target[effectiveTarget[i]];
  20090. }
  20091. // Return appropriate value with its type
  20092. if (typeof (target) === "boolean")
  20093. return values[0] === "true";
  20094. if (typeof (target) === "string")
  20095. return values[0];
  20096. // Parameters with multiple values such as Vector3 etc.
  20097. var split = new Array();
  20098. for (var i = 0; i < values.length; i++)
  20099. split.push(parseFloat(values[i]));
  20100. if (target instanceof BABYLON.Vector3)
  20101. return BABYLON.Vector3.FromArray(split);
  20102. if (target instanceof BABYLON.Vector4)
  20103. return BABYLON.Vector4.FromArray(split);
  20104. if (target instanceof BABYLON.Color3)
  20105. return BABYLON.Color3.FromArray(split);
  20106. if (target instanceof BABYLON.Color4)
  20107. return BABYLON.Color4.FromArray(split);
  20108. return parseFloat(values[0]);
  20109. };
  20110. // traverse graph per trigger
  20111. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20112. if (combineArray === void 0) { combineArray = null; }
  20113. if (parsedAction.detached)
  20114. return;
  20115. var parameters = new Array();
  20116. var target = null;
  20117. var propertyPath = null;
  20118. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20119. // Parameters
  20120. if (parsedAction.type === 2)
  20121. parameters.push(actionManager);
  20122. else
  20123. parameters.push(trigger);
  20124. if (combine) {
  20125. var actions = new Array();
  20126. for (var j = 0; j < parsedAction.combine.length; j++) {
  20127. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20128. }
  20129. parameters.push(actions);
  20130. }
  20131. else {
  20132. for (var i = 0; i < parsedAction.properties.length; i++) {
  20133. var value = parsedAction.properties[i].value;
  20134. var name = parsedAction.properties[i].name;
  20135. var targetType = parsedAction.properties[i].targetType;
  20136. if (name === "target")
  20137. if (targetType !== null && targetType === "SceneProperties")
  20138. value = target = scene;
  20139. else
  20140. value = target = scene.getNodeByName(value);
  20141. else if (name === "parent")
  20142. value = scene.getNodeByName(value);
  20143. else if (name === "sound")
  20144. value = scene.getSoundByName(value);
  20145. else if (name !== "propertyPath") {
  20146. if (parsedAction.type === 2 && name === "operator")
  20147. value = BABYLON.ValueCondition[value];
  20148. else
  20149. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20150. }
  20151. else {
  20152. propertyPath = value;
  20153. }
  20154. parameters.push(value);
  20155. }
  20156. }
  20157. if (combineArray === null) {
  20158. parameters.push(condition);
  20159. }
  20160. else {
  20161. parameters.push(null);
  20162. }
  20163. // If interpolate value action
  20164. if (parsedAction.name === "InterpolateValueAction") {
  20165. var param = parameters[parameters.length - 2];
  20166. parameters[parameters.length - 1] = param;
  20167. parameters[parameters.length - 2] = condition;
  20168. }
  20169. // Action or condition(s) and not CombineAction
  20170. var newAction = instanciate(parsedAction.name, parameters);
  20171. if (newAction instanceof BABYLON.Condition && condition !== null) {
  20172. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  20173. if (action)
  20174. action.then(nothing);
  20175. else
  20176. actionManager.registerAction(nothing);
  20177. action = nothing;
  20178. }
  20179. if (combineArray === null) {
  20180. if (newAction instanceof BABYLON.Condition) {
  20181. condition = newAction;
  20182. newAction = action;
  20183. }
  20184. else {
  20185. condition = null;
  20186. if (action)
  20187. action.then(newAction);
  20188. else
  20189. actionManager.registerAction(newAction);
  20190. }
  20191. }
  20192. else {
  20193. combineArray.push(newAction);
  20194. }
  20195. for (var i = 0; i < parsedAction.children.length; i++)
  20196. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20197. };
  20198. // triggers
  20199. for (var i = 0; i < parsedActions.children.length; i++) {
  20200. var triggerParams;
  20201. var trigger = parsedActions.children[i];
  20202. if (trigger.properties.length > 0) {
  20203. var param = trigger.properties[0].value;
  20204. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20205. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20206. }
  20207. else
  20208. triggerParams = BABYLON.ActionManager[trigger.name];
  20209. for (var j = 0; j < trigger.children.length; j++) {
  20210. if (!trigger.detached)
  20211. traverse(trigger.children[j], triggerParams, null, null);
  20212. }
  20213. }
  20214. };
  20215. var parseSound = function (parsedSound, scene, rootUrl) {
  20216. var soundName = parsedSound.name;
  20217. var soundUrl = rootUrl + soundName;
  20218. var options = {
  20219. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20220. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20221. rolloffFactor: parsedSound.rolloffFactor,
  20222. refDistance: parsedSound.refDistance,
  20223. distanceModel: parsedSound.distanceModel,
  20224. playbackRate: parsedSound.playbackRate
  20225. };
  20226. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20227. scene._addPendingData(newSound);
  20228. if (parsedSound.position) {
  20229. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20230. newSound.setPosition(soundPosition);
  20231. }
  20232. if (parsedSound.isDirectional) {
  20233. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20234. if (parsedSound.localDirectionToMesh) {
  20235. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20236. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20237. }
  20238. }
  20239. if (parsedSound.connectedMeshId) {
  20240. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20241. if (connectedMesh) {
  20242. newSound.attachToMesh(connectedMesh);
  20243. }
  20244. }
  20245. };
  20246. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20247. names = (names instanceof Array) ? names : [names];
  20248. for (var i in names) {
  20249. if (mesh.name === names[i]) {
  20250. hierarchyIds.push(mesh.id);
  20251. return true;
  20252. }
  20253. }
  20254. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20255. hierarchyIds.push(mesh.id);
  20256. return true;
  20257. }
  20258. return false;
  20259. };
  20260. var importVertexData = function (parsedVertexData, geometry) {
  20261. var vertexData = new BABYLON.VertexData();
  20262. // positions
  20263. var positions = parsedVertexData.positions;
  20264. if (positions) {
  20265. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20266. }
  20267. // normals
  20268. var normals = parsedVertexData.normals;
  20269. if (normals) {
  20270. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20271. }
  20272. // uvs
  20273. var uvs = parsedVertexData.uvs;
  20274. if (uvs) {
  20275. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20276. }
  20277. // uv2s
  20278. var uv2s = parsedVertexData.uv2s;
  20279. if (uv2s) {
  20280. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20281. }
  20282. // uv3s
  20283. var uv3s = parsedVertexData.uv3s;
  20284. if (uv3s) {
  20285. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20286. }
  20287. // uv4s
  20288. var uv4s = parsedVertexData.uv4s;
  20289. if (uv4s) {
  20290. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20291. }
  20292. // uv5s
  20293. var uv5s = parsedVertexData.uv5s;
  20294. if (uv5s) {
  20295. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20296. }
  20297. // uv6s
  20298. var uv6s = parsedVertexData.uv6s;
  20299. if (uv6s) {
  20300. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20301. }
  20302. // colors
  20303. var colors = parsedVertexData.colors;
  20304. if (colors) {
  20305. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20306. }
  20307. // matricesIndices
  20308. var matricesIndices = parsedVertexData.matricesIndices;
  20309. if (matricesIndices) {
  20310. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20311. }
  20312. // matricesWeights
  20313. var matricesWeights = parsedVertexData.matricesWeights;
  20314. if (matricesWeights) {
  20315. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20316. }
  20317. // indices
  20318. var indices = parsedVertexData.indices;
  20319. if (indices) {
  20320. vertexData.indices = indices;
  20321. }
  20322. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20323. };
  20324. var importGeometry = function (parsedGeometry, mesh) {
  20325. var scene = mesh.getScene();
  20326. // Geometry
  20327. var geometryId = parsedGeometry.geometryId;
  20328. if (geometryId) {
  20329. var geometry = scene.getGeometryByID(geometryId);
  20330. if (geometry) {
  20331. geometry.applyToMesh(mesh);
  20332. }
  20333. }
  20334. else if (parsedGeometry instanceof ArrayBuffer) {
  20335. var binaryInfo = mesh._binaryInfo;
  20336. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20337. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20338. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20339. }
  20340. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20341. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20342. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20343. }
  20344. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20345. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20346. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20347. }
  20348. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20349. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20350. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20351. }
  20352. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20353. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20354. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20355. }
  20356. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20357. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20358. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20359. }
  20360. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20361. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20362. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20363. }
  20364. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20365. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20366. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20367. }
  20368. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20369. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20370. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20371. }
  20372. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20373. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20374. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20375. }
  20376. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20377. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20378. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20379. }
  20380. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20381. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20382. mesh.setIndices(indicesData);
  20383. }
  20384. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20385. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20386. mesh.subMeshes = [];
  20387. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20388. var materialIndex = subMeshesData[(i * 5) + 0];
  20389. var verticesStart = subMeshesData[(i * 5) + 1];
  20390. var verticesCount = subMeshesData[(i * 5) + 2];
  20391. var indexStart = subMeshesData[(i * 5) + 3];
  20392. var indexCount = subMeshesData[(i * 5) + 4];
  20393. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20394. }
  20395. }
  20396. }
  20397. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20398. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20399. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20400. if (parsedGeometry.uvs) {
  20401. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20402. }
  20403. if (parsedGeometry.uvs2) {
  20404. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20405. }
  20406. if (parsedGeometry.uvs3) {
  20407. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20408. }
  20409. if (parsedGeometry.uvs4) {
  20410. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20411. }
  20412. if (parsedGeometry.uvs5) {
  20413. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20414. }
  20415. if (parsedGeometry.uvs6) {
  20416. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20417. }
  20418. if (parsedGeometry.colors) {
  20419. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20420. }
  20421. if (parsedGeometry.matricesIndices) {
  20422. if (!parsedGeometry.matricesIndices._isExpanded) {
  20423. var floatIndices = [];
  20424. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20425. var matricesIndex = parsedGeometry.matricesIndices[i];
  20426. floatIndices.push(matricesIndex & 0x000000FF);
  20427. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20428. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20429. floatIndices.push(matricesIndex >> 24);
  20430. }
  20431. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20432. }
  20433. else {
  20434. delete parsedGeometry.matricesIndices._isExpanded;
  20435. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20436. }
  20437. }
  20438. if (parsedGeometry.matricesWeights) {
  20439. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20440. }
  20441. mesh.setIndices(parsedGeometry.indices);
  20442. }
  20443. // SubMeshes
  20444. if (parsedGeometry.subMeshes) {
  20445. mesh.subMeshes = [];
  20446. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20447. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20448. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20449. }
  20450. }
  20451. // Flat shading
  20452. if (mesh._shouldGenerateFlatShading) {
  20453. mesh.convertToFlatShadedMesh();
  20454. delete mesh._shouldGenerateFlatShading;
  20455. }
  20456. // Update
  20457. mesh.computeWorldMatrix(true);
  20458. // Octree
  20459. if (scene._selectionOctree) {
  20460. scene._selectionOctree.addMesh(mesh);
  20461. }
  20462. };
  20463. BABYLON.SceneLoader.RegisterPlugin({
  20464. extensions: ".babylon",
  20465. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20466. var parsedData = JSON.parse(data);
  20467. var loadedSkeletonsIds = [];
  20468. var loadedMaterialsIds = [];
  20469. var hierarchyIds = [];
  20470. for (var index = 0; index < parsedData.meshes.length; index++) {
  20471. var parsedMesh = parsedData.meshes[index];
  20472. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20473. if (meshesNames instanceof Array) {
  20474. // Remove found mesh name from list.
  20475. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20476. }
  20477. //Geometry?
  20478. if (parsedMesh.geometryId) {
  20479. //does the file contain geometries?
  20480. if (parsedData.geometries) {
  20481. //find the correct geometry and add it to the scene
  20482. var found = false;
  20483. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20484. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20485. return;
  20486. }
  20487. else {
  20488. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20489. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20490. switch (geometryType) {
  20491. case "boxes":
  20492. parseBox(parsedGeometryData, scene);
  20493. break;
  20494. case "spheres":
  20495. parseSphere(parsedGeometryData, scene);
  20496. break;
  20497. case "cylinders":
  20498. parseCylinder(parsedGeometryData, scene);
  20499. break;
  20500. case "toruses":
  20501. parseTorus(parsedGeometryData, scene);
  20502. break;
  20503. case "grounds":
  20504. parseGround(parsedGeometryData, scene);
  20505. break;
  20506. case "planes":
  20507. parsePlane(parsedGeometryData, scene);
  20508. break;
  20509. case "torusKnots":
  20510. parseTorusKnot(parsedGeometryData, scene);
  20511. break;
  20512. case "vertexData":
  20513. parseVertexData(parsedGeometryData, scene, rootUrl);
  20514. break;
  20515. }
  20516. found = true;
  20517. }
  20518. });
  20519. }
  20520. });
  20521. if (!found) {
  20522. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20523. }
  20524. }
  20525. }
  20526. // Material ?
  20527. if (parsedMesh.materialId) {
  20528. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20529. if (!materialFound && parsedData.multiMaterials) {
  20530. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20531. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20532. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20533. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20534. var subMatId = parsedMultiMaterial.materials[matIndex];
  20535. loadedMaterialsIds.push(subMatId);
  20536. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20537. }
  20538. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20539. parseMultiMaterial(parsedMultiMaterial, scene);
  20540. materialFound = true;
  20541. break;
  20542. }
  20543. }
  20544. }
  20545. if (!materialFound) {
  20546. loadedMaterialsIds.push(parsedMesh.materialId);
  20547. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20548. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20549. }
  20550. }
  20551. }
  20552. // Skeleton ?
  20553. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20554. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20555. if (!skeletonAlreadyLoaded) {
  20556. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20557. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20558. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20559. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20560. loadedSkeletonsIds.push(parsedSkeleton.id);
  20561. }
  20562. }
  20563. }
  20564. }
  20565. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20566. meshes.push(mesh);
  20567. }
  20568. }
  20569. // Connecting parents
  20570. for (index = 0; index < scene.meshes.length; index++) {
  20571. var currentMesh = scene.meshes[index];
  20572. if (currentMesh._waitingParentId) {
  20573. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20574. currentMesh._waitingParentId = undefined;
  20575. }
  20576. }
  20577. // freeze world matrix application
  20578. for (index = 0; index < scene.meshes.length; index++) {
  20579. var currentMesh = scene.meshes[index];
  20580. if (currentMesh._waitingFreezeWorldMatrix) {
  20581. currentMesh.freezeWorldMatrix();
  20582. currentMesh._waitingFreezeWorldMatrix = undefined;
  20583. }
  20584. }
  20585. // Particles
  20586. if (parsedData.particleSystems) {
  20587. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20588. var parsedParticleSystem = parsedData.particleSystems[index];
  20589. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20590. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20591. }
  20592. }
  20593. }
  20594. return true;
  20595. },
  20596. load: function (scene, data, rootUrl) {
  20597. var parsedData = JSON.parse(data);
  20598. // Scene
  20599. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20600. scene.autoClear = parsedData.autoClear;
  20601. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20602. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20603. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20604. // Fog
  20605. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20606. scene.fogMode = parsedData.fogMode;
  20607. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20608. scene.fogStart = parsedData.fogStart;
  20609. scene.fogEnd = parsedData.fogEnd;
  20610. scene.fogDensity = parsedData.fogDensity;
  20611. }
  20612. // Lights
  20613. for (var index = 0; index < parsedData.lights.length; index++) {
  20614. var parsedLight = parsedData.lights[index];
  20615. parseLight(parsedLight, scene);
  20616. }
  20617. // Materials
  20618. if (parsedData.materials) {
  20619. for (index = 0; index < parsedData.materials.length; index++) {
  20620. var parsedMaterial = parsedData.materials[index];
  20621. parseMaterial(parsedMaterial, scene, rootUrl);
  20622. }
  20623. }
  20624. if (parsedData.multiMaterials) {
  20625. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20626. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20627. parseMultiMaterial(parsedMultiMaterial, scene);
  20628. }
  20629. }
  20630. // Skeletons
  20631. if (parsedData.skeletons) {
  20632. for (index = 0; index < parsedData.skeletons.length; index++) {
  20633. var parsedSkeleton = parsedData.skeletons[index];
  20634. parseSkeleton(parsedSkeleton, scene);
  20635. }
  20636. }
  20637. // Geometries
  20638. var geometries = parsedData.geometries;
  20639. if (geometries) {
  20640. // Boxes
  20641. var boxes = geometries.boxes;
  20642. if (boxes) {
  20643. for (index = 0; index < boxes.length; index++) {
  20644. var parsedBox = boxes[index];
  20645. parseBox(parsedBox, scene);
  20646. }
  20647. }
  20648. // Spheres
  20649. var spheres = geometries.spheres;
  20650. if (spheres) {
  20651. for (index = 0; index < spheres.length; index++) {
  20652. var parsedSphere = spheres[index];
  20653. parseSphere(parsedSphere, scene);
  20654. }
  20655. }
  20656. // Cylinders
  20657. var cylinders = geometries.cylinders;
  20658. if (cylinders) {
  20659. for (index = 0; index < cylinders.length; index++) {
  20660. var parsedCylinder = cylinders[index];
  20661. parseCylinder(parsedCylinder, scene);
  20662. }
  20663. }
  20664. // Toruses
  20665. var toruses = geometries.toruses;
  20666. if (toruses) {
  20667. for (index = 0; index < toruses.length; index++) {
  20668. var parsedTorus = toruses[index];
  20669. parseTorus(parsedTorus, scene);
  20670. }
  20671. }
  20672. // Grounds
  20673. var grounds = geometries.grounds;
  20674. if (grounds) {
  20675. for (index = 0; index < grounds.length; index++) {
  20676. var parsedGround = grounds[index];
  20677. parseGround(parsedGround, scene);
  20678. }
  20679. }
  20680. // Planes
  20681. var planes = geometries.planes;
  20682. if (planes) {
  20683. for (index = 0; index < planes.length; index++) {
  20684. var parsedPlane = planes[index];
  20685. parsePlane(parsedPlane, scene);
  20686. }
  20687. }
  20688. // TorusKnots
  20689. var torusKnots = geometries.torusKnots;
  20690. if (torusKnots) {
  20691. for (index = 0; index < torusKnots.length; index++) {
  20692. var parsedTorusKnot = torusKnots[index];
  20693. parseTorusKnot(parsedTorusKnot, scene);
  20694. }
  20695. }
  20696. // VertexData
  20697. var vertexData = geometries.vertexData;
  20698. if (vertexData) {
  20699. for (index = 0; index < vertexData.length; index++) {
  20700. var parsedVertexData = vertexData[index];
  20701. parseVertexData(parsedVertexData, scene, rootUrl);
  20702. }
  20703. }
  20704. }
  20705. // Meshes
  20706. for (index = 0; index < parsedData.meshes.length; index++) {
  20707. var parsedMesh = parsedData.meshes[index];
  20708. parseMesh(parsedMesh, scene, rootUrl);
  20709. }
  20710. // Cameras
  20711. for (index = 0; index < parsedData.cameras.length; index++) {
  20712. var parsedCamera = parsedData.cameras[index];
  20713. parseCamera(parsedCamera, scene);
  20714. }
  20715. if (parsedData.activeCameraID) {
  20716. scene.setActiveCameraByID(parsedData.activeCameraID);
  20717. }
  20718. // Browsing all the graph to connect the dots
  20719. for (index = 0; index < scene.cameras.length; index++) {
  20720. var camera = scene.cameras[index];
  20721. if (camera._waitingParentId) {
  20722. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20723. camera._waitingParentId = undefined;
  20724. }
  20725. }
  20726. for (index = 0; index < scene.lights.length; index++) {
  20727. var light = scene.lights[index];
  20728. if (light._waitingParentId) {
  20729. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20730. light._waitingParentId = undefined;
  20731. }
  20732. }
  20733. // Sounds
  20734. if (parsedData.sounds) {
  20735. for (index = 0; index < parsedData.sounds.length; index++) {
  20736. var parsedSound = parsedData.sounds[index];
  20737. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20738. parseSound(parsedSound, scene, rootUrl);
  20739. }
  20740. else {
  20741. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20742. }
  20743. }
  20744. }
  20745. // Connect parents & children and parse actions
  20746. for (index = 0; index < scene.meshes.length; index++) {
  20747. var mesh = scene.meshes[index];
  20748. if (mesh._waitingParentId) {
  20749. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20750. mesh._waitingParentId = undefined;
  20751. }
  20752. if (mesh._waitingActions) {
  20753. parseActions(mesh._waitingActions, mesh, scene);
  20754. mesh._waitingActions = undefined;
  20755. }
  20756. }
  20757. // freeze world matrix application
  20758. for (index = 0; index < scene.meshes.length; index++) {
  20759. var currentMesh = scene.meshes[index];
  20760. if (currentMesh._waitingFreezeWorldMatrix) {
  20761. currentMesh.freezeWorldMatrix();
  20762. currentMesh._waitingFreezeWorldMatrix = undefined;
  20763. }
  20764. }
  20765. // Particles Systems
  20766. if (parsedData.particleSystems) {
  20767. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20768. var parsedParticleSystem = parsedData.particleSystems[index];
  20769. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20770. }
  20771. }
  20772. // Lens flares
  20773. if (parsedData.lensFlareSystems) {
  20774. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20775. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20776. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20777. }
  20778. }
  20779. // Shadows
  20780. if (parsedData.shadowGenerators) {
  20781. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20782. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20783. parseShadowGenerator(parsedShadowGenerator, scene);
  20784. }
  20785. }
  20786. // Actions (scene)
  20787. if (parsedData.actions) {
  20788. parseActions(parsedData.actions, null, scene);
  20789. }
  20790. // Finish
  20791. return true;
  20792. }
  20793. });
  20794. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20795. })(BABYLON || (BABYLON = {}));
  20796. var BABYLON;
  20797. (function (BABYLON) {
  20798. var SpriteManager = (function () {
  20799. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20801. this.name = name;
  20802. this.cellSize = cellSize;
  20803. this.sprites = new Array();
  20804. this.renderingGroupId = 0;
  20805. this.layerMask = 0x0FFFFFFF;
  20806. this.fogEnabled = true;
  20807. this.isPickable = false;
  20808. this._vertexDeclaration = [4, 4, 4, 4];
  20809. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20810. this._capacity = capacity;
  20811. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20812. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20813. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20814. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20815. this._scene = scene;
  20816. this._scene.spriteManagers.push(this);
  20817. // VBO
  20818. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20819. var indices = [];
  20820. var index = 0;
  20821. for (var count = 0; count < capacity; count++) {
  20822. indices.push(index);
  20823. indices.push(index + 1);
  20824. indices.push(index + 2);
  20825. indices.push(index);
  20826. indices.push(index + 2);
  20827. indices.push(index + 3);
  20828. index += 4;
  20829. }
  20830. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20831. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20832. // Effects
  20833. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20834. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20835. }
  20836. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20837. var arrayOffset = index * 16;
  20838. if (offsetX === 0)
  20839. offsetX = this._epsilon;
  20840. else if (offsetX === 1)
  20841. offsetX = 1 - this._epsilon;
  20842. if (offsetY === 0)
  20843. offsetY = this._epsilon;
  20844. else if (offsetY === 1)
  20845. offsetY = 1 - this._epsilon;
  20846. this._vertices[arrayOffset] = sprite.position.x;
  20847. this._vertices[arrayOffset + 1] = sprite.position.y;
  20848. this._vertices[arrayOffset + 2] = sprite.position.z;
  20849. this._vertices[arrayOffset + 3] = sprite.angle;
  20850. this._vertices[arrayOffset + 4] = sprite.width;
  20851. this._vertices[arrayOffset + 5] = sprite.height;
  20852. this._vertices[arrayOffset + 6] = offsetX;
  20853. this._vertices[arrayOffset + 7] = offsetY;
  20854. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20855. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20856. var offset = (sprite.cellIndex / rowSize) >> 0;
  20857. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20858. this._vertices[arrayOffset + 11] = offset;
  20859. // Color
  20860. this._vertices[arrayOffset + 12] = sprite.color.r;
  20861. this._vertices[arrayOffset + 13] = sprite.color.g;
  20862. this._vertices[arrayOffset + 14] = sprite.color.b;
  20863. this._vertices[arrayOffset + 15] = sprite.color.a;
  20864. };
  20865. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20866. var count = Math.min(this._capacity, this.sprites.length);
  20867. var min = BABYLON.Vector3.Zero();
  20868. var max = BABYLON.Vector3.Zero();
  20869. var distance = Number.MAX_VALUE;
  20870. var currentSprite;
  20871. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20872. var cameraView = camera.getViewMatrix();
  20873. for (var index = 0; index < count; index++) {
  20874. var sprite = this.sprites[index];
  20875. if (!sprite) {
  20876. continue;
  20877. }
  20878. if (predicate) {
  20879. if (!predicate(sprite)) {
  20880. continue;
  20881. }
  20882. }
  20883. else if (!sprite.isPickable) {
  20884. continue;
  20885. }
  20886. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20887. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20888. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20889. if (ray.intersectsBoxMinMax(min, max)) {
  20890. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20891. if (distance > currentDistance) {
  20892. distance = currentDistance;
  20893. currentSprite = sprite;
  20894. if (fastCheck) {
  20895. break;
  20896. }
  20897. }
  20898. }
  20899. }
  20900. if (currentSprite) {
  20901. var result = new BABYLON.PickingInfo();
  20902. result.hit = true;
  20903. result.pickedSprite = currentSprite;
  20904. result.distance = distance;
  20905. return result;
  20906. }
  20907. return null;
  20908. };
  20909. SpriteManager.prototype.render = function () {
  20910. // Check
  20911. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20912. return;
  20913. var engine = this._scene.getEngine();
  20914. var baseSize = this._spriteTexture.getBaseSize();
  20915. // Sprites
  20916. var deltaTime = engine.getDeltaTime();
  20917. var max = Math.min(this._capacity, this.sprites.length);
  20918. var rowSize = baseSize.width / this.cellSize;
  20919. var offset = 0;
  20920. for (var index = 0; index < max; index++) {
  20921. var sprite = this.sprites[index];
  20922. if (!sprite) {
  20923. continue;
  20924. }
  20925. sprite._animate(deltaTime);
  20926. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20927. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20928. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20929. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20930. }
  20931. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20932. // Render
  20933. var effect = this._effectBase;
  20934. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20935. effect = this._effectFog;
  20936. }
  20937. engine.enableEffect(effect);
  20938. var viewMatrix = this._scene.getViewMatrix();
  20939. effect.setTexture("diffuseSampler", this._spriteTexture);
  20940. effect.setMatrix("view", viewMatrix);
  20941. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20942. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20943. // Fog
  20944. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20945. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20946. effect.setColor3("vFogColor", this._scene.fogColor);
  20947. }
  20948. // VBOs
  20949. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20950. // Draw order
  20951. engine.setDepthFunctionToLessOrEqual();
  20952. effect.setBool("alphaTest", true);
  20953. engine.setColorWrite(false);
  20954. engine.draw(true, 0, max * 6);
  20955. engine.setColorWrite(true);
  20956. effect.setBool("alphaTest", false);
  20957. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20958. engine.draw(true, 0, max * 6);
  20959. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20960. };
  20961. SpriteManager.prototype.dispose = function () {
  20962. if (this._vertexBuffer) {
  20963. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20964. this._vertexBuffer = null;
  20965. }
  20966. if (this._indexBuffer) {
  20967. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20968. this._indexBuffer = null;
  20969. }
  20970. if (this._spriteTexture) {
  20971. this._spriteTexture.dispose();
  20972. this._spriteTexture = null;
  20973. }
  20974. // Remove from scene
  20975. var index = this._scene.spriteManagers.indexOf(this);
  20976. this._scene.spriteManagers.splice(index, 1);
  20977. // Callback
  20978. if (this.onDispose) {
  20979. this.onDispose();
  20980. }
  20981. };
  20982. return SpriteManager;
  20983. })();
  20984. BABYLON.SpriteManager = SpriteManager;
  20985. })(BABYLON || (BABYLON = {}));
  20986. var BABYLON;
  20987. (function (BABYLON) {
  20988. var Sprite = (function () {
  20989. function Sprite(name, manager) {
  20990. this.name = name;
  20991. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20992. this.width = 1.0;
  20993. this.height = 1.0;
  20994. this.angle = 0;
  20995. this.cellIndex = 0;
  20996. this.invertU = 0;
  20997. this.invertV = 0;
  20998. this.animations = new Array();
  20999. this.isPickable = false;
  21000. this._animationStarted = false;
  21001. this._loopAnimation = false;
  21002. this._fromIndex = 0;
  21003. this._toIndex = 0;
  21004. this._delay = 0;
  21005. this._direction = 1;
  21006. this._frameCount = 0;
  21007. this._time = 0;
  21008. this._manager = manager;
  21009. this._manager.sprites.push(this);
  21010. this.position = BABYLON.Vector3.Zero();
  21011. }
  21012. Object.defineProperty(Sprite.prototype, "size", {
  21013. get: function () {
  21014. return this.width;
  21015. },
  21016. set: function (value) {
  21017. this.width = value;
  21018. this.height = value;
  21019. },
  21020. enumerable: true,
  21021. configurable: true
  21022. });
  21023. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21024. this._fromIndex = from;
  21025. this._toIndex = to;
  21026. this._loopAnimation = loop;
  21027. this._delay = delay;
  21028. this._animationStarted = true;
  21029. this._direction = from < to ? 1 : -1;
  21030. this.cellIndex = from;
  21031. this._time = 0;
  21032. };
  21033. Sprite.prototype.stopAnimation = function () {
  21034. this._animationStarted = false;
  21035. };
  21036. Sprite.prototype._animate = function (deltaTime) {
  21037. if (!this._animationStarted)
  21038. return;
  21039. this._time += deltaTime;
  21040. if (this._time > this._delay) {
  21041. this._time = this._time % this._delay;
  21042. this.cellIndex += this._direction;
  21043. if (this.cellIndex == this._toIndex) {
  21044. if (this._loopAnimation) {
  21045. this.cellIndex = this._fromIndex;
  21046. }
  21047. else {
  21048. this._animationStarted = false;
  21049. if (this.disposeWhenFinishedAnimating) {
  21050. this.dispose();
  21051. }
  21052. }
  21053. }
  21054. }
  21055. };
  21056. Sprite.prototype.dispose = function () {
  21057. for (var i = 0; i < this._manager.sprites.length; i++) {
  21058. if (this._manager.sprites[i] == this) {
  21059. this._manager.sprites.splice(i, 1);
  21060. }
  21061. }
  21062. };
  21063. return Sprite;
  21064. })();
  21065. BABYLON.Sprite = Sprite;
  21066. })(BABYLON || (BABYLON = {}));
  21067. var BABYLON;
  21068. (function (BABYLON) {
  21069. var Layer = (function () {
  21070. function Layer(name, imgUrl, scene, isBackground, color) {
  21071. this.name = name;
  21072. this._vertexDeclaration = [2];
  21073. this._vertexStrideSize = 2 * 4;
  21074. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21075. this.isBackground = isBackground === undefined ? true : isBackground;
  21076. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21077. this._scene = scene;
  21078. this._scene.layers.push(this);
  21079. // VBO
  21080. var vertices = [];
  21081. vertices.push(1, 1);
  21082. vertices.push(-1, 1);
  21083. vertices.push(-1, -1);
  21084. vertices.push(1, -1);
  21085. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21086. // Indices
  21087. var indices = [];
  21088. indices.push(0);
  21089. indices.push(1);
  21090. indices.push(2);
  21091. indices.push(0);
  21092. indices.push(2);
  21093. indices.push(3);
  21094. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21095. // Effects
  21096. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21097. }
  21098. Layer.prototype.render = function () {
  21099. // Check
  21100. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21101. return;
  21102. var engine = this._scene.getEngine();
  21103. // Render
  21104. engine.enableEffect(this._effect);
  21105. engine.setState(false);
  21106. // Texture
  21107. this._effect.setTexture("textureSampler", this.texture);
  21108. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21109. // Color
  21110. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21111. // VBOs
  21112. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21113. // Draw order
  21114. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21115. engine.draw(true, 0, 6);
  21116. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21117. };
  21118. Layer.prototype.dispose = function () {
  21119. if (this._vertexBuffer) {
  21120. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21121. this._vertexBuffer = null;
  21122. }
  21123. if (this._indexBuffer) {
  21124. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21125. this._indexBuffer = null;
  21126. }
  21127. if (this.texture) {
  21128. this.texture.dispose();
  21129. this.texture = null;
  21130. }
  21131. // Remove from scene
  21132. var index = this._scene.layers.indexOf(this);
  21133. this._scene.layers.splice(index, 1);
  21134. // Callback
  21135. if (this.onDispose) {
  21136. this.onDispose();
  21137. }
  21138. };
  21139. return Layer;
  21140. })();
  21141. BABYLON.Layer = Layer;
  21142. })(BABYLON || (BABYLON = {}));
  21143. var BABYLON;
  21144. (function (BABYLON) {
  21145. var Particle = (function () {
  21146. function Particle() {
  21147. this.position = BABYLON.Vector3.Zero();
  21148. this.direction = BABYLON.Vector3.Zero();
  21149. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21150. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21151. this.lifeTime = 1.0;
  21152. this.age = 0;
  21153. this.size = 0;
  21154. this.angle = 0;
  21155. this.angularSpeed = 0;
  21156. }
  21157. Particle.prototype.copyTo = function (other) {
  21158. other.position.copyFrom(this.position);
  21159. other.direction.copyFrom(this.direction);
  21160. other.color.copyFrom(this.color);
  21161. other.colorStep.copyFrom(this.colorStep);
  21162. other.lifeTime = this.lifeTime;
  21163. other.age = this.age;
  21164. other.size = this.size;
  21165. other.angle = this.angle;
  21166. other.angularSpeed = this.angularSpeed;
  21167. };
  21168. return Particle;
  21169. })();
  21170. BABYLON.Particle = Particle;
  21171. })(BABYLON || (BABYLON = {}));
  21172. var BABYLON;
  21173. (function (BABYLON) {
  21174. var randomNumber = function (min, max) {
  21175. if (min === max) {
  21176. return (min);
  21177. }
  21178. var random = Math.random();
  21179. return ((random * (max - min)) + min);
  21180. };
  21181. var ParticleSystem = (function () {
  21182. function ParticleSystem(name, capacity, scene, customEffect) {
  21183. var _this = this;
  21184. this.name = name;
  21185. this.renderingGroupId = 0;
  21186. this.emitter = null;
  21187. this.emitRate = 10;
  21188. this.manualEmitCount = -1;
  21189. this.updateSpeed = 0.01;
  21190. this.targetStopDuration = 0;
  21191. this.disposeOnStop = false;
  21192. this.minEmitPower = 1;
  21193. this.maxEmitPower = 1;
  21194. this.minLifeTime = 1;
  21195. this.maxLifeTime = 1;
  21196. this.minSize = 1;
  21197. this.maxSize = 1;
  21198. this.minAngularSpeed = 0;
  21199. this.maxAngularSpeed = 0;
  21200. this.layerMask = 0x0FFFFFFF;
  21201. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21202. this.forceDepthWrite = false;
  21203. this.gravity = BABYLON.Vector3.Zero();
  21204. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21205. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21206. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21207. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21208. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21209. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21210. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21211. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21212. this.particles = new Array();
  21213. this._vertexDeclaration = [3, 4, 4];
  21214. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21215. this._stockParticles = new Array();
  21216. this._newPartsExcess = 0;
  21217. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21218. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21219. this._scaledDirection = BABYLON.Vector3.Zero();
  21220. this._scaledGravity = BABYLON.Vector3.Zero();
  21221. this._currentRenderId = -1;
  21222. this._started = false;
  21223. this._stopped = false;
  21224. this._actualFrame = 0;
  21225. this.id = name;
  21226. this._capacity = capacity;
  21227. this._scene = scene;
  21228. this._customEffect = customEffect;
  21229. scene.particleSystems.push(this);
  21230. // VBO
  21231. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21232. var indices = [];
  21233. var index = 0;
  21234. for (var count = 0; count < capacity; count++) {
  21235. indices.push(index);
  21236. indices.push(index + 1);
  21237. indices.push(index + 2);
  21238. indices.push(index);
  21239. indices.push(index + 2);
  21240. indices.push(index + 3);
  21241. index += 4;
  21242. }
  21243. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21244. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21245. // Default behaviors
  21246. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21247. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21248. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21249. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21250. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21251. };
  21252. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21253. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21254. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21255. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21256. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21257. };
  21258. this.updateFunction = function (particles) {
  21259. for (var index = 0; index < particles.length; index++) {
  21260. var particle = particles[index];
  21261. particle.age += _this._scaledUpdateSpeed;
  21262. if (particle.age >= particle.lifeTime) {
  21263. _this.recycleParticle(particle);
  21264. index--;
  21265. continue;
  21266. }
  21267. else {
  21268. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21269. particle.color.addInPlace(_this._scaledColorStep);
  21270. if (particle.color.a < 0)
  21271. particle.color.a = 0;
  21272. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21273. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21274. particle.position.addInPlace(_this._scaledDirection);
  21275. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21276. particle.direction.addInPlace(_this._scaledGravity);
  21277. }
  21278. }
  21279. };
  21280. }
  21281. ParticleSystem.prototype.recycleParticle = function (particle) {
  21282. var lastParticle = this.particles.pop();
  21283. if (lastParticle !== particle) {
  21284. lastParticle.copyTo(particle);
  21285. this._stockParticles.push(lastParticle);
  21286. }
  21287. };
  21288. ParticleSystem.prototype.getCapacity = function () {
  21289. return this._capacity;
  21290. };
  21291. ParticleSystem.prototype.isAlive = function () {
  21292. return this._alive;
  21293. };
  21294. ParticleSystem.prototype.isStarted = function () {
  21295. return this._started;
  21296. };
  21297. ParticleSystem.prototype.start = function () {
  21298. this._started = true;
  21299. this._stopped = false;
  21300. this._actualFrame = 0;
  21301. };
  21302. ParticleSystem.prototype.stop = function () {
  21303. this._stopped = true;
  21304. };
  21305. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21306. var offset = index * 11;
  21307. this._vertices[offset] = particle.position.x;
  21308. this._vertices[offset + 1] = particle.position.y;
  21309. this._vertices[offset + 2] = particle.position.z;
  21310. this._vertices[offset + 3] = particle.color.r;
  21311. this._vertices[offset + 4] = particle.color.g;
  21312. this._vertices[offset + 5] = particle.color.b;
  21313. this._vertices[offset + 6] = particle.color.a;
  21314. this._vertices[offset + 7] = particle.angle;
  21315. this._vertices[offset + 8] = particle.size;
  21316. this._vertices[offset + 9] = offsetX;
  21317. this._vertices[offset + 10] = offsetY;
  21318. };
  21319. ParticleSystem.prototype._update = function (newParticles) {
  21320. // Update current
  21321. this._alive = this.particles.length > 0;
  21322. this.updateFunction(this.particles);
  21323. // Add new ones
  21324. var worldMatrix;
  21325. if (this.emitter.position) {
  21326. worldMatrix = this.emitter.getWorldMatrix();
  21327. }
  21328. else {
  21329. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21330. }
  21331. for (var index = 0; index < newParticles; index++) {
  21332. if (this.particles.length === this._capacity) {
  21333. break;
  21334. }
  21335. if (this._stockParticles.length !== 0) {
  21336. var particle = this._stockParticles.pop();
  21337. particle.age = 0;
  21338. }
  21339. else {
  21340. particle = new BABYLON.Particle();
  21341. }
  21342. this.particles.push(particle);
  21343. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21344. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21345. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21346. particle.size = randomNumber(this.minSize, this.maxSize);
  21347. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21348. this.startPositionFunction(worldMatrix, particle.position);
  21349. var step = randomNumber(0, 1.0);
  21350. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21351. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21352. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21353. }
  21354. };
  21355. ParticleSystem.prototype._getEffect = function () {
  21356. if (this._customEffect) {
  21357. return this._customEffect;
  21358. }
  21359. ;
  21360. var defines = [];
  21361. if (this._scene.clipPlane) {
  21362. defines.push("#define CLIPPLANE");
  21363. }
  21364. // Effect
  21365. var join = defines.join("\n");
  21366. if (this._cachedDefines !== join) {
  21367. this._cachedDefines = join;
  21368. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21369. }
  21370. return this._effect;
  21371. };
  21372. ParticleSystem.prototype.animate = function () {
  21373. if (!this._started)
  21374. return;
  21375. var effect = this._getEffect();
  21376. // Check
  21377. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21378. return;
  21379. if (this._currentRenderId === this._scene.getRenderId()) {
  21380. return;
  21381. }
  21382. this._currentRenderId = this._scene.getRenderId();
  21383. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21384. // determine the number of particles we need to create
  21385. var emitCout;
  21386. if (this.manualEmitCount > -1) {
  21387. emitCout = this.manualEmitCount;
  21388. this.manualEmitCount = 0;
  21389. }
  21390. else {
  21391. emitCout = this.emitRate;
  21392. }
  21393. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21394. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21395. if (this._newPartsExcess > 1.0) {
  21396. newParticles += this._newPartsExcess >> 0;
  21397. this._newPartsExcess -= this._newPartsExcess >> 0;
  21398. }
  21399. this._alive = false;
  21400. if (!this._stopped) {
  21401. this._actualFrame += this._scaledUpdateSpeed;
  21402. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21403. this.stop();
  21404. }
  21405. else {
  21406. newParticles = 0;
  21407. }
  21408. this._update(newParticles);
  21409. // Stopped?
  21410. if (this._stopped) {
  21411. if (!this._alive) {
  21412. this._started = false;
  21413. if (this.disposeOnStop) {
  21414. this._scene._toBeDisposed.push(this);
  21415. }
  21416. }
  21417. }
  21418. // Update VBO
  21419. var offset = 0;
  21420. for (var index = 0; index < this.particles.length; index++) {
  21421. var particle = this.particles[index];
  21422. this._appendParticleVertex(offset++, particle, 0, 0);
  21423. this._appendParticleVertex(offset++, particle, 1, 0);
  21424. this._appendParticleVertex(offset++, particle, 1, 1);
  21425. this._appendParticleVertex(offset++, particle, 0, 1);
  21426. }
  21427. var engine = this._scene.getEngine();
  21428. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21429. };
  21430. ParticleSystem.prototype.render = function () {
  21431. var effect = this._getEffect();
  21432. // Check
  21433. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21434. return 0;
  21435. var engine = this._scene.getEngine();
  21436. // Render
  21437. engine.enableEffect(effect);
  21438. engine.setState(false);
  21439. var viewMatrix = this._scene.getViewMatrix();
  21440. effect.setTexture("diffuseSampler", this.particleTexture);
  21441. effect.setMatrix("view", viewMatrix);
  21442. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21443. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21444. if (this._scene.clipPlane) {
  21445. var clipPlane = this._scene.clipPlane;
  21446. var invView = viewMatrix.clone();
  21447. invView.invert();
  21448. effect.setMatrix("invView", invView);
  21449. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21450. }
  21451. // VBOs
  21452. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21453. // Draw order
  21454. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21455. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21456. }
  21457. else {
  21458. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21459. }
  21460. if (this.forceDepthWrite) {
  21461. engine.setDepthWrite(true);
  21462. }
  21463. engine.draw(true, 0, this.particles.length * 6);
  21464. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21465. return this.particles.length;
  21466. };
  21467. ParticleSystem.prototype.dispose = function () {
  21468. if (this._vertexBuffer) {
  21469. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21470. this._vertexBuffer = null;
  21471. }
  21472. if (this._indexBuffer) {
  21473. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21474. this._indexBuffer = null;
  21475. }
  21476. if (this.particleTexture) {
  21477. this.particleTexture.dispose();
  21478. this.particleTexture = null;
  21479. }
  21480. // Remove from scene
  21481. var index = this._scene.particleSystems.indexOf(this);
  21482. this._scene.particleSystems.splice(index, 1);
  21483. // Callback
  21484. if (this.onDispose) {
  21485. this.onDispose();
  21486. }
  21487. };
  21488. // Clone
  21489. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21490. var result = new ParticleSystem(name, this._capacity, this._scene);
  21491. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21492. if (newEmitter === undefined) {
  21493. newEmitter = this.emitter;
  21494. }
  21495. result.emitter = newEmitter;
  21496. if (this.particleTexture) {
  21497. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21498. }
  21499. result.start();
  21500. return result;
  21501. };
  21502. // Statics
  21503. ParticleSystem.BLENDMODE_ONEONE = 0;
  21504. ParticleSystem.BLENDMODE_STANDARD = 1;
  21505. return ParticleSystem;
  21506. })();
  21507. BABYLON.ParticleSystem = ParticleSystem;
  21508. })(BABYLON || (BABYLON = {}));
  21509. var BABYLON;
  21510. (function (BABYLON) {
  21511. var Animation = (function () {
  21512. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21513. this.name = name;
  21514. this.targetProperty = targetProperty;
  21515. this.framePerSecond = framePerSecond;
  21516. this.dataType = dataType;
  21517. this.loopMode = loopMode;
  21518. this._offsetsCache = {};
  21519. this._highLimitsCache = {};
  21520. this._stopped = false;
  21521. this.allowMatricesInterpolation = false;
  21522. this.targetPropertyPath = targetProperty.split(".");
  21523. this.dataType = dataType;
  21524. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21525. }
  21526. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21527. var dataType = undefined;
  21528. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21529. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21530. }
  21531. else if (from instanceof BABYLON.Quaternion) {
  21532. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21533. }
  21534. else if (from instanceof BABYLON.Vector3) {
  21535. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21536. }
  21537. else if (from instanceof BABYLON.Vector2) {
  21538. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21539. }
  21540. else if (from instanceof BABYLON.Color3) {
  21541. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21542. }
  21543. if (dataType == undefined) {
  21544. return null;
  21545. }
  21546. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21547. var keys = [];
  21548. keys.push({ frame: 0, value: from });
  21549. keys.push({ frame: totalFrame, value: to });
  21550. animation.setKeys(keys);
  21551. if (easingFunction !== undefined) {
  21552. animation.setEasingFunction(easingFunction);
  21553. }
  21554. mesh.animations.push(animation);
  21555. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21556. };
  21557. // Methods
  21558. Animation.prototype.reset = function () {
  21559. this._offsetsCache = {};
  21560. this._highLimitsCache = {};
  21561. this.currentFrame = 0;
  21562. };
  21563. Animation.prototype.isStopped = function () {
  21564. return this._stopped;
  21565. };
  21566. Animation.prototype.getKeys = function () {
  21567. return this._keys;
  21568. };
  21569. Animation.prototype.getEasingFunction = function () {
  21570. return this._easingFunction;
  21571. };
  21572. Animation.prototype.setEasingFunction = function (easingFunction) {
  21573. this._easingFunction = easingFunction;
  21574. };
  21575. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21576. return startValue + (endValue - startValue) * gradient;
  21577. };
  21578. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21579. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21580. };
  21581. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21582. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21583. };
  21584. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21585. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21586. };
  21587. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21588. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21589. };
  21590. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21591. var startScale = new BABYLON.Vector3(0, 0, 0);
  21592. var startRotation = new BABYLON.Quaternion();
  21593. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21594. startValue.decompose(startScale, startRotation, startTranslation);
  21595. var endScale = new BABYLON.Vector3(0, 0, 0);
  21596. var endRotation = new BABYLON.Quaternion();
  21597. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21598. endValue.decompose(endScale, endRotation, endTranslation);
  21599. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21600. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21601. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21602. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21603. return result;
  21604. };
  21605. Animation.prototype.clone = function () {
  21606. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21607. if (this._keys) {
  21608. clone.setKeys(this._keys);
  21609. }
  21610. return clone;
  21611. };
  21612. Animation.prototype.setKeys = function (values) {
  21613. this._keys = values.slice(0);
  21614. this._offsetsCache = {};
  21615. this._highLimitsCache = {};
  21616. };
  21617. Animation.prototype._getKeyValue = function (value) {
  21618. if (typeof value === "function") {
  21619. return value();
  21620. }
  21621. return value;
  21622. };
  21623. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21624. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21625. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21626. }
  21627. this.currentFrame = currentFrame;
  21628. // Try to get a hash to find the right key
  21629. 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));
  21630. if (this._keys[startKey].frame >= currentFrame) {
  21631. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21632. startKey--;
  21633. }
  21634. }
  21635. for (var key = startKey; key < this._keys.length; key++) {
  21636. if (this._keys[key + 1].frame >= currentFrame) {
  21637. var startValue = this._getKeyValue(this._keys[key].value);
  21638. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21639. // gradient : percent of currentFrame between the frame inf and the frame sup
  21640. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21641. // check for easingFunction and correction of gradient
  21642. if (this._easingFunction != null) {
  21643. gradient = this._easingFunction.ease(gradient);
  21644. }
  21645. switch (this.dataType) {
  21646. // Float
  21647. case Animation.ANIMATIONTYPE_FLOAT:
  21648. switch (loopMode) {
  21649. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21650. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21651. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21652. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21653. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21654. }
  21655. break;
  21656. // Quaternion
  21657. case Animation.ANIMATIONTYPE_QUATERNION:
  21658. var quaternion = null;
  21659. switch (loopMode) {
  21660. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21661. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21662. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21663. break;
  21664. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21665. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21666. break;
  21667. }
  21668. return quaternion;
  21669. // Vector3
  21670. case Animation.ANIMATIONTYPE_VECTOR3:
  21671. switch (loopMode) {
  21672. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21673. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21674. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21675. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21676. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21677. }
  21678. // Vector2
  21679. case Animation.ANIMATIONTYPE_VECTOR2:
  21680. switch (loopMode) {
  21681. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21682. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21683. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21684. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21685. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21686. }
  21687. // Color3
  21688. case Animation.ANIMATIONTYPE_COLOR3:
  21689. switch (loopMode) {
  21690. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21691. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21692. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21693. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21694. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21695. }
  21696. // Matrix
  21697. case Animation.ANIMATIONTYPE_MATRIX:
  21698. switch (loopMode) {
  21699. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21700. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21701. if (this.allowMatricesInterpolation) {
  21702. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21703. }
  21704. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21705. return startValue;
  21706. }
  21707. default:
  21708. break;
  21709. }
  21710. break;
  21711. }
  21712. }
  21713. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21714. };
  21715. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21716. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21717. this._stopped = true;
  21718. return false;
  21719. }
  21720. var returnValue = true;
  21721. // Adding a start key at frame 0 if missing
  21722. if (this._keys[0].frame !== 0) {
  21723. var newKey = { frame: 0, value: this._keys[0].value };
  21724. this._keys.splice(0, 0, newKey);
  21725. }
  21726. // Check limits
  21727. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21728. from = this._keys[0].frame;
  21729. }
  21730. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21731. to = this._keys[this._keys.length - 1].frame;
  21732. }
  21733. // Compute ratio
  21734. var range = to - from;
  21735. var offsetValue;
  21736. // ratio represents the frame delta between from and to
  21737. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21738. var highLimitValue = 0;
  21739. if (ratio > range && !loop) {
  21740. returnValue = false;
  21741. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21742. }
  21743. else {
  21744. // Get max value if required
  21745. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21746. var keyOffset = to.toString() + from.toString();
  21747. if (!this._offsetsCache[keyOffset]) {
  21748. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21749. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21750. switch (this.dataType) {
  21751. // Float
  21752. case Animation.ANIMATIONTYPE_FLOAT:
  21753. this._offsetsCache[keyOffset] = toValue - fromValue;
  21754. break;
  21755. // Quaternion
  21756. case Animation.ANIMATIONTYPE_QUATERNION:
  21757. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21758. break;
  21759. // Vector3
  21760. case Animation.ANIMATIONTYPE_VECTOR3:
  21761. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21762. // Vector2
  21763. case Animation.ANIMATIONTYPE_VECTOR2:
  21764. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21765. // Color3
  21766. case Animation.ANIMATIONTYPE_COLOR3:
  21767. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21768. default:
  21769. break;
  21770. }
  21771. this._highLimitsCache[keyOffset] = toValue;
  21772. }
  21773. highLimitValue = this._highLimitsCache[keyOffset];
  21774. offsetValue = this._offsetsCache[keyOffset];
  21775. }
  21776. }
  21777. if (offsetValue === undefined) {
  21778. switch (this.dataType) {
  21779. // Float
  21780. case Animation.ANIMATIONTYPE_FLOAT:
  21781. offsetValue = 0;
  21782. break;
  21783. // Quaternion
  21784. case Animation.ANIMATIONTYPE_QUATERNION:
  21785. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21786. break;
  21787. // Vector3
  21788. case Animation.ANIMATIONTYPE_VECTOR3:
  21789. offsetValue = BABYLON.Vector3.Zero();
  21790. break;
  21791. // Vector2
  21792. case Animation.ANIMATIONTYPE_VECTOR2:
  21793. offsetValue = BABYLON.Vector2.Zero();
  21794. break;
  21795. // Color3
  21796. case Animation.ANIMATIONTYPE_COLOR3:
  21797. offsetValue = BABYLON.Color3.Black();
  21798. }
  21799. }
  21800. // Compute value
  21801. var repeatCount = (ratio / range) >> 0;
  21802. var currentFrame = returnValue ? from + ratio % range : to;
  21803. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21804. // Set value
  21805. if (this.targetPropertyPath.length > 1) {
  21806. var property = this._target[this.targetPropertyPath[0]];
  21807. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21808. property = property[this.targetPropertyPath[index]];
  21809. }
  21810. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21811. }
  21812. else {
  21813. this._target[this.targetPropertyPath[0]] = currentValue;
  21814. }
  21815. if (this._target.markAsDirty) {
  21816. this._target.markAsDirty(this.targetProperty);
  21817. }
  21818. if (!returnValue) {
  21819. this._stopped = true;
  21820. }
  21821. return returnValue;
  21822. };
  21823. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21824. get: function () {
  21825. return Animation._ANIMATIONTYPE_FLOAT;
  21826. },
  21827. enumerable: true,
  21828. configurable: true
  21829. });
  21830. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21831. get: function () {
  21832. return Animation._ANIMATIONTYPE_VECTOR3;
  21833. },
  21834. enumerable: true,
  21835. configurable: true
  21836. });
  21837. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21838. get: function () {
  21839. return Animation._ANIMATIONTYPE_VECTOR2;
  21840. },
  21841. enumerable: true,
  21842. configurable: true
  21843. });
  21844. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21845. get: function () {
  21846. return Animation._ANIMATIONTYPE_QUATERNION;
  21847. },
  21848. enumerable: true,
  21849. configurable: true
  21850. });
  21851. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21852. get: function () {
  21853. return Animation._ANIMATIONTYPE_MATRIX;
  21854. },
  21855. enumerable: true,
  21856. configurable: true
  21857. });
  21858. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21859. get: function () {
  21860. return Animation._ANIMATIONTYPE_COLOR3;
  21861. },
  21862. enumerable: true,
  21863. configurable: true
  21864. });
  21865. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21866. get: function () {
  21867. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21868. },
  21869. enumerable: true,
  21870. configurable: true
  21871. });
  21872. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21873. get: function () {
  21874. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21875. },
  21876. enumerable: true,
  21877. configurable: true
  21878. });
  21879. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21880. get: function () {
  21881. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21882. },
  21883. enumerable: true,
  21884. configurable: true
  21885. });
  21886. // Statics
  21887. Animation._ANIMATIONTYPE_FLOAT = 0;
  21888. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21889. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21890. Animation._ANIMATIONTYPE_MATRIX = 3;
  21891. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21892. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21893. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21894. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21895. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21896. return Animation;
  21897. })();
  21898. BABYLON.Animation = Animation;
  21899. })(BABYLON || (BABYLON = {}));
  21900. var BABYLON;
  21901. (function (BABYLON) {
  21902. var Animatable = (function () {
  21903. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21904. if (fromFrame === void 0) { fromFrame = 0; }
  21905. if (toFrame === void 0) { toFrame = 100; }
  21906. if (loopAnimation === void 0) { loopAnimation = false; }
  21907. if (speedRatio === void 0) { speedRatio = 1.0; }
  21908. this.target = target;
  21909. this.fromFrame = fromFrame;
  21910. this.toFrame = toFrame;
  21911. this.loopAnimation = loopAnimation;
  21912. this.speedRatio = speedRatio;
  21913. this.onAnimationEnd = onAnimationEnd;
  21914. this._animations = new Array();
  21915. this._paused = false;
  21916. this.animationStarted = false;
  21917. if (animations) {
  21918. this.appendAnimations(target, animations);
  21919. }
  21920. this._scene = scene;
  21921. scene._activeAnimatables.push(this);
  21922. }
  21923. // Methods
  21924. Animatable.prototype.appendAnimations = function (target, animations) {
  21925. for (var index = 0; index < animations.length; index++) {
  21926. var animation = animations[index];
  21927. animation._target = target;
  21928. this._animations.push(animation);
  21929. }
  21930. };
  21931. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21932. var animations = this._animations;
  21933. for (var index = 0; index < animations.length; index++) {
  21934. if (animations[index].targetProperty === property) {
  21935. return animations[index];
  21936. }
  21937. }
  21938. return null;
  21939. };
  21940. Animatable.prototype.reset = function () {
  21941. var animations = this._animations;
  21942. for (var index = 0; index < animations.length; index++) {
  21943. animations[index].reset();
  21944. }
  21945. this._localDelayOffset = null;
  21946. this._pausedDelay = null;
  21947. };
  21948. Animatable.prototype.pause = function () {
  21949. if (this._paused) {
  21950. return;
  21951. }
  21952. this._paused = true;
  21953. };
  21954. Animatable.prototype.restart = function () {
  21955. this._paused = false;
  21956. };
  21957. Animatable.prototype.stop = function () {
  21958. var index = this._scene._activeAnimatables.indexOf(this);
  21959. if (index > -1) {
  21960. this._scene._activeAnimatables.splice(index, 1);
  21961. }
  21962. if (this.onAnimationEnd) {
  21963. this.onAnimationEnd();
  21964. }
  21965. };
  21966. Animatable.prototype._animate = function (delay) {
  21967. if (this._paused) {
  21968. if (!this._pausedDelay) {
  21969. this._pausedDelay = delay;
  21970. }
  21971. return true;
  21972. }
  21973. if (!this._localDelayOffset) {
  21974. this._localDelayOffset = delay;
  21975. }
  21976. else if (this._pausedDelay) {
  21977. this._localDelayOffset += delay - this._pausedDelay;
  21978. this._pausedDelay = null;
  21979. }
  21980. // Animating
  21981. var running = false;
  21982. var animations = this._animations;
  21983. for (var index = 0; index < animations.length; index++) {
  21984. var animation = animations[index];
  21985. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21986. running = running || isRunning;
  21987. }
  21988. if (!running) {
  21989. // Remove from active animatables
  21990. index = this._scene._activeAnimatables.indexOf(this);
  21991. this._scene._activeAnimatables.splice(index, 1);
  21992. }
  21993. if (!running && this.onAnimationEnd) {
  21994. this.onAnimationEnd();
  21995. }
  21996. return running;
  21997. };
  21998. return Animatable;
  21999. })();
  22000. BABYLON.Animatable = Animatable;
  22001. })(BABYLON || (BABYLON = {}));
  22002. var BABYLON;
  22003. (function (BABYLON) {
  22004. var EasingFunction = (function () {
  22005. function EasingFunction() {
  22006. // Properties
  22007. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22008. }
  22009. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22010. get: function () {
  22011. return EasingFunction._EASINGMODE_EASEIN;
  22012. },
  22013. enumerable: true,
  22014. configurable: true
  22015. });
  22016. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22017. get: function () {
  22018. return EasingFunction._EASINGMODE_EASEOUT;
  22019. },
  22020. enumerable: true,
  22021. configurable: true
  22022. });
  22023. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22024. get: function () {
  22025. return EasingFunction._EASINGMODE_EASEINOUT;
  22026. },
  22027. enumerable: true,
  22028. configurable: true
  22029. });
  22030. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22031. var n = Math.min(Math.max(easingMode, 0), 2);
  22032. this._easingMode = n;
  22033. };
  22034. EasingFunction.prototype.getEasingMode = function () {
  22035. return this._easingMode;
  22036. };
  22037. EasingFunction.prototype.easeInCore = function (gradient) {
  22038. throw new Error('You must implement this method');
  22039. };
  22040. EasingFunction.prototype.ease = function (gradient) {
  22041. switch (this._easingMode) {
  22042. case EasingFunction.EASINGMODE_EASEIN:
  22043. return this.easeInCore(gradient);
  22044. case EasingFunction.EASINGMODE_EASEOUT:
  22045. return (1 - this.easeInCore(1 - gradient));
  22046. }
  22047. if (gradient >= 0.5) {
  22048. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22049. }
  22050. return (this.easeInCore(gradient * 2) * 0.5);
  22051. };
  22052. //Statics
  22053. EasingFunction._EASINGMODE_EASEIN = 0;
  22054. EasingFunction._EASINGMODE_EASEOUT = 1;
  22055. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22056. return EasingFunction;
  22057. })();
  22058. BABYLON.EasingFunction = EasingFunction;
  22059. var CircleEase = (function (_super) {
  22060. __extends(CircleEase, _super);
  22061. function CircleEase() {
  22062. _super.apply(this, arguments);
  22063. }
  22064. CircleEase.prototype.easeInCore = function (gradient) {
  22065. gradient = Math.max(0, Math.min(1, gradient));
  22066. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22067. };
  22068. return CircleEase;
  22069. })(EasingFunction);
  22070. BABYLON.CircleEase = CircleEase;
  22071. var BackEase = (function (_super) {
  22072. __extends(BackEase, _super);
  22073. function BackEase(amplitude) {
  22074. if (amplitude === void 0) { amplitude = 1; }
  22075. _super.call(this);
  22076. this.amplitude = amplitude;
  22077. }
  22078. BackEase.prototype.easeInCore = function (gradient) {
  22079. var num = Math.max(0, this.amplitude);
  22080. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22081. };
  22082. return BackEase;
  22083. })(EasingFunction);
  22084. BABYLON.BackEase = BackEase;
  22085. var BounceEase = (function (_super) {
  22086. __extends(BounceEase, _super);
  22087. function BounceEase(bounces, bounciness) {
  22088. if (bounces === void 0) { bounces = 3; }
  22089. if (bounciness === void 0) { bounciness = 2; }
  22090. _super.call(this);
  22091. this.bounces = bounces;
  22092. this.bounciness = bounciness;
  22093. }
  22094. BounceEase.prototype.easeInCore = function (gradient) {
  22095. var y = Math.max(0.0, this.bounces);
  22096. var bounciness = this.bounciness;
  22097. if (bounciness <= 1.0) {
  22098. bounciness = 1.001;
  22099. }
  22100. var num9 = Math.pow(bounciness, y);
  22101. var num5 = 1.0 - bounciness;
  22102. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22103. var num15 = gradient * num4;
  22104. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22105. var num3 = Math.floor(num65);
  22106. var num13 = num3 + 1.0;
  22107. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22108. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22109. var num7 = (num8 + num12) * 0.5;
  22110. var num6 = gradient - num7;
  22111. var num2 = num7 - num8;
  22112. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22113. };
  22114. return BounceEase;
  22115. })(EasingFunction);
  22116. BABYLON.BounceEase = BounceEase;
  22117. var CubicEase = (function (_super) {
  22118. __extends(CubicEase, _super);
  22119. function CubicEase() {
  22120. _super.apply(this, arguments);
  22121. }
  22122. CubicEase.prototype.easeInCore = function (gradient) {
  22123. return (gradient * gradient * gradient);
  22124. };
  22125. return CubicEase;
  22126. })(EasingFunction);
  22127. BABYLON.CubicEase = CubicEase;
  22128. var ElasticEase = (function (_super) {
  22129. __extends(ElasticEase, _super);
  22130. function ElasticEase(oscillations, springiness) {
  22131. if (oscillations === void 0) { oscillations = 3; }
  22132. if (springiness === void 0) { springiness = 3; }
  22133. _super.call(this);
  22134. this.oscillations = oscillations;
  22135. this.springiness = springiness;
  22136. }
  22137. ElasticEase.prototype.easeInCore = function (gradient) {
  22138. var num2;
  22139. var num3 = Math.max(0.0, this.oscillations);
  22140. var num = Math.max(0.0, this.springiness);
  22141. if (num == 0) {
  22142. num2 = gradient;
  22143. }
  22144. else {
  22145. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22146. }
  22147. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22148. };
  22149. return ElasticEase;
  22150. })(EasingFunction);
  22151. BABYLON.ElasticEase = ElasticEase;
  22152. var ExponentialEase = (function (_super) {
  22153. __extends(ExponentialEase, _super);
  22154. function ExponentialEase(exponent) {
  22155. if (exponent === void 0) { exponent = 2; }
  22156. _super.call(this);
  22157. this.exponent = exponent;
  22158. }
  22159. ExponentialEase.prototype.easeInCore = function (gradient) {
  22160. if (this.exponent <= 0) {
  22161. return gradient;
  22162. }
  22163. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22164. };
  22165. return ExponentialEase;
  22166. })(EasingFunction);
  22167. BABYLON.ExponentialEase = ExponentialEase;
  22168. var PowerEase = (function (_super) {
  22169. __extends(PowerEase, _super);
  22170. function PowerEase(power) {
  22171. if (power === void 0) { power = 2; }
  22172. _super.call(this);
  22173. this.power = power;
  22174. }
  22175. PowerEase.prototype.easeInCore = function (gradient) {
  22176. var y = Math.max(0.0, this.power);
  22177. return Math.pow(gradient, y);
  22178. };
  22179. return PowerEase;
  22180. })(EasingFunction);
  22181. BABYLON.PowerEase = PowerEase;
  22182. var QuadraticEase = (function (_super) {
  22183. __extends(QuadraticEase, _super);
  22184. function QuadraticEase() {
  22185. _super.apply(this, arguments);
  22186. }
  22187. QuadraticEase.prototype.easeInCore = function (gradient) {
  22188. return (gradient * gradient);
  22189. };
  22190. return QuadraticEase;
  22191. })(EasingFunction);
  22192. BABYLON.QuadraticEase = QuadraticEase;
  22193. var QuarticEase = (function (_super) {
  22194. __extends(QuarticEase, _super);
  22195. function QuarticEase() {
  22196. _super.apply(this, arguments);
  22197. }
  22198. QuarticEase.prototype.easeInCore = function (gradient) {
  22199. return (gradient * gradient * gradient * gradient);
  22200. };
  22201. return QuarticEase;
  22202. })(EasingFunction);
  22203. BABYLON.QuarticEase = QuarticEase;
  22204. var QuinticEase = (function (_super) {
  22205. __extends(QuinticEase, _super);
  22206. function QuinticEase() {
  22207. _super.apply(this, arguments);
  22208. }
  22209. QuinticEase.prototype.easeInCore = function (gradient) {
  22210. return (gradient * gradient * gradient * gradient * gradient);
  22211. };
  22212. return QuinticEase;
  22213. })(EasingFunction);
  22214. BABYLON.QuinticEase = QuinticEase;
  22215. var SineEase = (function (_super) {
  22216. __extends(SineEase, _super);
  22217. function SineEase() {
  22218. _super.apply(this, arguments);
  22219. }
  22220. SineEase.prototype.easeInCore = function (gradient) {
  22221. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22222. };
  22223. return SineEase;
  22224. })(EasingFunction);
  22225. BABYLON.SineEase = SineEase;
  22226. var BezierCurveEase = (function (_super) {
  22227. __extends(BezierCurveEase, _super);
  22228. function BezierCurveEase(x1, y1, x2, y2) {
  22229. if (x1 === void 0) { x1 = 0; }
  22230. if (y1 === void 0) { y1 = 0; }
  22231. if (x2 === void 0) { x2 = 1; }
  22232. if (y2 === void 0) { y2 = 1; }
  22233. _super.call(this);
  22234. this.x1 = x1;
  22235. this.y1 = y1;
  22236. this.x2 = x2;
  22237. this.y2 = y2;
  22238. }
  22239. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22240. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22241. };
  22242. return BezierCurveEase;
  22243. })(EasingFunction);
  22244. BABYLON.BezierCurveEase = BezierCurveEase;
  22245. })(BABYLON || (BABYLON = {}));
  22246. var BABYLON;
  22247. (function (BABYLON) {
  22248. var Bone = (function (_super) {
  22249. __extends(Bone, _super);
  22250. function Bone(name, skeleton, parentBone, matrix) {
  22251. _super.call(this, name, skeleton.getScene());
  22252. this.name = name;
  22253. this.children = new Array();
  22254. this.animations = new Array();
  22255. this._worldTransform = new BABYLON.Matrix();
  22256. this._absoluteTransform = new BABYLON.Matrix();
  22257. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22258. this._skeleton = skeleton;
  22259. this._matrix = matrix;
  22260. this._baseMatrix = matrix;
  22261. skeleton.bones.push(this);
  22262. if (parentBone) {
  22263. this._parent = parentBone;
  22264. parentBone.children.push(this);
  22265. }
  22266. else {
  22267. this._parent = null;
  22268. }
  22269. this._updateDifferenceMatrix();
  22270. }
  22271. // Members
  22272. Bone.prototype.getParent = function () {
  22273. return this._parent;
  22274. };
  22275. Bone.prototype.getLocalMatrix = function () {
  22276. return this._matrix;
  22277. };
  22278. Bone.prototype.getBaseMatrix = function () {
  22279. return this._baseMatrix;
  22280. };
  22281. Bone.prototype.getWorldMatrix = function () {
  22282. return this._worldTransform;
  22283. };
  22284. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22285. return this._invertedAbsoluteTransform;
  22286. };
  22287. Bone.prototype.getAbsoluteMatrix = function () {
  22288. var matrix = this._matrix.clone();
  22289. var parent = this._parent;
  22290. while (parent) {
  22291. matrix = matrix.multiply(parent.getLocalMatrix());
  22292. parent = parent.getParent();
  22293. }
  22294. return matrix;
  22295. };
  22296. // Methods
  22297. Bone.prototype.updateMatrix = function (matrix) {
  22298. this._matrix = matrix;
  22299. this._skeleton._markAsDirty();
  22300. this._updateDifferenceMatrix();
  22301. };
  22302. Bone.prototype._updateDifferenceMatrix = function () {
  22303. if (this._parent) {
  22304. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22305. }
  22306. else {
  22307. this._absoluteTransform.copyFrom(this._matrix);
  22308. }
  22309. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22310. for (var index = 0; index < this.children.length; index++) {
  22311. this.children[index]._updateDifferenceMatrix();
  22312. }
  22313. };
  22314. Bone.prototype.markAsDirty = function () {
  22315. this._currentRenderId++;
  22316. this._skeleton._markAsDirty();
  22317. };
  22318. return Bone;
  22319. })(BABYLON.Node);
  22320. BABYLON.Bone = Bone;
  22321. })(BABYLON || (BABYLON = {}));
  22322. var BABYLON;
  22323. (function (BABYLON) {
  22324. var Skeleton = (function () {
  22325. function Skeleton(name, id, scene) {
  22326. this.name = name;
  22327. this.id = id;
  22328. this.bones = new Array();
  22329. this._isDirty = true;
  22330. this._identity = BABYLON.Matrix.Identity();
  22331. this.bones = [];
  22332. this._scene = scene;
  22333. scene.skeletons.push(this);
  22334. this.prepare();
  22335. //make sure it will recalculate the matrix next time prepare is called.
  22336. this._isDirty = true;
  22337. }
  22338. // Members
  22339. Skeleton.prototype.getTransformMatrices = function () {
  22340. return this._transformMatrices;
  22341. };
  22342. Skeleton.prototype.getScene = function () {
  22343. return this._scene;
  22344. };
  22345. // Methods
  22346. Skeleton.prototype._markAsDirty = function () {
  22347. this._isDirty = true;
  22348. };
  22349. Skeleton.prototype.prepare = function () {
  22350. if (!this._isDirty) {
  22351. return;
  22352. }
  22353. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22354. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22355. }
  22356. for (var index = 0; index < this.bones.length; index++) {
  22357. var bone = this.bones[index];
  22358. var parentBone = bone.getParent();
  22359. if (parentBone) {
  22360. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22361. }
  22362. else {
  22363. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22364. }
  22365. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22366. }
  22367. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22368. this._isDirty = false;
  22369. this._scene._activeBones += this.bones.length;
  22370. };
  22371. Skeleton.prototype.getAnimatables = function () {
  22372. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22373. this._animatables = [];
  22374. for (var index = 0; index < this.bones.length; index++) {
  22375. this._animatables.push(this.bones[index]);
  22376. }
  22377. }
  22378. return this._animatables;
  22379. };
  22380. Skeleton.prototype.clone = function (name, id) {
  22381. var result = new Skeleton(name, id || name, this._scene);
  22382. for (var index = 0; index < this.bones.length; index++) {
  22383. var source = this.bones[index];
  22384. var parentBone = null;
  22385. if (source.getParent()) {
  22386. var parentIndex = this.bones.indexOf(source.getParent());
  22387. parentBone = result.bones[parentIndex];
  22388. }
  22389. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22390. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22391. }
  22392. return result;
  22393. };
  22394. return Skeleton;
  22395. })();
  22396. BABYLON.Skeleton = Skeleton;
  22397. })(BABYLON || (BABYLON = {}));
  22398. var BABYLON;
  22399. (function (BABYLON) {
  22400. var PostProcess = (function () {
  22401. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22402. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22403. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22404. this.name = name;
  22405. this.width = -1;
  22406. this.height = -1;
  22407. this._reusable = false;
  22408. this._textures = new BABYLON.SmartArray(2);
  22409. this._currentRenderTextureInd = 0;
  22410. if (camera != null) {
  22411. this._camera = camera;
  22412. this._scene = camera.getScene();
  22413. camera.attachPostProcess(this);
  22414. this._engine = this._scene.getEngine();
  22415. }
  22416. else {
  22417. this._engine = engine;
  22418. }
  22419. this._renderRatio = ratio;
  22420. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22421. this._reusable = reusable || false;
  22422. this._textureType = textureType;
  22423. samplers = samplers || [];
  22424. samplers.push("textureSampler");
  22425. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22426. }
  22427. PostProcess.prototype.isReusable = function () {
  22428. return this._reusable;
  22429. };
  22430. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22431. camera = camera || this._camera;
  22432. var scene = camera.getScene();
  22433. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22434. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22435. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22436. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22437. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22438. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22439. if (this._textures.length > 0) {
  22440. for (var i = 0; i < this._textures.length; i++) {
  22441. this._engine._releaseTexture(this._textures.data[i]);
  22442. }
  22443. this._textures.reset();
  22444. }
  22445. this.width = desiredWidth;
  22446. this.height = desiredHeight;
  22447. 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 }));
  22448. if (this._reusable) {
  22449. 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 }));
  22450. }
  22451. if (this.onSizeChanged) {
  22452. this.onSizeChanged();
  22453. }
  22454. }
  22455. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22456. if (this.onActivate) {
  22457. this.onActivate(camera);
  22458. }
  22459. // Clear
  22460. if (this.clearColor) {
  22461. this._engine.clear(this.clearColor, true, true);
  22462. }
  22463. else {
  22464. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22465. }
  22466. if (this._reusable) {
  22467. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22468. }
  22469. };
  22470. PostProcess.prototype.apply = function () {
  22471. // Check
  22472. if (!this._effect.isReady())
  22473. return null;
  22474. // States
  22475. this._engine.enableEffect(this._effect);
  22476. this._engine.setState(false);
  22477. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22478. this._engine.setDepthBuffer(false);
  22479. this._engine.setDepthWrite(false);
  22480. // Texture
  22481. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22482. // Parameters
  22483. if (this.onApply) {
  22484. this.onApply(this._effect);
  22485. }
  22486. return this._effect;
  22487. };
  22488. PostProcess.prototype.dispose = function (camera) {
  22489. camera = camera || this._camera;
  22490. if (this._textures.length > 0) {
  22491. for (var i = 0; i < this._textures.length; i++) {
  22492. this._engine._releaseTexture(this._textures.data[i]);
  22493. }
  22494. this._textures.reset();
  22495. }
  22496. if (!camera) {
  22497. return;
  22498. }
  22499. camera.detachPostProcess(this);
  22500. var index = camera._postProcesses.indexOf(this);
  22501. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22502. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22503. }
  22504. };
  22505. return PostProcess;
  22506. })();
  22507. BABYLON.PostProcess = PostProcess;
  22508. })(BABYLON || (BABYLON = {}));
  22509. var BABYLON;
  22510. (function (BABYLON) {
  22511. var PostProcessManager = (function () {
  22512. function PostProcessManager(scene) {
  22513. this._vertexDeclaration = [2];
  22514. this._vertexStrideSize = 2 * 4;
  22515. this._scene = scene;
  22516. }
  22517. PostProcessManager.prototype._prepareBuffers = function () {
  22518. if (this._vertexBuffer) {
  22519. return;
  22520. }
  22521. // VBO
  22522. var vertices = [];
  22523. vertices.push(1, 1);
  22524. vertices.push(-1, 1);
  22525. vertices.push(-1, -1);
  22526. vertices.push(1, -1);
  22527. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22528. // Indices
  22529. var indices = [];
  22530. indices.push(0);
  22531. indices.push(1);
  22532. indices.push(2);
  22533. indices.push(0);
  22534. indices.push(2);
  22535. indices.push(3);
  22536. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22537. };
  22538. // Methods
  22539. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22540. var postProcesses = this._scene.activeCamera._postProcesses;
  22541. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22542. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22543. return false;
  22544. }
  22545. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22546. return true;
  22547. };
  22548. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22549. var engine = this._scene.getEngine();
  22550. for (var index = 0; index < postProcesses.length; index++) {
  22551. if (index < postProcesses.length - 1) {
  22552. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22553. }
  22554. else {
  22555. if (targetTexture) {
  22556. engine.bindFramebuffer(targetTexture);
  22557. }
  22558. else {
  22559. engine.restoreDefaultFramebuffer();
  22560. }
  22561. }
  22562. var pp = postProcesses[index];
  22563. var effect = pp.apply();
  22564. if (effect) {
  22565. if (pp.onBeforeRender) {
  22566. pp.onBeforeRender(effect);
  22567. }
  22568. // VBOs
  22569. this._prepareBuffers();
  22570. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22571. // Draw order
  22572. engine.draw(true, 0, 6);
  22573. if (pp.onAfterRender) {
  22574. pp.onAfterRender(effect);
  22575. }
  22576. }
  22577. }
  22578. // Restore depth buffer
  22579. engine.setDepthBuffer(true);
  22580. engine.setDepthWrite(true);
  22581. };
  22582. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22583. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22584. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22585. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22586. return;
  22587. }
  22588. var engine = this._scene.getEngine();
  22589. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22590. if (index < postProcessesTakenIndices.length - 1) {
  22591. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22592. }
  22593. else {
  22594. if (targetTexture) {
  22595. engine.bindFramebuffer(targetTexture, faceIndex);
  22596. }
  22597. else {
  22598. engine.restoreDefaultFramebuffer();
  22599. }
  22600. }
  22601. if (doNotPresent) {
  22602. break;
  22603. }
  22604. var pp = postProcesses[postProcessesTakenIndices[index]];
  22605. var effect = pp.apply();
  22606. if (effect) {
  22607. if (pp.onBeforeRender) {
  22608. pp.onBeforeRender(effect);
  22609. }
  22610. // VBOs
  22611. this._prepareBuffers();
  22612. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22613. // Draw order
  22614. engine.draw(true, 0, 6);
  22615. if (pp.onAfterRender) {
  22616. pp.onAfterRender(effect);
  22617. }
  22618. }
  22619. }
  22620. // Restore depth buffer
  22621. engine.setDepthBuffer(true);
  22622. engine.setDepthWrite(true);
  22623. };
  22624. PostProcessManager.prototype.dispose = function () {
  22625. if (this._vertexBuffer) {
  22626. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22627. this._vertexBuffer = null;
  22628. }
  22629. if (this._indexBuffer) {
  22630. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22631. this._indexBuffer = null;
  22632. }
  22633. };
  22634. return PostProcessManager;
  22635. })();
  22636. BABYLON.PostProcessManager = PostProcessManager;
  22637. })(BABYLON || (BABYLON = {}));
  22638. var BABYLON;
  22639. (function (BABYLON) {
  22640. var PassPostProcess = (function (_super) {
  22641. __extends(PassPostProcess, _super);
  22642. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22643. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22644. }
  22645. return PassPostProcess;
  22646. })(BABYLON.PostProcess);
  22647. BABYLON.PassPostProcess = PassPostProcess;
  22648. })(BABYLON || (BABYLON = {}));
  22649. var BABYLON;
  22650. (function (BABYLON) {
  22651. var PhysicsEngine = (function () {
  22652. function PhysicsEngine(plugin) {
  22653. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22654. }
  22655. PhysicsEngine.prototype._initialize = function (gravity) {
  22656. this._currentPlugin.initialize();
  22657. this._setGravity(gravity);
  22658. };
  22659. PhysicsEngine.prototype._runOneStep = function (delta) {
  22660. if (delta > 0.1) {
  22661. delta = 0.1;
  22662. }
  22663. else if (delta <= 0) {
  22664. delta = 1.0 / 60.0;
  22665. }
  22666. this._currentPlugin.runOneStep(delta);
  22667. };
  22668. PhysicsEngine.prototype._setGravity = function (gravity) {
  22669. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22670. this._currentPlugin.setGravity(this.gravity);
  22671. };
  22672. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22673. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22674. };
  22675. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22676. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22677. };
  22678. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22679. this._currentPlugin.unregisterMesh(mesh);
  22680. };
  22681. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22682. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22683. };
  22684. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22685. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22686. };
  22687. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22688. this._currentPlugin.updateBodyPosition(mesh);
  22689. };
  22690. PhysicsEngine.prototype.dispose = function () {
  22691. this._currentPlugin.dispose();
  22692. };
  22693. PhysicsEngine.prototype.isSupported = function () {
  22694. return this._currentPlugin.isSupported();
  22695. };
  22696. // Statics
  22697. PhysicsEngine.NoImpostor = 0;
  22698. PhysicsEngine.SphereImpostor = 1;
  22699. PhysicsEngine.BoxImpostor = 2;
  22700. PhysicsEngine.PlaneImpostor = 3;
  22701. PhysicsEngine.MeshImpostor = 4;
  22702. PhysicsEngine.CapsuleImpostor = 5;
  22703. PhysicsEngine.ConeImpostor = 6;
  22704. PhysicsEngine.CylinderImpostor = 7;
  22705. PhysicsEngine.ConvexHullImpostor = 8;
  22706. PhysicsEngine.Epsilon = 0.001;
  22707. return PhysicsEngine;
  22708. })();
  22709. BABYLON.PhysicsEngine = PhysicsEngine;
  22710. })(BABYLON || (BABYLON = {}));
  22711. var BABYLON;
  22712. (function (BABYLON) {
  22713. var VertexData = (function () {
  22714. function VertexData() {
  22715. }
  22716. VertexData.prototype.set = function (data, kind) {
  22717. switch (kind) {
  22718. case BABYLON.VertexBuffer.PositionKind:
  22719. this.positions = data;
  22720. break;
  22721. case BABYLON.VertexBuffer.NormalKind:
  22722. this.normals = data;
  22723. break;
  22724. case BABYLON.VertexBuffer.UVKind:
  22725. this.uvs = data;
  22726. break;
  22727. case BABYLON.VertexBuffer.UV2Kind:
  22728. this.uvs2 = data;
  22729. break;
  22730. case BABYLON.VertexBuffer.UV3Kind:
  22731. this.uvs3 = data;
  22732. break;
  22733. case BABYLON.VertexBuffer.UV4Kind:
  22734. this.uvs4 = data;
  22735. break;
  22736. case BABYLON.VertexBuffer.UV5Kind:
  22737. this.uvs5 = data;
  22738. break;
  22739. case BABYLON.VertexBuffer.UV6Kind:
  22740. this.uvs6 = data;
  22741. break;
  22742. case BABYLON.VertexBuffer.ColorKind:
  22743. this.colors = data;
  22744. break;
  22745. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22746. this.matricesIndices = data;
  22747. break;
  22748. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22749. this.matricesWeights = data;
  22750. break;
  22751. }
  22752. };
  22753. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22754. this._applyTo(mesh, updatable);
  22755. };
  22756. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22757. this._applyTo(geometry, updatable);
  22758. };
  22759. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22760. this._update(mesh);
  22761. };
  22762. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22763. this._update(geometry);
  22764. };
  22765. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22766. if (this.positions) {
  22767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22768. }
  22769. if (this.normals) {
  22770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22771. }
  22772. if (this.uvs) {
  22773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22774. }
  22775. if (this.uvs2) {
  22776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22777. }
  22778. if (this.uvs3) {
  22779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22780. }
  22781. if (this.uvs4) {
  22782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22783. }
  22784. if (this.uvs5) {
  22785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22786. }
  22787. if (this.uvs6) {
  22788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22789. }
  22790. if (this.colors) {
  22791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22792. }
  22793. if (this.matricesIndices) {
  22794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22795. }
  22796. if (this.matricesWeights) {
  22797. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22798. }
  22799. if (this.indices) {
  22800. meshOrGeometry.setIndices(this.indices);
  22801. }
  22802. };
  22803. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22804. if (this.positions) {
  22805. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22806. }
  22807. if (this.normals) {
  22808. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22809. }
  22810. if (this.uvs) {
  22811. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22812. }
  22813. if (this.uvs2) {
  22814. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22815. }
  22816. if (this.uvs3) {
  22817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22818. }
  22819. if (this.uvs4) {
  22820. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22821. }
  22822. if (this.uvs5) {
  22823. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22824. }
  22825. if (this.uvs6) {
  22826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22827. }
  22828. if (this.colors) {
  22829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22830. }
  22831. if (this.matricesIndices) {
  22832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22833. }
  22834. if (this.matricesWeights) {
  22835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22836. }
  22837. if (this.indices) {
  22838. meshOrGeometry.setIndices(this.indices);
  22839. }
  22840. };
  22841. VertexData.prototype.transform = function (matrix) {
  22842. var transformed = BABYLON.Vector3.Zero();
  22843. var index;
  22844. if (this.positions) {
  22845. var position = BABYLON.Vector3.Zero();
  22846. for (index = 0; index < this.positions.length; index += 3) {
  22847. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22848. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22849. this.positions[index] = transformed.x;
  22850. this.positions[index + 1] = transformed.y;
  22851. this.positions[index + 2] = transformed.z;
  22852. }
  22853. }
  22854. if (this.normals) {
  22855. var normal = BABYLON.Vector3.Zero();
  22856. for (index = 0; index < this.normals.length; index += 3) {
  22857. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22858. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22859. this.normals[index] = transformed.x;
  22860. this.normals[index + 1] = transformed.y;
  22861. this.normals[index + 2] = transformed.z;
  22862. }
  22863. }
  22864. };
  22865. VertexData.prototype.merge = function (other) {
  22866. var index;
  22867. if (other.indices) {
  22868. if (!this.indices) {
  22869. this.indices = [];
  22870. }
  22871. var offset = this.positions ? this.positions.length / 3 : 0;
  22872. for (index = 0; index < other.indices.length; index++) {
  22873. this.indices.push(other.indices[index] + offset);
  22874. }
  22875. }
  22876. if (other.positions) {
  22877. if (!this.positions) {
  22878. this.positions = [];
  22879. }
  22880. for (index = 0; index < other.positions.length; index++) {
  22881. this.positions.push(other.positions[index]);
  22882. }
  22883. }
  22884. if (other.normals) {
  22885. if (!this.normals) {
  22886. this.normals = [];
  22887. }
  22888. for (index = 0; index < other.normals.length; index++) {
  22889. this.normals.push(other.normals[index]);
  22890. }
  22891. }
  22892. if (other.uvs) {
  22893. if (!this.uvs) {
  22894. this.uvs = [];
  22895. }
  22896. for (index = 0; index < other.uvs.length; index++) {
  22897. this.uvs.push(other.uvs[index]);
  22898. }
  22899. }
  22900. if (other.uvs2) {
  22901. if (!this.uvs2) {
  22902. this.uvs2 = [];
  22903. }
  22904. for (index = 0; index < other.uvs2.length; index++) {
  22905. this.uvs2.push(other.uvs2[index]);
  22906. }
  22907. }
  22908. if (other.uvs3) {
  22909. if (!this.uvs3) {
  22910. this.uvs3 = [];
  22911. }
  22912. for (index = 0; index < other.uvs3.length; index++) {
  22913. this.uvs3.push(other.uvs3[index]);
  22914. }
  22915. }
  22916. if (other.uvs4) {
  22917. if (!this.uvs4) {
  22918. this.uvs4 = [];
  22919. }
  22920. for (index = 0; index < other.uvs4.length; index++) {
  22921. this.uvs4.push(other.uvs4[index]);
  22922. }
  22923. }
  22924. if (other.uvs5) {
  22925. if (!this.uvs5) {
  22926. this.uvs5 = [];
  22927. }
  22928. for (index = 0; index < other.uvs5.length; index++) {
  22929. this.uvs5.push(other.uvs5[index]);
  22930. }
  22931. }
  22932. if (other.uvs6) {
  22933. if (!this.uvs6) {
  22934. this.uvs6 = [];
  22935. }
  22936. for (index = 0; index < other.uvs6.length; index++) {
  22937. this.uvs6.push(other.uvs6[index]);
  22938. }
  22939. }
  22940. if (other.matricesIndices) {
  22941. if (!this.matricesIndices) {
  22942. this.matricesIndices = [];
  22943. }
  22944. for (index = 0; index < other.matricesIndices.length; index++) {
  22945. this.matricesIndices.push(other.matricesIndices[index]);
  22946. }
  22947. }
  22948. if (other.matricesWeights) {
  22949. if (!this.matricesWeights) {
  22950. this.matricesWeights = [];
  22951. }
  22952. for (index = 0; index < other.matricesWeights.length; index++) {
  22953. this.matricesWeights.push(other.matricesWeights[index]);
  22954. }
  22955. }
  22956. if (other.colors) {
  22957. if (!this.colors) {
  22958. this.colors = [];
  22959. }
  22960. for (index = 0; index < other.colors.length; index++) {
  22961. this.colors.push(other.colors[index]);
  22962. }
  22963. }
  22964. };
  22965. // Statics
  22966. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  22967. return VertexData._ExtractFrom(mesh, copyWhenShared);
  22968. };
  22969. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  22970. return VertexData._ExtractFrom(geometry, copyWhenShared);
  22971. };
  22972. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  22973. var result = new VertexData();
  22974. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22975. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  22976. }
  22977. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22978. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  22979. }
  22980. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22981. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  22982. }
  22983. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22984. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  22985. }
  22986. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  22987. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  22988. }
  22989. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  22990. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  22991. }
  22992. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  22993. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  22994. }
  22995. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  22996. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  22997. }
  22998. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22999. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23000. }
  23001. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23002. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23003. }
  23004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23005. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23006. }
  23007. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23008. return result;
  23009. };
  23010. VertexData.CreateRibbon = function (options) {
  23011. var pathArray = options.pathArray;
  23012. var closeArray = options.closeArray || false;
  23013. var closePath = options.closePath || false;
  23014. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23015. var offset = options.offset || defaultOffset;
  23016. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23017. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23018. var positions = [];
  23019. var indices = [];
  23020. var normals = [];
  23021. var uvs = [];
  23022. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23023. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23024. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23025. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23026. var minlg; // minimal length among all paths from pathArray
  23027. var lg = []; // array of path lengths : nb of vertex per path
  23028. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23029. var p; // path iterator
  23030. var i; // point iterator
  23031. var j; // point iterator
  23032. // if single path in pathArray
  23033. if (pathArray.length < 2) {
  23034. var ar1 = [];
  23035. var ar2 = [];
  23036. for (i = 0; i < pathArray[0].length - offset; i++) {
  23037. ar1.push(pathArray[0][i]);
  23038. ar2.push(pathArray[0][i + offset]);
  23039. }
  23040. pathArray = [ar1, ar2];
  23041. }
  23042. // positions and horizontal distances (u)
  23043. var idc = 0;
  23044. var closePathCorr = (closePath) ? 1 : 0;
  23045. var path;
  23046. var l;
  23047. minlg = pathArray[0].length;
  23048. var vectlg;
  23049. var dist;
  23050. for (p = 0; p < pathArray.length; p++) {
  23051. uTotalDistance[p] = 0;
  23052. us[p] = [0];
  23053. path = pathArray[p];
  23054. l = path.length;
  23055. minlg = (minlg < l) ? minlg : l;
  23056. j = 0;
  23057. while (j < l) {
  23058. positions.push(path[j].x, path[j].y, path[j].z);
  23059. if (j > 0) {
  23060. vectlg = path[j].subtract(path[j - 1]).length();
  23061. dist = vectlg + uTotalDistance[p];
  23062. us[p].push(dist);
  23063. uTotalDistance[p] = dist;
  23064. }
  23065. j++;
  23066. }
  23067. if (closePath) {
  23068. j--;
  23069. positions.push(path[0].x, path[0].y, path[0].z);
  23070. vectlg = path[j].subtract(path[0]).length();
  23071. dist = vectlg + uTotalDistance[p];
  23072. us[p].push(dist);
  23073. uTotalDistance[p] = dist;
  23074. }
  23075. lg[p] = l + closePathCorr;
  23076. idx[p] = idc;
  23077. idc += (l + closePathCorr);
  23078. }
  23079. // vertical distances (v)
  23080. var path1;
  23081. var path2;
  23082. var vertex1;
  23083. var vertex2;
  23084. for (i = 0; i < minlg + closePathCorr; i++) {
  23085. vTotalDistance[i] = 0;
  23086. vs[i] = [0];
  23087. for (p = 0; p < pathArray.length - 1; p++) {
  23088. path1 = pathArray[p];
  23089. path2 = pathArray[p + 1];
  23090. if (i === minlg) {
  23091. vertex1 = path1[0];
  23092. vertex2 = path2[0];
  23093. }
  23094. else {
  23095. vertex1 = path1[i];
  23096. vertex2 = path2[i];
  23097. }
  23098. vectlg = vertex2.subtract(vertex1).length();
  23099. dist = vectlg + vTotalDistance[i];
  23100. vs[i].push(dist);
  23101. vTotalDistance[i] = dist;
  23102. }
  23103. if (closeArray) {
  23104. path1 = pathArray[p];
  23105. path2 = pathArray[0];
  23106. if (i === minlg) {
  23107. vertex2 = path2[0];
  23108. }
  23109. vectlg = vertex2.subtract(vertex1).length();
  23110. dist = vectlg + vTotalDistance[i];
  23111. vTotalDistance[i] = dist;
  23112. }
  23113. }
  23114. // uvs
  23115. var u;
  23116. var v;
  23117. for (p = 0; p < pathArray.length; p++) {
  23118. for (i = 0; i < minlg + closePathCorr; i++) {
  23119. u = us[p][i] / uTotalDistance[p];
  23120. v = vs[i][p] / vTotalDistance[i];
  23121. uvs.push(u, v);
  23122. }
  23123. }
  23124. // indices
  23125. p = 0; // path index
  23126. var pi = 0; // positions array index
  23127. var l1 = lg[p] - 1; // path1 length
  23128. var l2 = lg[p + 1] - 1; // path2 length
  23129. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23130. var shft = idx[1] - idx[0]; // shift
  23131. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23132. while (pi <= min && p < path1nb) {
  23133. // 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
  23134. indices.push(pi, pi + shft, pi + 1);
  23135. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23136. pi += 1;
  23137. if (pi === min) {
  23138. p++;
  23139. if (p === lg.length - 1) {
  23140. shft = idx[0] - idx[p];
  23141. l1 = lg[p] - 1;
  23142. l2 = lg[0] - 1;
  23143. }
  23144. else {
  23145. shft = idx[p + 1] - idx[p];
  23146. l1 = lg[p] - 1;
  23147. l2 = lg[p + 1] - 1;
  23148. }
  23149. pi = idx[p];
  23150. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23151. }
  23152. }
  23153. // normals
  23154. VertexData.ComputeNormals(positions, indices, normals);
  23155. if (closePath) {
  23156. var indexFirst = 0;
  23157. var indexLast = 0;
  23158. for (p = 0; p < pathArray.length; p++) {
  23159. indexFirst = idx[p] * 3;
  23160. if (p + 1 < pathArray.length) {
  23161. indexLast = (idx[p + 1] - 1) * 3;
  23162. }
  23163. else {
  23164. indexLast = normals.length - 3;
  23165. }
  23166. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23167. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23168. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23169. normals[indexLast] = normals[indexFirst];
  23170. normals[indexLast + 1] = normals[indexFirst + 1];
  23171. normals[indexLast + 2] = normals[indexFirst + 2];
  23172. }
  23173. }
  23174. // sides
  23175. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23176. // Result
  23177. var vertexData = new VertexData();
  23178. vertexData.indices = indices;
  23179. vertexData.positions = positions;
  23180. vertexData.normals = normals;
  23181. vertexData.uvs = uvs;
  23182. if (closePath) {
  23183. vertexData._idx = idx;
  23184. }
  23185. return vertexData;
  23186. };
  23187. VertexData.CreateBox = function (options) {
  23188. var normalsSource = [
  23189. new BABYLON.Vector3(0, 0, 1),
  23190. new BABYLON.Vector3(0, 0, -1),
  23191. new BABYLON.Vector3(1, 0, 0),
  23192. new BABYLON.Vector3(-1, 0, 0),
  23193. new BABYLON.Vector3(0, 1, 0),
  23194. new BABYLON.Vector3(0, -1, 0)
  23195. ];
  23196. var indices = [];
  23197. var positions = [];
  23198. var normals = [];
  23199. var uvs = [];
  23200. var width = options.width || options.size || 1;
  23201. var height = options.height || options.size || 1;
  23202. var depth = options.depth || options.size || 1;
  23203. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23204. var faceUV = options.faceUV || new Array(6);
  23205. var faceColors = options.faceColors;
  23206. var colors = [];
  23207. // default face colors and UV if undefined
  23208. for (var f = 0; f < 6; f++) {
  23209. if (faceUV[f] === undefined) {
  23210. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23211. }
  23212. if (faceColors && faceColors[f] === undefined) {
  23213. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23214. }
  23215. }
  23216. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23217. // Create each face in turn.
  23218. for (var index = 0; index < normalsSource.length; index++) {
  23219. var normal = normalsSource[index];
  23220. // Get two vectors perpendicular to the face normal and to each other.
  23221. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23222. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23223. // Six indices (two triangles) per face.
  23224. var verticesLength = positions.length / 3;
  23225. indices.push(verticesLength);
  23226. indices.push(verticesLength + 1);
  23227. indices.push(verticesLength + 2);
  23228. indices.push(verticesLength);
  23229. indices.push(verticesLength + 2);
  23230. indices.push(verticesLength + 3);
  23231. // Four vertices per face.
  23232. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23233. positions.push(vertex.x, vertex.y, vertex.z);
  23234. normals.push(normal.x, normal.y, normal.z);
  23235. uvs.push(faceUV[index].z, faceUV[index].w);
  23236. if (faceColors) {
  23237. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23238. }
  23239. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23240. positions.push(vertex.x, vertex.y, vertex.z);
  23241. normals.push(normal.x, normal.y, normal.z);
  23242. uvs.push(faceUV[index].x, faceUV[index].w);
  23243. if (faceColors) {
  23244. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23245. }
  23246. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23247. positions.push(vertex.x, vertex.y, vertex.z);
  23248. normals.push(normal.x, normal.y, normal.z);
  23249. uvs.push(faceUV[index].x, faceUV[index].y);
  23250. if (faceColors) {
  23251. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23252. }
  23253. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23254. positions.push(vertex.x, vertex.y, vertex.z);
  23255. normals.push(normal.x, normal.y, normal.z);
  23256. uvs.push(faceUV[index].z, faceUV[index].y);
  23257. if (faceColors) {
  23258. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23259. }
  23260. }
  23261. // sides
  23262. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23263. // Result
  23264. var vertexData = new VertexData();
  23265. vertexData.indices = indices;
  23266. vertexData.positions = positions;
  23267. vertexData.normals = normals;
  23268. vertexData.uvs = uvs;
  23269. if (faceColors) {
  23270. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23271. vertexData.colors = totalColors;
  23272. }
  23273. return vertexData;
  23274. };
  23275. VertexData.CreateSphere = function (options) {
  23276. var segments = options.segments || 32;
  23277. var diameterX = options.diameterX || options.diameter || 1;
  23278. var diameterY = options.diameterY || options.diameter || 1;
  23279. var diameterZ = options.diameterZ || options.diameter || 1;
  23280. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  23281. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23282. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23283. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23284. var totalZRotationSteps = 2 + segments;
  23285. var totalYRotationSteps = 2 * totalZRotationSteps;
  23286. var indices = [];
  23287. var positions = [];
  23288. var normals = [];
  23289. var uvs = [];
  23290. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23291. var normalizedZ = zRotationStep / totalZRotationSteps;
  23292. var angleZ = normalizedZ * Math.PI * slice;
  23293. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23294. var normalizedY = yRotationStep / totalYRotationSteps;
  23295. var angleY = normalizedY * Math.PI * 2 * arc;
  23296. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23297. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23298. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23299. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23300. var vertex = complete.multiply(radius);
  23301. var normal = BABYLON.Vector3.Normalize(vertex);
  23302. positions.push(vertex.x, vertex.y, vertex.z);
  23303. normals.push(normal.x, normal.y, normal.z);
  23304. uvs.push(normalizedY, normalizedZ);
  23305. }
  23306. if (zRotationStep > 0) {
  23307. var verticesCount = positions.length / 3;
  23308. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23309. indices.push((firstIndex));
  23310. indices.push((firstIndex + 1));
  23311. indices.push(firstIndex + totalYRotationSteps + 1);
  23312. indices.push((firstIndex + totalYRotationSteps + 1));
  23313. indices.push((firstIndex + 1));
  23314. indices.push((firstIndex + totalYRotationSteps + 2));
  23315. }
  23316. }
  23317. }
  23318. // Sides
  23319. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23320. // Result
  23321. var vertexData = new VertexData();
  23322. vertexData.indices = indices;
  23323. vertexData.positions = positions;
  23324. vertexData.normals = normals;
  23325. vertexData.uvs = uvs;
  23326. return vertexData;
  23327. };
  23328. // Cylinder and cone
  23329. VertexData.CreateCylinder = function (options) {
  23330. var height = options.height || 2;
  23331. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23332. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23333. var tessellation = options.tessellation || 24;
  23334. var subdivisions = options.subdivisions || 1;
  23335. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  23336. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23337. var faceUV = options.faceUV || new Array(3);
  23338. var faceColors = options.faceColors;
  23339. // default face colors and UV if undefined
  23340. for (var f = 0; f < 3; f++) {
  23341. if (faceColors && faceColors[f] === undefined) {
  23342. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23343. }
  23344. if (faceUV && faceUV[f] === undefined) {
  23345. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23346. }
  23347. }
  23348. var indices = [];
  23349. var positions = [];
  23350. var normals = [];
  23351. var uvs = [];
  23352. var colors = [];
  23353. var angle_step = Math.PI * 2 * arc / tessellation;
  23354. var angle;
  23355. var h;
  23356. var radius;
  23357. var tan = (diameterBottom - diameterTop) / 2 / height;
  23358. var ringVertex = BABYLON.Vector3.Zero();
  23359. var ringNormal = BABYLON.Vector3.Zero();
  23360. // positions, normals, uvs
  23361. var i;
  23362. var j;
  23363. for (i = 0; i <= subdivisions; i++) {
  23364. h = i / subdivisions;
  23365. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23366. for (j = 0; j <= tessellation; j++) {
  23367. angle = j * angle_step;
  23368. ringVertex.x = Math.cos(-angle) * radius;
  23369. ringVertex.y = -height / 2 + h * height;
  23370. ringVertex.z = Math.sin(-angle) * radius;
  23371. if (diameterTop === 0 && i === subdivisions) {
  23372. // if no top cap, reuse former normals
  23373. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23374. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23375. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23376. }
  23377. else {
  23378. ringNormal.x = ringVertex.x;
  23379. ringNormal.z = ringVertex.z;
  23380. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23381. ringNormal.normalize();
  23382. }
  23383. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23384. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23385. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  23386. if (faceColors) {
  23387. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23388. }
  23389. }
  23390. }
  23391. // indices
  23392. for (i = 0; i < subdivisions; i++) {
  23393. for (j = 0; j < tessellation; j++) {
  23394. var i0 = i * (tessellation + 1) + j;
  23395. var i1 = (i + 1) * (tessellation + 1) + j;
  23396. var i2 = i * (tessellation + 1) + (j + 1);
  23397. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  23398. indices.push(i0, i1, i2);
  23399. indices.push(i3, i2, i1);
  23400. }
  23401. }
  23402. // Caps
  23403. var createCylinderCap = function (isTop) {
  23404. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23405. if (radius === 0) {
  23406. return;
  23407. }
  23408. // Cap positions, normals & uvs
  23409. var angle;
  23410. var circleVector;
  23411. var i;
  23412. var u = (isTop) ? faceUV[2] : faceUV[0];
  23413. var c;
  23414. if (faceColors) {
  23415. c = (isTop) ? faceColors[2] : faceColors[0];
  23416. }
  23417. // cap center
  23418. var vbase = positions.length / 3;
  23419. var offset = isTop ? height / 2 : -height / 2;
  23420. var center = new BABYLON.Vector3(0, offset, 0);
  23421. positions.push(center.x, center.y, center.z);
  23422. normals.push(0, isTop ? 1 : -1, 0);
  23423. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23424. if (faceColors) {
  23425. colors.push(c.r, c.g, c.b, c.a);
  23426. }
  23427. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23428. for (i = 0; i <= tessellation; i++) {
  23429. angle = Math.PI * 2 * i * arc / tessellation;
  23430. var cos = Math.cos(-angle);
  23431. var sin = Math.sin(-angle);
  23432. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23433. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23434. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23435. normals.push(0, isTop ? 1 : -1, 0);
  23436. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23437. if (faceColors) {
  23438. colors.push(c.r, c.g, c.b, c.a);
  23439. }
  23440. }
  23441. // Cap indices
  23442. for (i = 0; i < tessellation; i++) {
  23443. if (!isTop) {
  23444. indices.push(vbase);
  23445. indices.push(vbase + (i + 1));
  23446. indices.push(vbase + (i + 2));
  23447. }
  23448. else {
  23449. indices.push(vbase);
  23450. indices.push(vbase + (i + 2));
  23451. indices.push(vbase + (i + 1));
  23452. }
  23453. }
  23454. };
  23455. // add caps to geometry
  23456. createCylinderCap(false);
  23457. createCylinderCap(true);
  23458. // Sides
  23459. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23460. var vertexData = new VertexData();
  23461. vertexData.indices = indices;
  23462. vertexData.positions = positions;
  23463. vertexData.normals = normals;
  23464. vertexData.uvs = uvs;
  23465. if (faceColors) {
  23466. vertexData.colors = colors;
  23467. }
  23468. return vertexData;
  23469. };
  23470. VertexData.CreateTorus = function (options) {
  23471. var indices = [];
  23472. var positions = [];
  23473. var normals = [];
  23474. var uvs = [];
  23475. var diameter = options.diameter || 1;
  23476. var thickness = options.thickness || 0.5;
  23477. var tessellation = options.tessellation || 16;
  23478. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23479. var stride = tessellation + 1;
  23480. for (var i = 0; i <= tessellation; i++) {
  23481. var u = i / tessellation;
  23482. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23483. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23484. for (var j = 0; j <= tessellation; j++) {
  23485. var v = 1 - j / tessellation;
  23486. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23487. var dx = Math.cos(innerAngle);
  23488. var dy = Math.sin(innerAngle);
  23489. // Create a vertex.
  23490. var normal = new BABYLON.Vector3(dx, dy, 0);
  23491. var position = normal.scale(thickness / 2);
  23492. var textureCoordinate = new BABYLON.Vector2(u, v);
  23493. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23494. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23495. positions.push(position.x, position.y, position.z);
  23496. normals.push(normal.x, normal.y, normal.z);
  23497. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23498. // And create indices for two triangles.
  23499. var nextI = (i + 1) % stride;
  23500. var nextJ = (j + 1) % stride;
  23501. indices.push(i * stride + j);
  23502. indices.push(i * stride + nextJ);
  23503. indices.push(nextI * stride + j);
  23504. indices.push(i * stride + nextJ);
  23505. indices.push(nextI * stride + nextJ);
  23506. indices.push(nextI * stride + j);
  23507. }
  23508. }
  23509. // Sides
  23510. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23511. // Result
  23512. var vertexData = new VertexData();
  23513. vertexData.indices = indices;
  23514. vertexData.positions = positions;
  23515. vertexData.normals = normals;
  23516. vertexData.uvs = uvs;
  23517. return vertexData;
  23518. };
  23519. VertexData.CreateLines = function (options) {
  23520. var indices = [];
  23521. var positions = [];
  23522. var points = options.points;
  23523. for (var index = 0; index < points.length; index++) {
  23524. positions.push(points[index].x, points[index].y, points[index].z);
  23525. if (index > 0) {
  23526. indices.push(index - 1);
  23527. indices.push(index);
  23528. }
  23529. }
  23530. // Result
  23531. var vertexData = new VertexData();
  23532. vertexData.indices = indices;
  23533. vertexData.positions = positions;
  23534. return vertexData;
  23535. };
  23536. VertexData.CreateDashedLines = function (options) {
  23537. var dashSize = options.dashSize || 3;
  23538. var gapSize = options.gapSize || 1;
  23539. var dashNb = options.dashNb || 200;
  23540. var points = options.points;
  23541. var positions = new Array();
  23542. var indices = new Array();
  23543. var curvect = BABYLON.Vector3.Zero();
  23544. var lg = 0;
  23545. var nb = 0;
  23546. var shft = 0;
  23547. var dashshft = 0;
  23548. var curshft = 0;
  23549. var idx = 0;
  23550. var i = 0;
  23551. for (i = 0; i < points.length - 1; i++) {
  23552. points[i + 1].subtractToRef(points[i], curvect);
  23553. lg += curvect.length();
  23554. }
  23555. shft = lg / dashNb;
  23556. dashshft = dashSize * shft / (dashSize + gapSize);
  23557. for (i = 0; i < points.length - 1; i++) {
  23558. points[i + 1].subtractToRef(points[i], curvect);
  23559. nb = Math.floor(curvect.length() / shft);
  23560. curvect.normalize();
  23561. for (var j = 0; j < nb; j++) {
  23562. curshft = shft * j;
  23563. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23564. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23565. indices.push(idx, idx + 1);
  23566. idx += 2;
  23567. }
  23568. }
  23569. // Result
  23570. var vertexData = new VertexData();
  23571. vertexData.positions = positions;
  23572. vertexData.indices = indices;
  23573. return vertexData;
  23574. };
  23575. VertexData.CreateGround = function (options) {
  23576. var indices = [];
  23577. var positions = [];
  23578. var normals = [];
  23579. var uvs = [];
  23580. var row, col;
  23581. var width = options.width || 1;
  23582. var height = options.height || 1;
  23583. var subdivisions = options.subdivisions || 1;
  23584. for (row = 0; row <= subdivisions; row++) {
  23585. for (col = 0; col <= subdivisions; col++) {
  23586. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23587. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23588. positions.push(position.x, position.y, position.z);
  23589. normals.push(normal.x, normal.y, normal.z);
  23590. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23591. }
  23592. }
  23593. for (row = 0; row < subdivisions; row++) {
  23594. for (col = 0; col < subdivisions; col++) {
  23595. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23596. indices.push(col + 1 + row * (subdivisions + 1));
  23597. indices.push(col + row * (subdivisions + 1));
  23598. indices.push(col + (row + 1) * (subdivisions + 1));
  23599. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23600. indices.push(col + row * (subdivisions + 1));
  23601. }
  23602. }
  23603. // Result
  23604. var vertexData = new VertexData();
  23605. vertexData.indices = indices;
  23606. vertexData.positions = positions;
  23607. vertexData.normals = normals;
  23608. vertexData.uvs = uvs;
  23609. return vertexData;
  23610. };
  23611. VertexData.CreateTiledGround = function (options) {
  23612. var xmin = options.xmin;
  23613. var zmin = options.zmin;
  23614. var xmax = options.xmax;
  23615. var zmax = options.zmax;
  23616. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23617. var precision = options.precision || { w: 1, h: 1 };
  23618. var indices = [];
  23619. var positions = [];
  23620. var normals = [];
  23621. var uvs = [];
  23622. var row, col, tileRow, tileCol;
  23623. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23624. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23625. precision.w = (precision.w < 1) ? 1 : precision.w;
  23626. precision.h = (precision.h < 1) ? 1 : precision.h;
  23627. var tileSize = {
  23628. 'w': (xmax - xmin) / subdivisions.w,
  23629. 'h': (zmax - zmin) / subdivisions.h
  23630. };
  23631. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23632. // Indices
  23633. var base = positions.length / 3;
  23634. var rowLength = precision.w + 1;
  23635. for (row = 0; row < precision.h; row++) {
  23636. for (col = 0; col < precision.w; col++) {
  23637. var square = [
  23638. base + col + row * rowLength,
  23639. base + (col + 1) + row * rowLength,
  23640. base + (col + 1) + (row + 1) * rowLength,
  23641. base + col + (row + 1) * rowLength
  23642. ];
  23643. indices.push(square[1]);
  23644. indices.push(square[2]);
  23645. indices.push(square[3]);
  23646. indices.push(square[0]);
  23647. indices.push(square[1]);
  23648. indices.push(square[3]);
  23649. }
  23650. }
  23651. // Position, normals and uvs
  23652. var position = BABYLON.Vector3.Zero();
  23653. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23654. for (row = 0; row <= precision.h; row++) {
  23655. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23656. for (col = 0; col <= precision.w; col++) {
  23657. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23658. position.y = 0;
  23659. positions.push(position.x, position.y, position.z);
  23660. normals.push(normal.x, normal.y, normal.z);
  23661. uvs.push(col / precision.w, row / precision.h);
  23662. }
  23663. }
  23664. }
  23665. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23666. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23667. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23668. }
  23669. }
  23670. // Result
  23671. var vertexData = new VertexData();
  23672. vertexData.indices = indices;
  23673. vertexData.positions = positions;
  23674. vertexData.normals = normals;
  23675. vertexData.uvs = uvs;
  23676. return vertexData;
  23677. };
  23678. VertexData.CreateGroundFromHeightMap = function (options) {
  23679. var indices = [];
  23680. var positions = [];
  23681. var normals = [];
  23682. var uvs = [];
  23683. var row, col;
  23684. // Vertices
  23685. for (row = 0; row <= options.subdivisions; row++) {
  23686. for (col = 0; col <= options.subdivisions; col++) {
  23687. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  23688. // Compute height
  23689. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23690. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23691. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23692. var r = options.buffer[pos] / 255.0;
  23693. var g = options.buffer[pos + 1] / 255.0;
  23694. var b = options.buffer[pos + 2] / 255.0;
  23695. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23696. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23697. // Add vertex
  23698. positions.push(position.x, position.y, position.z);
  23699. normals.push(0, 0, 0);
  23700. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23701. }
  23702. }
  23703. // Indices
  23704. for (row = 0; row < options.subdivisions; row++) {
  23705. for (col = 0; col < options.subdivisions; col++) {
  23706. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23707. indices.push(col + 1 + row * (options.subdivisions + 1));
  23708. indices.push(col + row * (options.subdivisions + 1));
  23709. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23710. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23711. indices.push(col + row * (options.subdivisions + 1));
  23712. }
  23713. }
  23714. // Normals
  23715. VertexData.ComputeNormals(positions, indices, normals);
  23716. // Result
  23717. var vertexData = new VertexData();
  23718. vertexData.indices = indices;
  23719. vertexData.positions = positions;
  23720. vertexData.normals = normals;
  23721. vertexData.uvs = uvs;
  23722. return vertexData;
  23723. };
  23724. VertexData.CreatePlane = function (options) {
  23725. var indices = [];
  23726. var positions = [];
  23727. var normals = [];
  23728. var uvs = [];
  23729. var width = options.width || options.size || 1;
  23730. var height = options.height || options.size || 1;
  23731. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23732. // Vertices
  23733. var halfWidth = width / 2.0;
  23734. var halfHeight = height / 2.0;
  23735. positions.push(-halfWidth, -halfHeight, 0);
  23736. normals.push(0, 0, -1.0);
  23737. uvs.push(0.0, 0.0);
  23738. positions.push(halfWidth, -halfHeight, 0);
  23739. normals.push(0, 0, -1.0);
  23740. uvs.push(1.0, 0.0);
  23741. positions.push(halfWidth, halfHeight, 0);
  23742. normals.push(0, 0, -1.0);
  23743. uvs.push(1.0, 1.0);
  23744. positions.push(-halfWidth, halfHeight, 0);
  23745. normals.push(0, 0, -1.0);
  23746. uvs.push(0.0, 1.0);
  23747. // Indices
  23748. indices.push(0);
  23749. indices.push(1);
  23750. indices.push(2);
  23751. indices.push(0);
  23752. indices.push(2);
  23753. indices.push(3);
  23754. // Sides
  23755. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23756. // Result
  23757. var vertexData = new VertexData();
  23758. vertexData.indices = indices;
  23759. vertexData.positions = positions;
  23760. vertexData.normals = normals;
  23761. vertexData.uvs = uvs;
  23762. return vertexData;
  23763. };
  23764. VertexData.CreateDisc = function (options) {
  23765. var positions = [];
  23766. var indices = [];
  23767. var normals = [];
  23768. var uvs = [];
  23769. var radius = options.radius || 0.5;
  23770. var tessellation = options.tessellation || 64;
  23771. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23772. // positions and uvs
  23773. positions.push(0, 0, 0); // disc center first
  23774. uvs.push(0.5, 0.5);
  23775. var step = Math.PI * 2 / tessellation;
  23776. for (var a = 0; a < Math.PI * 2; a += step) {
  23777. var x = Math.cos(a);
  23778. var y = Math.sin(a);
  23779. var u = (x + 1) / 2;
  23780. var v = (1 - y) / 2;
  23781. positions.push(radius * x, radius * y, 0);
  23782. uvs.push(u, v);
  23783. }
  23784. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23785. uvs.push(uvs[2], uvs[3]);
  23786. //indices
  23787. var vertexNb = positions.length / 3;
  23788. for (var i = 1; i < vertexNb - 1; i++) {
  23789. indices.push(i + 1, 0, i);
  23790. }
  23791. // result
  23792. VertexData.ComputeNormals(positions, indices, normals);
  23793. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23794. var vertexData = new VertexData();
  23795. vertexData.indices = indices;
  23796. vertexData.positions = positions;
  23797. vertexData.normals = normals;
  23798. vertexData.uvs = uvs;
  23799. return vertexData;
  23800. };
  23801. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  23802. VertexData.CreatePolyhedron = function (options) {
  23803. // provided polyhedron types :
  23804. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  23805. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  23806. var polyhedra = [];
  23807. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  23808. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  23809. polyhedra[2] = {
  23810. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  23811. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  23812. };
  23813. polyhedra[3] = {
  23814. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  23815. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  23816. };
  23817. polyhedra[4] = {
  23818. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  23819. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  23820. };
  23821. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  23822. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  23823. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  23824. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  23825. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  23826. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  23827. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  23828. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  23829. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  23830. polyhedra[14] = {
  23831. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  23832. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  23833. };
  23834. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  23835. var size = options.size;
  23836. var sizeX = options.sizeX || size || 1;
  23837. var sizeY = options.sizeY || size || 1;
  23838. var sizeZ = options.sizeZ || size || 1;
  23839. var data = options.custom || polyhedra[type];
  23840. var nbfaces = data.face.length;
  23841. var faceUV = options.faceUV || new Array(nbfaces);
  23842. var faceColors = options.faceColors;
  23843. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23844. var positions = [];
  23845. var indices = [];
  23846. var normals = [];
  23847. var uvs = [];
  23848. var colors = [];
  23849. var index = 0;
  23850. var faceIdx = 0; // face cursor in the array "indexes"
  23851. var indexes = [];
  23852. var i = 0;
  23853. var f = 0;
  23854. var u, v, ang, x, y, tmp;
  23855. // default face colors and UV if undefined
  23856. for (f = 0; f < nbfaces; f++) {
  23857. if (faceColors && faceColors[f] === undefined) {
  23858. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23859. }
  23860. if (faceUV && faceUV[f] === undefined) {
  23861. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23862. }
  23863. }
  23864. for (f = 0; f < nbfaces; f++) {
  23865. var fl = data.face[f].length; // number of vertices of the current face
  23866. ang = 2 * Math.PI / fl;
  23867. x = 0.5 * Math.tan(ang / 2);
  23868. y = 0.5;
  23869. // positions, uvs, colors
  23870. for (i = 0; i < fl; i++) {
  23871. // positions
  23872. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  23873. indexes.push(index);
  23874. index++;
  23875. // uvs
  23876. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  23877. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  23878. uvs.push(u, v);
  23879. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  23880. y = x * Math.sin(ang) + y * Math.cos(ang);
  23881. x = tmp;
  23882. // colors
  23883. if (faceColors) {
  23884. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  23885. }
  23886. }
  23887. // indices from indexes
  23888. for (i = 0; i < fl - 2; i++) {
  23889. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  23890. }
  23891. faceIdx += fl;
  23892. }
  23893. VertexData.ComputeNormals(positions, indices, normals);
  23894. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23895. var vertexData = new VertexData();
  23896. vertexData.positions = positions;
  23897. vertexData.indices = indices;
  23898. vertexData.normals = normals;
  23899. vertexData.uvs = uvs;
  23900. if (faceColors) {
  23901. vertexData.colors = colors;
  23902. }
  23903. return vertexData;
  23904. };
  23905. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  23906. VertexData.CreateTorusKnot = function (options) {
  23907. var indices = [];
  23908. var positions = [];
  23909. var normals = [];
  23910. var uvs = [];
  23911. var radius = options.radius || 2;
  23912. var tube = options.tube || 0.5;
  23913. var radialSegments = options.radialSegments || 32;
  23914. var tubularSegments = options.tubularSegments || 32;
  23915. var p = options.p || 2;
  23916. var q = options.q || 3;
  23917. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23918. // Helper
  23919. var getPos = function (angle) {
  23920. var cu = Math.cos(angle);
  23921. var su = Math.sin(angle);
  23922. var quOverP = q / p * angle;
  23923. var cs = Math.cos(quOverP);
  23924. var tx = radius * (2 + cs) * 0.5 * cu;
  23925. var ty = radius * (2 + cs) * su * 0.5;
  23926. var tz = radius * Math.sin(quOverP) * 0.5;
  23927. return new BABYLON.Vector3(tx, ty, tz);
  23928. };
  23929. // Vertices
  23930. var i;
  23931. var j;
  23932. for (i = 0; i <= radialSegments; i++) {
  23933. var modI = i % radialSegments;
  23934. var u = modI / radialSegments * 2 * p * Math.PI;
  23935. var p1 = getPos(u);
  23936. var p2 = getPos(u + 0.01);
  23937. var tang = p2.subtract(p1);
  23938. var n = p2.add(p1);
  23939. var bitan = BABYLON.Vector3.Cross(tang, n);
  23940. n = BABYLON.Vector3.Cross(bitan, tang);
  23941. bitan.normalize();
  23942. n.normalize();
  23943. for (j = 0; j < tubularSegments; j++) {
  23944. var modJ = j % tubularSegments;
  23945. var v = modJ / tubularSegments * 2 * Math.PI;
  23946. var cx = -tube * Math.cos(v);
  23947. var cy = tube * Math.sin(v);
  23948. positions.push(p1.x + cx * n.x + cy * bitan.x);
  23949. positions.push(p1.y + cx * n.y + cy * bitan.y);
  23950. positions.push(p1.z + cx * n.z + cy * bitan.z);
  23951. uvs.push(i / radialSegments);
  23952. uvs.push(j / tubularSegments);
  23953. }
  23954. }
  23955. for (i = 0; i < radialSegments; i++) {
  23956. for (j = 0; j < tubularSegments; j++) {
  23957. var jNext = (j + 1) % tubularSegments;
  23958. var a = i * tubularSegments + j;
  23959. var b = (i + 1) * tubularSegments + j;
  23960. var c = (i + 1) * tubularSegments + jNext;
  23961. var d = i * tubularSegments + jNext;
  23962. indices.push(d);
  23963. indices.push(b);
  23964. indices.push(a);
  23965. indices.push(d);
  23966. indices.push(c);
  23967. indices.push(b);
  23968. }
  23969. }
  23970. // Normals
  23971. VertexData.ComputeNormals(positions, indices, normals);
  23972. // Sides
  23973. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23974. // Result
  23975. var vertexData = new VertexData();
  23976. vertexData.indices = indices;
  23977. vertexData.positions = positions;
  23978. vertexData.normals = normals;
  23979. vertexData.uvs = uvs;
  23980. return vertexData;
  23981. };
  23982. // Tools
  23983. /**
  23984. * @param {any} - positions (number[] or Float32Array)
  23985. * @param {any} - indices (number[] or Uint16Array)
  23986. * @param {any} - normals (number[] or Float32Array)
  23987. */
  23988. VertexData.ComputeNormals = function (positions, indices, normals) {
  23989. var index = 0;
  23990. // temp Vector3
  23991. var p1p2 = BABYLON.Vector3.Zero();
  23992. var p3p2 = BABYLON.Vector3.Zero();
  23993. var faceNormal = BABYLON.Vector3.Zero();
  23994. var vertexNormali1 = BABYLON.Vector3.Zero();
  23995. for (index = 0; index < positions.length; index++) {
  23996. normals[index] = 0.0;
  23997. }
  23998. // indice triplet = 1 face
  23999. var nbFaces = indices.length / 3;
  24000. for (index = 0; index < nbFaces; index++) {
  24001. var i1 = indices[index * 3];
  24002. var i2 = indices[index * 3 + 1];
  24003. var i3 = indices[index * 3 + 2];
  24004. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  24005. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24006. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24007. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  24008. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24009. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24010. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24011. faceNormal.normalize();
  24012. normals[i1 * 3] += faceNormal.x;
  24013. normals[i1 * 3 + 1] += faceNormal.y;
  24014. normals[i1 * 3 + 2] += faceNormal.z;
  24015. normals[i2 * 3] += faceNormal.x;
  24016. normals[i2 * 3 + 1] += faceNormal.y;
  24017. normals[i2 * 3 + 2] += faceNormal.z;
  24018. normals[i3 * 3] += faceNormal.x;
  24019. normals[i3 * 3 + 1] += faceNormal.y;
  24020. normals[i3 * 3 + 2] += faceNormal.z;
  24021. }
  24022. // last normalization
  24023. for (index = 0; index < normals.length / 3; index++) {
  24024. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24025. vertexNormali1.normalize();
  24026. normals[index * 3] = vertexNormali1.x;
  24027. normals[index * 3 + 1] = vertexNormali1.y;
  24028. normals[index * 3 + 2] = vertexNormali1.z;
  24029. }
  24030. };
  24031. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24032. var li = indices.length;
  24033. var ln = normals.length;
  24034. var i;
  24035. var n;
  24036. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24037. switch (sideOrientation) {
  24038. case BABYLON.Mesh.FRONTSIDE:
  24039. // nothing changed
  24040. break;
  24041. case BABYLON.Mesh.BACKSIDE:
  24042. var tmp;
  24043. // indices
  24044. for (i = 0; i < li; i += 3) {
  24045. tmp = indices[i];
  24046. indices[i] = indices[i + 2];
  24047. indices[i + 2] = tmp;
  24048. }
  24049. // normals
  24050. for (n = 0; n < ln; n++) {
  24051. normals[n] = -normals[n];
  24052. }
  24053. break;
  24054. case BABYLON.Mesh.DOUBLESIDE:
  24055. // positions
  24056. var lp = positions.length;
  24057. var l = lp / 3;
  24058. for (var p = 0; p < lp; p++) {
  24059. positions[lp + p] = positions[p];
  24060. }
  24061. // indices
  24062. for (i = 0; i < li; i += 3) {
  24063. indices[i + li] = indices[i + 2] + l;
  24064. indices[i + 1 + li] = indices[i + 1] + l;
  24065. indices[i + 2 + li] = indices[i] + l;
  24066. }
  24067. // normals
  24068. for (n = 0; n < ln; n++) {
  24069. normals[ln + n] = -normals[n];
  24070. }
  24071. // uvs
  24072. var lu = uvs.length;
  24073. for (var u = 0; u < lu; u++) {
  24074. uvs[u + lu] = uvs[u];
  24075. }
  24076. break;
  24077. }
  24078. };
  24079. return VertexData;
  24080. })();
  24081. BABYLON.VertexData = VertexData;
  24082. })(BABYLON || (BABYLON = {}));
  24083. var BABYLON;
  24084. (function (BABYLON) {
  24085. var Tags = (function () {
  24086. function Tags() {
  24087. }
  24088. Tags.EnableFor = function (obj) {
  24089. obj._tags = obj._tags || {};
  24090. obj.hasTags = function () {
  24091. return Tags.HasTags(obj);
  24092. };
  24093. obj.addTags = function (tagsString) {
  24094. return Tags.AddTagsTo(obj, tagsString);
  24095. };
  24096. obj.removeTags = function (tagsString) {
  24097. return Tags.RemoveTagsFrom(obj, tagsString);
  24098. };
  24099. obj.matchesTagsQuery = function (tagsQuery) {
  24100. return Tags.MatchesQuery(obj, tagsQuery);
  24101. };
  24102. };
  24103. Tags.DisableFor = function (obj) {
  24104. delete obj._tags;
  24105. delete obj.hasTags;
  24106. delete obj.addTags;
  24107. delete obj.removeTags;
  24108. delete obj.matchesTagsQuery;
  24109. };
  24110. Tags.HasTags = function (obj) {
  24111. if (!obj._tags) {
  24112. return false;
  24113. }
  24114. return !BABYLON.Tools.IsEmpty(obj._tags);
  24115. };
  24116. Tags.GetTags = function (obj) {
  24117. if (!obj._tags) {
  24118. return null;
  24119. }
  24120. return obj._tags;
  24121. };
  24122. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24123. // a tag cannot start with '||', '&&', and '!'
  24124. // it cannot contain whitespaces
  24125. Tags.AddTagsTo = function (obj, tagsString) {
  24126. if (!tagsString) {
  24127. return;
  24128. }
  24129. var tags = tagsString.split(" ");
  24130. for (var t in tags) {
  24131. Tags._AddTagTo(obj, tags[t]);
  24132. }
  24133. };
  24134. Tags._AddTagTo = function (obj, tag) {
  24135. tag = tag.trim();
  24136. if (tag === "" || tag === "true" || tag === "false") {
  24137. return;
  24138. }
  24139. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24140. return;
  24141. }
  24142. Tags.EnableFor(obj);
  24143. obj._tags[tag] = true;
  24144. };
  24145. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24146. if (!Tags.HasTags(obj)) {
  24147. return;
  24148. }
  24149. var tags = tagsString.split(" ");
  24150. for (var t in tags) {
  24151. Tags._RemoveTagFrom(obj, tags[t]);
  24152. }
  24153. };
  24154. Tags._RemoveTagFrom = function (obj, tag) {
  24155. delete obj._tags[tag];
  24156. };
  24157. Tags.MatchesQuery = function (obj, tagsQuery) {
  24158. if (tagsQuery === undefined) {
  24159. return true;
  24160. }
  24161. if (tagsQuery === "") {
  24162. return Tags.HasTags(obj);
  24163. }
  24164. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24165. };
  24166. return Tags;
  24167. })();
  24168. BABYLON.Tags = Tags;
  24169. })(BABYLON || (BABYLON = {}));
  24170. var BABYLON;
  24171. (function (BABYLON) {
  24172. var Internals;
  24173. (function (Internals) {
  24174. var AndOrNotEvaluator = (function () {
  24175. function AndOrNotEvaluator() {
  24176. }
  24177. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24178. if (!query.match(/\([^\(\)]*\)/g)) {
  24179. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24180. }
  24181. else {
  24182. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24183. // remove parenthesis
  24184. r = r.slice(1, r.length - 1);
  24185. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24186. });
  24187. }
  24188. if (query === "true") {
  24189. return true;
  24190. }
  24191. if (query === "false") {
  24192. return false;
  24193. }
  24194. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24195. };
  24196. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24197. evaluateCallback = evaluateCallback || (function (r) {
  24198. return r === "true" ? true : false;
  24199. });
  24200. var result;
  24201. var or = parenthesisContent.split("||");
  24202. for (var i in or) {
  24203. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24204. var and = ori.split("&&");
  24205. if (and.length > 1) {
  24206. for (var j = 0; j < and.length; ++j) {
  24207. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24208. if (andj !== "true" && andj !== "false") {
  24209. if (andj[0] === "!") {
  24210. result = !evaluateCallback(andj.substring(1));
  24211. }
  24212. else {
  24213. result = evaluateCallback(andj);
  24214. }
  24215. }
  24216. else {
  24217. result = andj === "true" ? true : false;
  24218. }
  24219. if (!result) {
  24220. ori = "false";
  24221. break;
  24222. }
  24223. }
  24224. }
  24225. if (result || ori === "true") {
  24226. result = true;
  24227. break;
  24228. }
  24229. // result equals false (or undefined)
  24230. if (ori !== "true" && ori !== "false") {
  24231. if (ori[0] === "!") {
  24232. result = !evaluateCallback(ori.substring(1));
  24233. }
  24234. else {
  24235. result = evaluateCallback(ori);
  24236. }
  24237. }
  24238. else {
  24239. result = ori === "true" ? true : false;
  24240. }
  24241. }
  24242. // the whole parenthesis scope is replaced by 'true' or 'false'
  24243. return result ? "true" : "false";
  24244. };
  24245. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24246. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24247. // remove whitespaces
  24248. r = r.replace(/[\s]/g, function () { return ""; });
  24249. return r.length % 2 ? "!" : "";
  24250. });
  24251. booleanString = booleanString.trim();
  24252. if (booleanString === "!true") {
  24253. booleanString = "false";
  24254. }
  24255. else if (booleanString === "!false") {
  24256. booleanString = "true";
  24257. }
  24258. return booleanString;
  24259. };
  24260. return AndOrNotEvaluator;
  24261. })();
  24262. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24263. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24264. })(BABYLON || (BABYLON = {}));
  24265. var BABYLON;
  24266. (function (BABYLON) {
  24267. var PostProcessRenderPass = (function () {
  24268. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24269. this._enabled = true;
  24270. this._refCount = 0;
  24271. this._name = name;
  24272. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24273. this.setRenderList(renderList);
  24274. this._renderTexture.onBeforeRender = beforeRender;
  24275. this._renderTexture.onAfterRender = afterRender;
  24276. this._scene = scene;
  24277. this._renderList = renderList;
  24278. }
  24279. // private
  24280. PostProcessRenderPass.prototype._incRefCount = function () {
  24281. if (this._refCount === 0) {
  24282. this._scene.customRenderTargets.push(this._renderTexture);
  24283. }
  24284. return ++this._refCount;
  24285. };
  24286. PostProcessRenderPass.prototype._decRefCount = function () {
  24287. this._refCount--;
  24288. if (this._refCount <= 0) {
  24289. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24290. }
  24291. return this._refCount;
  24292. };
  24293. PostProcessRenderPass.prototype._update = function () {
  24294. this.setRenderList(this._renderList);
  24295. };
  24296. // public
  24297. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24298. this._renderTexture.renderList = renderList;
  24299. };
  24300. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24301. return this._renderTexture;
  24302. };
  24303. return PostProcessRenderPass;
  24304. })();
  24305. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24306. })(BABYLON || (BABYLON = {}));
  24307. var BABYLON;
  24308. (function (BABYLON) {
  24309. var PostProcessRenderEffect = (function () {
  24310. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24311. this._engine = engine;
  24312. this._name = name;
  24313. this._singleInstance = singleInstance || true;
  24314. this._getPostProcess = getPostProcess;
  24315. this._cameras = [];
  24316. this._indicesForCamera = [];
  24317. this._postProcesses = {};
  24318. this._renderPasses = {};
  24319. this._renderEffectAsPasses = {};
  24320. }
  24321. PostProcessRenderEffect.prototype._update = function () {
  24322. for (var renderPassName in this._renderPasses) {
  24323. this._renderPasses[renderPassName]._update();
  24324. }
  24325. };
  24326. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24327. this._renderPasses[renderPass._name] = renderPass;
  24328. this._linkParameters();
  24329. };
  24330. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24331. delete this._renderPasses[renderPass._name];
  24332. this._linkParameters();
  24333. };
  24334. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24335. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24336. this._linkParameters();
  24337. };
  24338. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24339. for (var renderPassName in this._renderPasses) {
  24340. if (renderPassName === passName) {
  24341. return this._renderPasses[passName];
  24342. }
  24343. }
  24344. };
  24345. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24346. this._renderPasses = {};
  24347. this._linkParameters();
  24348. };
  24349. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24350. var cameraKey;
  24351. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24352. for (var i = 0; i < _cam.length; i++) {
  24353. var camera = _cam[i];
  24354. var cameraName = camera.name;
  24355. if (this._singleInstance) {
  24356. cameraKey = 0;
  24357. }
  24358. else {
  24359. cameraKey = cameraName;
  24360. }
  24361. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24362. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24363. if (!this._indicesForCamera[cameraName]) {
  24364. this._indicesForCamera[cameraName] = [];
  24365. }
  24366. this._indicesForCamera[cameraName].push(index);
  24367. if (this._cameras.indexOf(camera) === -1) {
  24368. this._cameras[cameraName] = camera;
  24369. }
  24370. for (var passName in this._renderPasses) {
  24371. this._renderPasses[passName]._incRefCount();
  24372. }
  24373. }
  24374. this._linkParameters();
  24375. };
  24376. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24377. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24378. for (var i = 0; i < _cam.length; i++) {
  24379. var camera = _cam[i];
  24380. var cameraName = camera.name;
  24381. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24382. var index = this._cameras.indexOf(cameraName);
  24383. this._indicesForCamera.splice(index, 1);
  24384. this._cameras.splice(index, 1);
  24385. for (var passName in this._renderPasses) {
  24386. this._renderPasses[passName]._decRefCount();
  24387. }
  24388. }
  24389. };
  24390. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24391. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24392. for (var i = 0; i < _cam.length; i++) {
  24393. var camera = _cam[i];
  24394. var cameraName = camera.name;
  24395. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24396. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24397. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24398. }
  24399. }
  24400. for (var passName in this._renderPasses) {
  24401. this._renderPasses[passName]._incRefCount();
  24402. }
  24403. }
  24404. };
  24405. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24406. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24407. for (var i = 0; i < _cam.length; i++) {
  24408. var camera = _cam[i];
  24409. var cameraName = camera.Name;
  24410. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24411. for (var passName in this._renderPasses) {
  24412. this._renderPasses[passName]._decRefCount();
  24413. }
  24414. }
  24415. };
  24416. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24417. if (this._singleInstance) {
  24418. return this._postProcesses[0];
  24419. }
  24420. else {
  24421. return this._postProcesses[camera.name];
  24422. }
  24423. };
  24424. PostProcessRenderEffect.prototype._linkParameters = function () {
  24425. var _this = this;
  24426. for (var index in this._postProcesses) {
  24427. if (this.applyParameters) {
  24428. this.applyParameters(this._postProcesses[index]);
  24429. }
  24430. this._postProcesses[index].onBeforeRender = function (effect) {
  24431. _this._linkTextures(effect);
  24432. };
  24433. }
  24434. };
  24435. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24436. for (var renderPassName in this._renderPasses) {
  24437. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24438. }
  24439. for (var renderEffectName in this._renderEffectAsPasses) {
  24440. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24441. }
  24442. };
  24443. return PostProcessRenderEffect;
  24444. })();
  24445. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24446. })(BABYLON || (BABYLON = {}));
  24447. var BABYLON;
  24448. (function (BABYLON) {
  24449. var PostProcessRenderPipeline = (function () {
  24450. function PostProcessRenderPipeline(engine, name) {
  24451. this._engine = engine;
  24452. this._name = name;
  24453. this._renderEffects = {};
  24454. this._renderEffectsForIsolatedPass = {};
  24455. this._cameras = [];
  24456. }
  24457. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24458. this._renderEffects[renderEffect._name] = renderEffect;
  24459. };
  24460. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24461. var renderEffects = this._renderEffects[renderEffectName];
  24462. if (!renderEffects) {
  24463. return;
  24464. }
  24465. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24466. };
  24467. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24468. var renderEffects = this._renderEffects[renderEffectName];
  24469. if (!renderEffects) {
  24470. return;
  24471. }
  24472. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24473. };
  24474. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24475. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24476. var indicesToDelete = [];
  24477. for (var i = 0; i < _cam.length; i++) {
  24478. var camera = _cam[i];
  24479. var cameraName = camera.name;
  24480. if (this._cameras.indexOf(camera) === -1) {
  24481. this._cameras[cameraName] = camera;
  24482. }
  24483. else if (unique) {
  24484. indicesToDelete.push(i);
  24485. }
  24486. }
  24487. for (var i = 0; i < indicesToDelete.length; i++) {
  24488. cameras.splice(indicesToDelete[i], 1);
  24489. }
  24490. for (var renderEffectName in this._renderEffects) {
  24491. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24492. }
  24493. };
  24494. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24495. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24496. for (var renderEffectName in this._renderEffects) {
  24497. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24498. }
  24499. for (var i = 0; i < _cam.length; i++) {
  24500. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24501. }
  24502. };
  24503. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24504. var _this = this;
  24505. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24506. var pass = null;
  24507. for (var renderEffectName in this._renderEffects) {
  24508. pass = this._renderEffects[renderEffectName].getPass(passName);
  24509. if (pass != null) {
  24510. break;
  24511. }
  24512. }
  24513. if (pass === null) {
  24514. return;
  24515. }
  24516. for (var renderEffectName in this._renderEffects) {
  24517. this._renderEffects[renderEffectName]._disable(_cam);
  24518. }
  24519. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24520. for (var i = 0; i < _cam.length; i++) {
  24521. var camera = _cam[i];
  24522. var cameraName = camera.name;
  24523. 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); });
  24524. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24525. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24526. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24527. }
  24528. };
  24529. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24530. var _this = this;
  24531. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24532. for (var i = 0; i < _cam.length; i++) {
  24533. var camera = _cam[i];
  24534. var cameraName = camera.name;
  24535. 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); });
  24536. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24537. }
  24538. for (var renderEffectName in this._renderEffects) {
  24539. this._renderEffects[renderEffectName]._enable(_cam);
  24540. }
  24541. };
  24542. PostProcessRenderPipeline.prototype._update = function () {
  24543. for (var renderEffectName in this._renderEffects) {
  24544. this._renderEffects[renderEffectName]._update();
  24545. }
  24546. for (var i = 0; i < this._cameras.length; i++) {
  24547. var cameraName = this._cameras[i].name;
  24548. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24549. this._renderEffectsForIsolatedPass[cameraName]._update();
  24550. }
  24551. }
  24552. };
  24553. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24554. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24555. return PostProcessRenderPipeline;
  24556. })();
  24557. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24558. })(BABYLON || (BABYLON = {}));
  24559. var BABYLON;
  24560. (function (BABYLON) {
  24561. var PostProcessRenderPipelineManager = (function () {
  24562. function PostProcessRenderPipelineManager() {
  24563. this._renderPipelines = {};
  24564. }
  24565. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  24566. this._renderPipelines[renderPipeline._name] = renderPipeline;
  24567. };
  24568. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  24569. var renderPipeline = this._renderPipelines[renderPipelineName];
  24570. if (!renderPipeline) {
  24571. return;
  24572. }
  24573. renderPipeline._attachCameras(cameras, unique);
  24574. };
  24575. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  24576. var renderPipeline = this._renderPipelines[renderPipelineName];
  24577. if (!renderPipeline) {
  24578. return;
  24579. }
  24580. renderPipeline._detachCameras(cameras);
  24581. };
  24582. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24583. var renderPipeline = this._renderPipelines[renderPipelineName];
  24584. if (!renderPipeline) {
  24585. return;
  24586. }
  24587. renderPipeline._enableEffect(renderEffectName, cameras);
  24588. };
  24589. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24590. var renderPipeline = this._renderPipelines[renderPipelineName];
  24591. if (!renderPipeline) {
  24592. return;
  24593. }
  24594. renderPipeline._disableEffect(renderEffectName, cameras);
  24595. };
  24596. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  24597. var renderPipeline = this._renderPipelines[renderPipelineName];
  24598. if (!renderPipeline) {
  24599. return;
  24600. }
  24601. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  24602. };
  24603. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  24604. var renderPipeline = this._renderPipelines[renderPipelineName];
  24605. if (!renderPipeline) {
  24606. return;
  24607. }
  24608. renderPipeline._disableDisplayOnlyPass(cameras);
  24609. };
  24610. PostProcessRenderPipelineManager.prototype.update = function () {
  24611. for (var renderPipelineName in this._renderPipelines) {
  24612. this._renderPipelines[renderPipelineName]._update();
  24613. }
  24614. };
  24615. return PostProcessRenderPipelineManager;
  24616. })();
  24617. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  24618. })(BABYLON || (BABYLON = {}));
  24619. var BABYLON;
  24620. (function (BABYLON) {
  24621. var BoundingBoxRenderer = (function () {
  24622. function BoundingBoxRenderer(scene) {
  24623. this.frontColor = new BABYLON.Color3(1, 1, 1);
  24624. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  24625. this.showBackLines = true;
  24626. this.renderList = new BABYLON.SmartArray(32);
  24627. this._scene = scene;
  24628. }
  24629. BoundingBoxRenderer.prototype._prepareRessources = function () {
  24630. if (this._colorShader) {
  24631. return;
  24632. }
  24633. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  24634. attributes: ["position"],
  24635. uniforms: ["worldViewProjection", "color"]
  24636. });
  24637. var engine = this._scene.getEngine();
  24638. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  24639. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  24640. 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]);
  24641. };
  24642. BoundingBoxRenderer.prototype.reset = function () {
  24643. this.renderList.reset();
  24644. };
  24645. BoundingBoxRenderer.prototype.render = function () {
  24646. if (this.renderList.length === 0) {
  24647. return;
  24648. }
  24649. this._prepareRessources();
  24650. if (!this._colorShader.isReady()) {
  24651. return;
  24652. }
  24653. var engine = this._scene.getEngine();
  24654. engine.setDepthWrite(false);
  24655. this._colorShader._preBind();
  24656. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  24657. var boundingBox = this.renderList.data[boundingBoxIndex];
  24658. var min = boundingBox.minimum;
  24659. var max = boundingBox.maximum;
  24660. var diff = max.subtract(min);
  24661. var median = min.add(diff.scale(0.5));
  24662. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  24663. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  24664. .multiply(boundingBox.getWorldMatrix());
  24665. // VBOs
  24666. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  24667. if (this.showBackLines) {
  24668. // Back
  24669. engine.setDepthFunctionToGreaterOrEqual();
  24670. this._scene.resetCachedMaterial();
  24671. this._colorShader.setColor4("color", this.backColor.toColor4());
  24672. this._colorShader.bind(worldMatrix);
  24673. // Draw order
  24674. engine.draw(false, 0, 24);
  24675. }
  24676. // Front
  24677. engine.setDepthFunctionToLess();
  24678. this._scene.resetCachedMaterial();
  24679. this._colorShader.setColor4("color", this.frontColor.toColor4());
  24680. this._colorShader.bind(worldMatrix);
  24681. // Draw order
  24682. engine.draw(false, 0, 24);
  24683. }
  24684. this._colorShader.unbind();
  24685. engine.setDepthFunctionToLessOrEqual();
  24686. engine.setDepthWrite(true);
  24687. };
  24688. BoundingBoxRenderer.prototype.dispose = function () {
  24689. if (!this._colorShader) {
  24690. return;
  24691. }
  24692. this._colorShader.dispose();
  24693. this._vb.dispose();
  24694. this._scene.getEngine()._releaseBuffer(this._ib);
  24695. };
  24696. return BoundingBoxRenderer;
  24697. })();
  24698. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  24699. })(BABYLON || (BABYLON = {}));
  24700. var BABYLON;
  24701. (function (BABYLON) {
  24702. var Condition = (function () {
  24703. function Condition(actionManager) {
  24704. this._actionManager = actionManager;
  24705. }
  24706. Condition.prototype.isValid = function () {
  24707. return true;
  24708. };
  24709. Condition.prototype._getProperty = function (propertyPath) {
  24710. return this._actionManager._getProperty(propertyPath);
  24711. };
  24712. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24713. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24714. };
  24715. return Condition;
  24716. })();
  24717. BABYLON.Condition = Condition;
  24718. var ValueCondition = (function (_super) {
  24719. __extends(ValueCondition, _super);
  24720. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24721. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24722. _super.call(this, actionManager);
  24723. this.propertyPath = propertyPath;
  24724. this.value = value;
  24725. this.operator = operator;
  24726. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24727. this._property = this._getProperty(this.propertyPath);
  24728. }
  24729. Object.defineProperty(ValueCondition, "IsEqual", {
  24730. get: function () {
  24731. return ValueCondition._IsEqual;
  24732. },
  24733. enumerable: true,
  24734. configurable: true
  24735. });
  24736. Object.defineProperty(ValueCondition, "IsDifferent", {
  24737. get: function () {
  24738. return ValueCondition._IsDifferent;
  24739. },
  24740. enumerable: true,
  24741. configurable: true
  24742. });
  24743. Object.defineProperty(ValueCondition, "IsGreater", {
  24744. get: function () {
  24745. return ValueCondition._IsGreater;
  24746. },
  24747. enumerable: true,
  24748. configurable: true
  24749. });
  24750. Object.defineProperty(ValueCondition, "IsLesser", {
  24751. get: function () {
  24752. return ValueCondition._IsLesser;
  24753. },
  24754. enumerable: true,
  24755. configurable: true
  24756. });
  24757. // Methods
  24758. ValueCondition.prototype.isValid = function () {
  24759. switch (this.operator) {
  24760. case ValueCondition.IsGreater:
  24761. return this._target[this._property] > this.value;
  24762. case ValueCondition.IsLesser:
  24763. return this._target[this._property] < this.value;
  24764. case ValueCondition.IsEqual:
  24765. case ValueCondition.IsDifferent:
  24766. var check;
  24767. if (this.value.equals) {
  24768. check = this.value.equals(this._target[this._property]);
  24769. }
  24770. else {
  24771. check = this.value === this._target[this._property];
  24772. }
  24773. return this.operator === ValueCondition.IsEqual ? check : !check;
  24774. }
  24775. return false;
  24776. };
  24777. // Statics
  24778. ValueCondition._IsEqual = 0;
  24779. ValueCondition._IsDifferent = 1;
  24780. ValueCondition._IsGreater = 2;
  24781. ValueCondition._IsLesser = 3;
  24782. return ValueCondition;
  24783. })(Condition);
  24784. BABYLON.ValueCondition = ValueCondition;
  24785. var PredicateCondition = (function (_super) {
  24786. __extends(PredicateCondition, _super);
  24787. function PredicateCondition(actionManager, predicate) {
  24788. _super.call(this, actionManager);
  24789. this.predicate = predicate;
  24790. }
  24791. PredicateCondition.prototype.isValid = function () {
  24792. return this.predicate();
  24793. };
  24794. return PredicateCondition;
  24795. })(Condition);
  24796. BABYLON.PredicateCondition = PredicateCondition;
  24797. var StateCondition = (function (_super) {
  24798. __extends(StateCondition, _super);
  24799. function StateCondition(actionManager, target, value) {
  24800. _super.call(this, actionManager);
  24801. this.value = value;
  24802. this._target = target;
  24803. }
  24804. // Methods
  24805. StateCondition.prototype.isValid = function () {
  24806. return this._target.state === this.value;
  24807. };
  24808. return StateCondition;
  24809. })(Condition);
  24810. BABYLON.StateCondition = StateCondition;
  24811. })(BABYLON || (BABYLON = {}));
  24812. var BABYLON;
  24813. (function (BABYLON) {
  24814. var Action = (function () {
  24815. function Action(triggerOptions, condition) {
  24816. this.triggerOptions = triggerOptions;
  24817. if (triggerOptions.parameter) {
  24818. this.trigger = triggerOptions.trigger;
  24819. this._triggerParameter = triggerOptions.parameter;
  24820. }
  24821. else {
  24822. this.trigger = triggerOptions;
  24823. }
  24824. this._nextActiveAction = this;
  24825. this._condition = condition;
  24826. }
  24827. // Methods
  24828. Action.prototype._prepare = function () {
  24829. };
  24830. Action.prototype.getTriggerParameter = function () {
  24831. return this._triggerParameter;
  24832. };
  24833. Action.prototype._executeCurrent = function (evt) {
  24834. if (this._nextActiveAction._condition) {
  24835. var condition = this._nextActiveAction._condition;
  24836. var currentRenderId = this._actionManager.getScene().getRenderId();
  24837. // We cache the current evaluation for the current frame
  24838. if (condition._evaluationId === currentRenderId) {
  24839. if (!condition._currentResult) {
  24840. return;
  24841. }
  24842. }
  24843. else {
  24844. condition._evaluationId = currentRenderId;
  24845. if (!condition.isValid()) {
  24846. condition._currentResult = false;
  24847. return;
  24848. }
  24849. condition._currentResult = true;
  24850. }
  24851. }
  24852. this._nextActiveAction.execute(evt);
  24853. if (this._nextActiveAction._child) {
  24854. if (!this._nextActiveAction._child._actionManager) {
  24855. this._nextActiveAction._child._actionManager = this._actionManager;
  24856. }
  24857. this._nextActiveAction = this._nextActiveAction._child;
  24858. }
  24859. else {
  24860. this._nextActiveAction = this;
  24861. }
  24862. };
  24863. Action.prototype.execute = function (evt) {
  24864. };
  24865. Action.prototype.then = function (action) {
  24866. this._child = action;
  24867. action._actionManager = this._actionManager;
  24868. action._prepare();
  24869. return action;
  24870. };
  24871. Action.prototype._getProperty = function (propertyPath) {
  24872. return this._actionManager._getProperty(propertyPath);
  24873. };
  24874. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24875. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24876. };
  24877. return Action;
  24878. })();
  24879. BABYLON.Action = Action;
  24880. })(BABYLON || (BABYLON = {}));
  24881. var BABYLON;
  24882. (function (BABYLON) {
  24883. /**
  24884. * ActionEvent is the event beint sent when an action is triggered.
  24885. */
  24886. var ActionEvent = (function () {
  24887. /**
  24888. * @constructor
  24889. * @param source The mesh or sprite that triggered the action.
  24890. * @param pointerX The X mouse cursor position at the time of the event
  24891. * @param pointerY The Y mouse cursor position at the time of the event
  24892. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24893. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24894. */
  24895. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  24896. this.source = source;
  24897. this.pointerX = pointerX;
  24898. this.pointerY = pointerY;
  24899. this.meshUnderPointer = meshUnderPointer;
  24900. this.sourceEvent = sourceEvent;
  24901. this.additionalData = additionalData;
  24902. }
  24903. /**
  24904. * Helper function to auto-create an ActionEvent from a source mesh.
  24905. * @param source The source mesh that triggered the event
  24906. * @param evt {Event} The original (browser) event
  24907. */
  24908. ActionEvent.CreateNew = function (source, evt, additionalData) {
  24909. var scene = source.getScene();
  24910. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  24911. };
  24912. /**
  24913. * Helper function to auto-create an ActionEvent from a source mesh.
  24914. * @param source The source sprite that triggered the event
  24915. * @param scene Scene associated with the sprite
  24916. * @param evt {Event} The original (browser) event
  24917. */
  24918. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  24919. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  24920. };
  24921. /**
  24922. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24923. * @param scene the scene where the event occurred
  24924. * @param evt {Event} The original (browser) event
  24925. */
  24926. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24927. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24928. };
  24929. return ActionEvent;
  24930. })();
  24931. BABYLON.ActionEvent = ActionEvent;
  24932. /**
  24933. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24934. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24935. */
  24936. var ActionManager = (function () {
  24937. function ActionManager(scene) {
  24938. // Members
  24939. this.actions = new Array();
  24940. this._scene = scene;
  24941. scene._actionManagers.push(this);
  24942. }
  24943. Object.defineProperty(ActionManager, "NothingTrigger", {
  24944. get: function () {
  24945. return ActionManager._NothingTrigger;
  24946. },
  24947. enumerable: true,
  24948. configurable: true
  24949. });
  24950. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24951. get: function () {
  24952. return ActionManager._OnPickTrigger;
  24953. },
  24954. enumerable: true,
  24955. configurable: true
  24956. });
  24957. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24958. get: function () {
  24959. return ActionManager._OnLeftPickTrigger;
  24960. },
  24961. enumerable: true,
  24962. configurable: true
  24963. });
  24964. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24965. get: function () {
  24966. return ActionManager._OnRightPickTrigger;
  24967. },
  24968. enumerable: true,
  24969. configurable: true
  24970. });
  24971. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24972. get: function () {
  24973. return ActionManager._OnCenterPickTrigger;
  24974. },
  24975. enumerable: true,
  24976. configurable: true
  24977. });
  24978. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24979. get: function () {
  24980. return ActionManager._OnPointerOverTrigger;
  24981. },
  24982. enumerable: true,
  24983. configurable: true
  24984. });
  24985. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24986. get: function () {
  24987. return ActionManager._OnPointerOutTrigger;
  24988. },
  24989. enumerable: true,
  24990. configurable: true
  24991. });
  24992. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24993. get: function () {
  24994. return ActionManager._OnEveryFrameTrigger;
  24995. },
  24996. enumerable: true,
  24997. configurable: true
  24998. });
  24999. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25000. get: function () {
  25001. return ActionManager._OnIntersectionEnterTrigger;
  25002. },
  25003. enumerable: true,
  25004. configurable: true
  25005. });
  25006. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25007. get: function () {
  25008. return ActionManager._OnIntersectionExitTrigger;
  25009. },
  25010. enumerable: true,
  25011. configurable: true
  25012. });
  25013. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25014. get: function () {
  25015. return ActionManager._OnKeyDownTrigger;
  25016. },
  25017. enumerable: true,
  25018. configurable: true
  25019. });
  25020. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25021. get: function () {
  25022. return ActionManager._OnKeyUpTrigger;
  25023. },
  25024. enumerable: true,
  25025. configurable: true
  25026. });
  25027. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25028. get: function () {
  25029. return ActionManager._OnPickUpTrigger;
  25030. },
  25031. enumerable: true,
  25032. configurable: true
  25033. });
  25034. // Methods
  25035. ActionManager.prototype.dispose = function () {
  25036. var index = this._scene._actionManagers.indexOf(this);
  25037. if (index > -1) {
  25038. this._scene._actionManagers.splice(index, 1);
  25039. }
  25040. };
  25041. ActionManager.prototype.getScene = function () {
  25042. return this._scene;
  25043. };
  25044. /**
  25045. * Does this action manager handles actions of any of the given triggers
  25046. * @param {number[]} triggers - the triggers to be tested
  25047. * @return {boolean} whether one (or more) of the triggers is handeled
  25048. */
  25049. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25050. for (var index = 0; index < this.actions.length; index++) {
  25051. var action = this.actions[index];
  25052. if (triggers.indexOf(action.trigger) > -1) {
  25053. return true;
  25054. }
  25055. }
  25056. return false;
  25057. };
  25058. /**
  25059. * Does this action manager handles actions of a given trigger
  25060. * @param {number} trigger - the trigger to be tested
  25061. * @return {boolean} whether the trigger is handeled
  25062. */
  25063. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25064. for (var index = 0; index < this.actions.length; index++) {
  25065. var action = this.actions[index];
  25066. if (action.trigger === trigger) {
  25067. return true;
  25068. }
  25069. }
  25070. return false;
  25071. };
  25072. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25073. /**
  25074. * Does this action manager has pointer triggers
  25075. * @return {boolean} whether or not it has pointer triggers
  25076. */
  25077. get: function () {
  25078. for (var index = 0; index < this.actions.length; index++) {
  25079. var action = this.actions[index];
  25080. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25081. return true;
  25082. }
  25083. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25084. return true;
  25085. }
  25086. }
  25087. return false;
  25088. },
  25089. enumerable: true,
  25090. configurable: true
  25091. });
  25092. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25093. /**
  25094. * Does this action manager has pick triggers
  25095. * @return {boolean} whether or not it has pick triggers
  25096. */
  25097. get: function () {
  25098. for (var index = 0; index < this.actions.length; index++) {
  25099. var action = this.actions[index];
  25100. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25101. return true;
  25102. }
  25103. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25104. return true;
  25105. }
  25106. }
  25107. return false;
  25108. },
  25109. enumerable: true,
  25110. configurable: true
  25111. });
  25112. /**
  25113. * Registers an action to this action manager
  25114. * @param {BABYLON.Action} action - the action to be registered
  25115. * @return {BABYLON.Action} the action amended (prepared) after registration
  25116. */
  25117. ActionManager.prototype.registerAction = function (action) {
  25118. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25119. if (this.getScene().actionManager !== this) {
  25120. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25121. return null;
  25122. }
  25123. }
  25124. this.actions.push(action);
  25125. action._actionManager = this;
  25126. action._prepare();
  25127. return action;
  25128. };
  25129. /**
  25130. * Process a specific trigger
  25131. * @param {number} trigger - the trigger to process
  25132. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25133. */
  25134. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25135. for (var index = 0; index < this.actions.length; index++) {
  25136. var action = this.actions[index];
  25137. if (action.trigger === trigger) {
  25138. if (trigger === ActionManager.OnKeyUpTrigger
  25139. || trigger === ActionManager.OnKeyDownTrigger) {
  25140. var parameter = action.getTriggerParameter();
  25141. if (parameter) {
  25142. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25143. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25144. if (actualkey !== parameter.toLowerCase()) {
  25145. continue;
  25146. }
  25147. }
  25148. }
  25149. action._executeCurrent(evt);
  25150. }
  25151. }
  25152. };
  25153. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25154. var properties = propertyPath.split(".");
  25155. for (var index = 0; index < properties.length - 1; index++) {
  25156. target = target[properties[index]];
  25157. }
  25158. return target;
  25159. };
  25160. ActionManager.prototype._getProperty = function (propertyPath) {
  25161. var properties = propertyPath.split(".");
  25162. return properties[properties.length - 1];
  25163. };
  25164. // Statics
  25165. ActionManager._NothingTrigger = 0;
  25166. ActionManager._OnPickTrigger = 1;
  25167. ActionManager._OnLeftPickTrigger = 2;
  25168. ActionManager._OnRightPickTrigger = 3;
  25169. ActionManager._OnCenterPickTrigger = 4;
  25170. ActionManager._OnPointerOverTrigger = 5;
  25171. ActionManager._OnPointerOutTrigger = 6;
  25172. ActionManager._OnEveryFrameTrigger = 7;
  25173. ActionManager._OnIntersectionEnterTrigger = 8;
  25174. ActionManager._OnIntersectionExitTrigger = 9;
  25175. ActionManager._OnKeyDownTrigger = 10;
  25176. ActionManager._OnKeyUpTrigger = 11;
  25177. ActionManager._OnPickUpTrigger = 12;
  25178. return ActionManager;
  25179. })();
  25180. BABYLON.ActionManager = ActionManager;
  25181. })(BABYLON || (BABYLON = {}));
  25182. var BABYLON;
  25183. (function (BABYLON) {
  25184. var InterpolateValueAction = (function (_super) {
  25185. __extends(InterpolateValueAction, _super);
  25186. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25187. if (duration === void 0) { duration = 1000; }
  25188. _super.call(this, triggerOptions, condition);
  25189. this.propertyPath = propertyPath;
  25190. this.value = value;
  25191. this.duration = duration;
  25192. this.stopOtherAnimations = stopOtherAnimations;
  25193. this.onInterpolationDone = onInterpolationDone;
  25194. this._target = target;
  25195. }
  25196. InterpolateValueAction.prototype._prepare = function () {
  25197. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25198. this._property = this._getProperty(this.propertyPath);
  25199. };
  25200. InterpolateValueAction.prototype.execute = function () {
  25201. var scene = this._actionManager.getScene();
  25202. var keys = [
  25203. {
  25204. frame: 0,
  25205. value: this._target[this._property]
  25206. }, {
  25207. frame: 100,
  25208. value: this.value
  25209. }
  25210. ];
  25211. var dataType;
  25212. if (typeof this.value === "number") {
  25213. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25214. }
  25215. else if (this.value instanceof BABYLON.Color3) {
  25216. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25217. }
  25218. else if (this.value instanceof BABYLON.Vector3) {
  25219. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25220. }
  25221. else if (this.value instanceof BABYLON.Matrix) {
  25222. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25223. }
  25224. else if (this.value instanceof BABYLON.Quaternion) {
  25225. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25226. }
  25227. else {
  25228. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25229. return;
  25230. }
  25231. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25232. animation.setKeys(keys);
  25233. if (this.stopOtherAnimations) {
  25234. scene.stopAnimation(this._target);
  25235. }
  25236. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25237. };
  25238. return InterpolateValueAction;
  25239. })(BABYLON.Action);
  25240. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25241. })(BABYLON || (BABYLON = {}));
  25242. var BABYLON;
  25243. (function (BABYLON) {
  25244. var SwitchBooleanAction = (function (_super) {
  25245. __extends(SwitchBooleanAction, _super);
  25246. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25247. _super.call(this, triggerOptions, condition);
  25248. this.propertyPath = propertyPath;
  25249. this._target = target;
  25250. }
  25251. SwitchBooleanAction.prototype._prepare = function () {
  25252. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25253. this._property = this._getProperty(this.propertyPath);
  25254. };
  25255. SwitchBooleanAction.prototype.execute = function () {
  25256. this._target[this._property] = !this._target[this._property];
  25257. };
  25258. return SwitchBooleanAction;
  25259. })(BABYLON.Action);
  25260. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25261. var SetStateAction = (function (_super) {
  25262. __extends(SetStateAction, _super);
  25263. function SetStateAction(triggerOptions, target, value, condition) {
  25264. _super.call(this, triggerOptions, condition);
  25265. this.value = value;
  25266. this._target = target;
  25267. }
  25268. SetStateAction.prototype.execute = function () {
  25269. this._target.state = this.value;
  25270. };
  25271. return SetStateAction;
  25272. })(BABYLON.Action);
  25273. BABYLON.SetStateAction = SetStateAction;
  25274. var SetValueAction = (function (_super) {
  25275. __extends(SetValueAction, _super);
  25276. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25277. _super.call(this, triggerOptions, condition);
  25278. this.propertyPath = propertyPath;
  25279. this.value = value;
  25280. this._target = target;
  25281. }
  25282. SetValueAction.prototype._prepare = function () {
  25283. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25284. this._property = this._getProperty(this.propertyPath);
  25285. };
  25286. SetValueAction.prototype.execute = function () {
  25287. this._target[this._property] = this.value;
  25288. };
  25289. return SetValueAction;
  25290. })(BABYLON.Action);
  25291. BABYLON.SetValueAction = SetValueAction;
  25292. var IncrementValueAction = (function (_super) {
  25293. __extends(IncrementValueAction, _super);
  25294. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25295. _super.call(this, triggerOptions, condition);
  25296. this.propertyPath = propertyPath;
  25297. this.value = value;
  25298. this._target = target;
  25299. }
  25300. IncrementValueAction.prototype._prepare = function () {
  25301. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25302. this._property = this._getProperty(this.propertyPath);
  25303. if (typeof this._target[this._property] !== "number") {
  25304. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25305. }
  25306. };
  25307. IncrementValueAction.prototype.execute = function () {
  25308. this._target[this._property] += this.value;
  25309. };
  25310. return IncrementValueAction;
  25311. })(BABYLON.Action);
  25312. BABYLON.IncrementValueAction = IncrementValueAction;
  25313. var PlayAnimationAction = (function (_super) {
  25314. __extends(PlayAnimationAction, _super);
  25315. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25316. _super.call(this, triggerOptions, condition);
  25317. this.from = from;
  25318. this.to = to;
  25319. this.loop = loop;
  25320. this._target = target;
  25321. }
  25322. PlayAnimationAction.prototype._prepare = function () {
  25323. };
  25324. PlayAnimationAction.prototype.execute = function () {
  25325. var scene = this._actionManager.getScene();
  25326. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25327. };
  25328. return PlayAnimationAction;
  25329. })(BABYLON.Action);
  25330. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25331. var StopAnimationAction = (function (_super) {
  25332. __extends(StopAnimationAction, _super);
  25333. function StopAnimationAction(triggerOptions, target, condition) {
  25334. _super.call(this, triggerOptions, condition);
  25335. this._target = target;
  25336. }
  25337. StopAnimationAction.prototype._prepare = function () {
  25338. };
  25339. StopAnimationAction.prototype.execute = function () {
  25340. var scene = this._actionManager.getScene();
  25341. scene.stopAnimation(this._target);
  25342. };
  25343. return StopAnimationAction;
  25344. })(BABYLON.Action);
  25345. BABYLON.StopAnimationAction = StopAnimationAction;
  25346. var DoNothingAction = (function (_super) {
  25347. __extends(DoNothingAction, _super);
  25348. function DoNothingAction(triggerOptions, condition) {
  25349. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25350. _super.call(this, triggerOptions, condition);
  25351. }
  25352. DoNothingAction.prototype.execute = function () {
  25353. };
  25354. return DoNothingAction;
  25355. })(BABYLON.Action);
  25356. BABYLON.DoNothingAction = DoNothingAction;
  25357. var CombineAction = (function (_super) {
  25358. __extends(CombineAction, _super);
  25359. function CombineAction(triggerOptions, children, condition) {
  25360. _super.call(this, triggerOptions, condition);
  25361. this.children = children;
  25362. }
  25363. CombineAction.prototype._prepare = function () {
  25364. for (var index = 0; index < this.children.length; index++) {
  25365. this.children[index]._actionManager = this._actionManager;
  25366. this.children[index]._prepare();
  25367. }
  25368. };
  25369. CombineAction.prototype.execute = function (evt) {
  25370. for (var index = 0; index < this.children.length; index++) {
  25371. this.children[index].execute(evt);
  25372. }
  25373. };
  25374. return CombineAction;
  25375. })(BABYLON.Action);
  25376. BABYLON.CombineAction = CombineAction;
  25377. var ExecuteCodeAction = (function (_super) {
  25378. __extends(ExecuteCodeAction, _super);
  25379. function ExecuteCodeAction(triggerOptions, func, condition) {
  25380. _super.call(this, triggerOptions, condition);
  25381. this.func = func;
  25382. }
  25383. ExecuteCodeAction.prototype.execute = function (evt) {
  25384. this.func(evt);
  25385. };
  25386. return ExecuteCodeAction;
  25387. })(BABYLON.Action);
  25388. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25389. var SetParentAction = (function (_super) {
  25390. __extends(SetParentAction, _super);
  25391. function SetParentAction(triggerOptions, target, parent, condition) {
  25392. _super.call(this, triggerOptions, condition);
  25393. this._target = target;
  25394. this._parent = parent;
  25395. }
  25396. SetParentAction.prototype._prepare = function () {
  25397. };
  25398. SetParentAction.prototype.execute = function () {
  25399. if (this._target.parent === this._parent) {
  25400. return;
  25401. }
  25402. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25403. invertParentWorldMatrix.invert();
  25404. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25405. this._target.parent = this._parent;
  25406. };
  25407. return SetParentAction;
  25408. })(BABYLON.Action);
  25409. BABYLON.SetParentAction = SetParentAction;
  25410. var PlaySoundAction = (function (_super) {
  25411. __extends(PlaySoundAction, _super);
  25412. function PlaySoundAction(triggerOptions, sound, condition) {
  25413. _super.call(this, triggerOptions, condition);
  25414. this._sound = sound;
  25415. }
  25416. PlaySoundAction.prototype._prepare = function () {
  25417. };
  25418. PlaySoundAction.prototype.execute = function () {
  25419. if (this._sound !== undefined)
  25420. this._sound.play();
  25421. };
  25422. return PlaySoundAction;
  25423. })(BABYLON.Action);
  25424. BABYLON.PlaySoundAction = PlaySoundAction;
  25425. var StopSoundAction = (function (_super) {
  25426. __extends(StopSoundAction, _super);
  25427. function StopSoundAction(triggerOptions, sound, condition) {
  25428. _super.call(this, triggerOptions, condition);
  25429. this._sound = sound;
  25430. }
  25431. StopSoundAction.prototype._prepare = function () {
  25432. };
  25433. StopSoundAction.prototype.execute = function () {
  25434. if (this._sound !== undefined)
  25435. this._sound.stop();
  25436. };
  25437. return StopSoundAction;
  25438. })(BABYLON.Action);
  25439. BABYLON.StopSoundAction = StopSoundAction;
  25440. })(BABYLON || (BABYLON = {}));
  25441. var BABYLON;
  25442. (function (BABYLON) {
  25443. var Geometry = (function () {
  25444. function Geometry(id, scene, vertexData, updatable, mesh) {
  25445. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25446. this._totalVertices = 0;
  25447. this._indices = [];
  25448. this._isDisposed = false;
  25449. this.id = id;
  25450. this._engine = scene.getEngine();
  25451. this._meshes = [];
  25452. this._scene = scene;
  25453. // vertexData
  25454. if (vertexData) {
  25455. this.setAllVerticesData(vertexData, updatable);
  25456. }
  25457. else {
  25458. this._totalVertices = 0;
  25459. this._indices = [];
  25460. }
  25461. // applyToMesh
  25462. if (mesh) {
  25463. this.applyToMesh(mesh);
  25464. mesh.computeWorldMatrix(true);
  25465. }
  25466. }
  25467. Geometry.prototype.getScene = function () {
  25468. return this._scene;
  25469. };
  25470. Geometry.prototype.getEngine = function () {
  25471. return this._engine;
  25472. };
  25473. Geometry.prototype.isReady = function () {
  25474. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25475. };
  25476. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25477. vertexData.applyToGeometry(this, updatable);
  25478. this.notifyUpdate();
  25479. };
  25480. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25481. this._vertexBuffers = this._vertexBuffers || {};
  25482. if (this._vertexBuffers[kind]) {
  25483. this._vertexBuffers[kind].dispose();
  25484. }
  25485. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25486. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25487. stride = this._vertexBuffers[kind].getStrideSize();
  25488. this._totalVertices = data.length / stride;
  25489. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25490. var meshes = this._meshes;
  25491. var numOfMeshes = meshes.length;
  25492. for (var index = 0; index < numOfMeshes; index++) {
  25493. var mesh = meshes[index];
  25494. mesh._resetPointsArrayCache();
  25495. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25496. mesh._createGlobalSubMesh();
  25497. mesh.computeWorldMatrix(true);
  25498. }
  25499. }
  25500. this.notifyUpdate(kind);
  25501. };
  25502. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25503. var vertexBuffer = this.getVertexBuffer(kind);
  25504. if (!vertexBuffer) {
  25505. return;
  25506. }
  25507. vertexBuffer.updateDirectly(data, offset);
  25508. this.notifyUpdate(kind);
  25509. };
  25510. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25511. var vertexBuffer = this.getVertexBuffer(kind);
  25512. if (!vertexBuffer) {
  25513. return;
  25514. }
  25515. vertexBuffer.update(data);
  25516. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25517. var extend;
  25518. var stride = vertexBuffer.getStrideSize();
  25519. this._totalVertices = data.length / stride;
  25520. if (updateExtends) {
  25521. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25522. }
  25523. var meshes = this._meshes;
  25524. var numOfMeshes = meshes.length;
  25525. for (var index = 0; index < numOfMeshes; index++) {
  25526. var mesh = meshes[index];
  25527. mesh._resetPointsArrayCache();
  25528. if (updateExtends) {
  25529. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25530. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25531. var subMesh = mesh.subMeshes[subIndex];
  25532. subMesh.refreshBoundingInfo();
  25533. }
  25534. }
  25535. }
  25536. }
  25537. this.notifyUpdate(kind);
  25538. };
  25539. Geometry.prototype.getTotalVertices = function () {
  25540. if (!this.isReady()) {
  25541. return 0;
  25542. }
  25543. return this._totalVertices;
  25544. };
  25545. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25546. var vertexBuffer = this.getVertexBuffer(kind);
  25547. if (!vertexBuffer) {
  25548. return null;
  25549. }
  25550. var orig = vertexBuffer.getData();
  25551. if (!copyWhenShared || this._meshes.length === 1) {
  25552. return orig;
  25553. }
  25554. else {
  25555. var len = orig.length;
  25556. var copy = [];
  25557. for (var i = 0; i < len; i++) {
  25558. copy.push(orig[i]);
  25559. }
  25560. return copy;
  25561. }
  25562. };
  25563. Geometry.prototype.getVertexBuffer = function (kind) {
  25564. if (!this.isReady()) {
  25565. return null;
  25566. }
  25567. return this._vertexBuffers[kind];
  25568. };
  25569. Geometry.prototype.getVertexBuffers = function () {
  25570. if (!this.isReady()) {
  25571. return null;
  25572. }
  25573. return this._vertexBuffers;
  25574. };
  25575. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25576. if (!this._vertexBuffers) {
  25577. if (this._delayInfo) {
  25578. return this._delayInfo.indexOf(kind) !== -1;
  25579. }
  25580. return false;
  25581. }
  25582. return this._vertexBuffers[kind] !== undefined;
  25583. };
  25584. Geometry.prototype.getVerticesDataKinds = function () {
  25585. var result = [];
  25586. var kind;
  25587. if (!this._vertexBuffers && this._delayInfo) {
  25588. for (kind in this._delayInfo) {
  25589. result.push(kind);
  25590. }
  25591. }
  25592. else {
  25593. for (kind in this._vertexBuffers) {
  25594. result.push(kind);
  25595. }
  25596. }
  25597. return result;
  25598. };
  25599. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25600. if (this._indexBuffer) {
  25601. this._engine._releaseBuffer(this._indexBuffer);
  25602. }
  25603. this._indices = indices;
  25604. if (this._meshes.length !== 0 && this._indices) {
  25605. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25606. }
  25607. if (totalVertices !== undefined) {
  25608. this._totalVertices = totalVertices;
  25609. }
  25610. var meshes = this._meshes;
  25611. var numOfMeshes = meshes.length;
  25612. for (var index = 0; index < numOfMeshes; index++) {
  25613. meshes[index]._createGlobalSubMesh();
  25614. }
  25615. this.notifyUpdate();
  25616. };
  25617. Geometry.prototype.getTotalIndices = function () {
  25618. if (!this.isReady()) {
  25619. return 0;
  25620. }
  25621. return this._indices.length;
  25622. };
  25623. Geometry.prototype.getIndices = function (copyWhenShared) {
  25624. if (!this.isReady()) {
  25625. return null;
  25626. }
  25627. var orig = this._indices;
  25628. if (!copyWhenShared || this._meshes.length === 1) {
  25629. return orig;
  25630. }
  25631. else {
  25632. var len = orig.length;
  25633. var copy = [];
  25634. for (var i = 0; i < len; i++) {
  25635. copy.push(orig[i]);
  25636. }
  25637. return copy;
  25638. }
  25639. };
  25640. Geometry.prototype.getIndexBuffer = function () {
  25641. if (!this.isReady()) {
  25642. return null;
  25643. }
  25644. return this._indexBuffer;
  25645. };
  25646. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25647. var meshes = this._meshes;
  25648. var index = meshes.indexOf(mesh);
  25649. if (index === -1) {
  25650. return;
  25651. }
  25652. for (var kind in this._vertexBuffers) {
  25653. this._vertexBuffers[kind].dispose();
  25654. }
  25655. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25656. this._indexBuffer = null;
  25657. }
  25658. meshes.splice(index, 1);
  25659. mesh._geometry = null;
  25660. if (meshes.length === 0 && shouldDispose) {
  25661. this.dispose();
  25662. }
  25663. };
  25664. Geometry.prototype.applyToMesh = function (mesh) {
  25665. if (mesh._geometry === this) {
  25666. return;
  25667. }
  25668. var previousGeometry = mesh._geometry;
  25669. if (previousGeometry) {
  25670. previousGeometry.releaseForMesh(mesh);
  25671. }
  25672. var meshes = this._meshes;
  25673. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25674. mesh._geometry = this;
  25675. this._scene.pushGeometry(this);
  25676. meshes.push(mesh);
  25677. if (this.isReady()) {
  25678. this._applyToMesh(mesh);
  25679. }
  25680. else {
  25681. mesh._boundingInfo = this._boundingInfo;
  25682. }
  25683. };
  25684. Geometry.prototype._applyToMesh = function (mesh) {
  25685. var numOfMeshes = this._meshes.length;
  25686. // vertexBuffers
  25687. for (var kind in this._vertexBuffers) {
  25688. if (numOfMeshes === 1) {
  25689. this._vertexBuffers[kind].create();
  25690. }
  25691. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25692. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25693. mesh._resetPointsArrayCache();
  25694. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25695. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25696. mesh._createGlobalSubMesh();
  25697. //bounding info was just created again, world matrix should be applied again.
  25698. mesh._updateBoundingInfo();
  25699. }
  25700. }
  25701. // indexBuffer
  25702. if (numOfMeshes === 1 && this._indices) {
  25703. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25704. }
  25705. if (this._indexBuffer) {
  25706. this._indexBuffer.references = numOfMeshes;
  25707. }
  25708. };
  25709. Geometry.prototype.notifyUpdate = function (kind) {
  25710. if (this.onGeometryUpdated) {
  25711. this.onGeometryUpdated(this, kind);
  25712. }
  25713. };
  25714. Geometry.prototype.load = function (scene, onLoaded) {
  25715. var _this = this;
  25716. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25717. return;
  25718. }
  25719. if (this.isReady()) {
  25720. if (onLoaded) {
  25721. onLoaded();
  25722. }
  25723. return;
  25724. }
  25725. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25726. scene._addPendingData(this);
  25727. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25728. _this._delayLoadingFunction(JSON.parse(data), _this);
  25729. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25730. _this._delayInfo = [];
  25731. scene._removePendingData(_this);
  25732. var meshes = _this._meshes;
  25733. var numOfMeshes = meshes.length;
  25734. for (var index = 0; index < numOfMeshes; index++) {
  25735. _this._applyToMesh(meshes[index]);
  25736. }
  25737. if (onLoaded) {
  25738. onLoaded();
  25739. }
  25740. }, function () { }, scene.database);
  25741. };
  25742. Geometry.prototype.isDisposed = function () {
  25743. return this._isDisposed;
  25744. };
  25745. Geometry.prototype.dispose = function () {
  25746. var meshes = this._meshes;
  25747. var numOfMeshes = meshes.length;
  25748. var index;
  25749. for (index = 0; index < numOfMeshes; index++) {
  25750. this.releaseForMesh(meshes[index]);
  25751. }
  25752. this._meshes = [];
  25753. for (var kind in this._vertexBuffers) {
  25754. this._vertexBuffers[kind].dispose();
  25755. }
  25756. this._vertexBuffers = [];
  25757. this._totalVertices = 0;
  25758. if (this._indexBuffer) {
  25759. this._engine._releaseBuffer(this._indexBuffer);
  25760. }
  25761. this._indexBuffer = null;
  25762. this._indices = [];
  25763. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25764. this.delayLoadingFile = null;
  25765. this._delayLoadingFunction = null;
  25766. this._delayInfo = [];
  25767. this._boundingInfo = null; // todo: .dispose()
  25768. this._scene.removeGeometry(this);
  25769. this._isDisposed = true;
  25770. };
  25771. Geometry.prototype.copy = function (id) {
  25772. var vertexData = new BABYLON.VertexData();
  25773. vertexData.indices = [];
  25774. var indices = this.getIndices();
  25775. for (var index = 0; index < indices.length; index++) {
  25776. vertexData.indices.push(indices[index]);
  25777. }
  25778. var updatable = false;
  25779. var stopChecking = false;
  25780. var kind;
  25781. for (kind in this._vertexBuffers) {
  25782. // using slice() to make a copy of the array and not just reference it
  25783. var data = this.getVerticesData(kind);
  25784. if (data instanceof Float32Array) {
  25785. vertexData.set(new Float32Array(data), kind);
  25786. }
  25787. else {
  25788. vertexData.set(data.slice(0), kind);
  25789. }
  25790. if (!stopChecking) {
  25791. updatable = this.getVertexBuffer(kind).isUpdatable();
  25792. stopChecking = !updatable;
  25793. }
  25794. }
  25795. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25796. geometry.delayLoadState = this.delayLoadState;
  25797. geometry.delayLoadingFile = this.delayLoadingFile;
  25798. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25799. for (kind in this._delayInfo) {
  25800. geometry._delayInfo = geometry._delayInfo || [];
  25801. geometry._delayInfo.push(kind);
  25802. }
  25803. // Bounding info
  25804. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25805. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25806. return geometry;
  25807. };
  25808. // Statics
  25809. Geometry.ExtractFromMesh = function (mesh, id) {
  25810. var geometry = mesh._geometry;
  25811. if (!geometry) {
  25812. return null;
  25813. }
  25814. return geometry.copy(id);
  25815. };
  25816. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25817. // be aware Math.random() could cause collisions
  25818. Geometry.RandomId = function () {
  25819. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25820. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25821. return v.toString(16);
  25822. });
  25823. };
  25824. return Geometry;
  25825. })();
  25826. BABYLON.Geometry = Geometry;
  25827. /////// Primitives //////////////////////////////////////////////
  25828. var Geometry;
  25829. (function (Geometry) {
  25830. var Primitives;
  25831. (function (Primitives) {
  25832. /// Abstract class
  25833. var _Primitive = (function (_super) {
  25834. __extends(_Primitive, _super);
  25835. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25836. this._beingRegenerated = true;
  25837. this._canBeRegenerated = canBeRegenerated;
  25838. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25839. this._beingRegenerated = false;
  25840. }
  25841. _Primitive.prototype.canBeRegenerated = function () {
  25842. return this._canBeRegenerated;
  25843. };
  25844. _Primitive.prototype.regenerate = function () {
  25845. if (!this._canBeRegenerated) {
  25846. return;
  25847. }
  25848. this._beingRegenerated = true;
  25849. this.setAllVerticesData(this._regenerateVertexData(), false);
  25850. this._beingRegenerated = false;
  25851. };
  25852. _Primitive.prototype.asNewGeometry = function (id) {
  25853. return _super.prototype.copy.call(this, id);
  25854. };
  25855. // overrides
  25856. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25857. if (!this._beingRegenerated) {
  25858. return;
  25859. }
  25860. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25861. };
  25862. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25863. if (!this._beingRegenerated) {
  25864. return;
  25865. }
  25866. _super.prototype.setVerticesData.call(this, kind, data, false);
  25867. };
  25868. // to override
  25869. // protected
  25870. _Primitive.prototype._regenerateVertexData = function () {
  25871. throw new Error("Abstract method");
  25872. };
  25873. _Primitive.prototype.copy = function (id) {
  25874. throw new Error("Must be overriden in sub-classes.");
  25875. };
  25876. return _Primitive;
  25877. })(Geometry);
  25878. Primitives._Primitive = _Primitive;
  25879. var Ribbon = (function (_super) {
  25880. __extends(Ribbon, _super);
  25881. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25882. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25883. this.pathArray = pathArray;
  25884. this.closeArray = closeArray;
  25885. this.closePath = closePath;
  25886. this.offset = offset;
  25887. this.side = side;
  25888. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25889. }
  25890. Ribbon.prototype._regenerateVertexData = function () {
  25891. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  25892. };
  25893. Ribbon.prototype.copy = function (id) {
  25894. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25895. };
  25896. return Ribbon;
  25897. })(_Primitive);
  25898. Primitives.Ribbon = Ribbon;
  25899. var Box = (function (_super) {
  25900. __extends(Box, _super);
  25901. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25902. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25903. this.size = size;
  25904. this.side = side;
  25905. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25906. }
  25907. Box.prototype._regenerateVertexData = function () {
  25908. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  25909. };
  25910. Box.prototype.copy = function (id) {
  25911. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25912. };
  25913. return Box;
  25914. })(_Primitive);
  25915. Primitives.Box = Box;
  25916. var Sphere = (function (_super) {
  25917. __extends(Sphere, _super);
  25918. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25919. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25920. this.segments = segments;
  25921. this.diameter = diameter;
  25922. this.side = side;
  25923. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25924. }
  25925. Sphere.prototype._regenerateVertexData = function () {
  25926. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  25927. };
  25928. Sphere.prototype.copy = function (id) {
  25929. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25930. };
  25931. return Sphere;
  25932. })(_Primitive);
  25933. Primitives.Sphere = Sphere;
  25934. var Disc = (function (_super) {
  25935. __extends(Disc, _super);
  25936. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  25937. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25938. this.radius = radius;
  25939. this.tessellation = tessellation;
  25940. this.side = side;
  25941. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25942. }
  25943. Disc.prototype._regenerateVertexData = function () {
  25944. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  25945. };
  25946. Disc.prototype.copy = function (id) {
  25947. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  25948. };
  25949. return Disc;
  25950. })(_Primitive);
  25951. Primitives.Disc = Disc;
  25952. var Cylinder = (function (_super) {
  25953. __extends(Cylinder, _super);
  25954. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25955. if (subdivisions === void 0) { subdivisions = 1; }
  25956. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25957. this.height = height;
  25958. this.diameterTop = diameterTop;
  25959. this.diameterBottom = diameterBottom;
  25960. this.tessellation = tessellation;
  25961. this.subdivisions = subdivisions;
  25962. this.side = side;
  25963. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25964. }
  25965. Cylinder.prototype._regenerateVertexData = function () {
  25966. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  25967. };
  25968. Cylinder.prototype.copy = function (id) {
  25969. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25970. };
  25971. return Cylinder;
  25972. })(_Primitive);
  25973. Primitives.Cylinder = Cylinder;
  25974. var Torus = (function (_super) {
  25975. __extends(Torus, _super);
  25976. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25977. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25978. this.diameter = diameter;
  25979. this.thickness = thickness;
  25980. this.tessellation = tessellation;
  25981. this.side = side;
  25982. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25983. }
  25984. Torus.prototype._regenerateVertexData = function () {
  25985. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  25986. };
  25987. Torus.prototype.copy = function (id) {
  25988. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25989. };
  25990. return Torus;
  25991. })(_Primitive);
  25992. Primitives.Torus = Torus;
  25993. var Ground = (function (_super) {
  25994. __extends(Ground, _super);
  25995. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25996. this.width = width;
  25997. this.height = height;
  25998. this.subdivisions = subdivisions;
  25999. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26000. }
  26001. Ground.prototype._regenerateVertexData = function () {
  26002. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26003. };
  26004. Ground.prototype.copy = function (id) {
  26005. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26006. };
  26007. return Ground;
  26008. })(_Primitive);
  26009. Primitives.Ground = Ground;
  26010. var TiledGround = (function (_super) {
  26011. __extends(TiledGround, _super);
  26012. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26013. this.xmin = xmin;
  26014. this.zmin = zmin;
  26015. this.xmax = xmax;
  26016. this.zmax = zmax;
  26017. this.subdivisions = subdivisions;
  26018. this.precision = precision;
  26019. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26020. }
  26021. TiledGround.prototype._regenerateVertexData = function () {
  26022. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26023. };
  26024. TiledGround.prototype.copy = function (id) {
  26025. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26026. };
  26027. return TiledGround;
  26028. })(_Primitive);
  26029. Primitives.TiledGround = TiledGround;
  26030. var Plane = (function (_super) {
  26031. __extends(Plane, _super);
  26032. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26033. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26034. this.size = size;
  26035. this.side = side;
  26036. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26037. }
  26038. Plane.prototype._regenerateVertexData = function () {
  26039. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26040. };
  26041. Plane.prototype.copy = function (id) {
  26042. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26043. };
  26044. return Plane;
  26045. })(_Primitive);
  26046. Primitives.Plane = Plane;
  26047. var TorusKnot = (function (_super) {
  26048. __extends(TorusKnot, _super);
  26049. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26050. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26051. this.radius = radius;
  26052. this.tube = tube;
  26053. this.radialSegments = radialSegments;
  26054. this.tubularSegments = tubularSegments;
  26055. this.p = p;
  26056. this.q = q;
  26057. this.side = side;
  26058. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26059. }
  26060. TorusKnot.prototype._regenerateVertexData = function () {
  26061. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  26062. };
  26063. TorusKnot.prototype.copy = function (id) {
  26064. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26065. };
  26066. return TorusKnot;
  26067. })(_Primitive);
  26068. Primitives.TorusKnot = TorusKnot;
  26069. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26070. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26071. })(BABYLON || (BABYLON = {}));
  26072. var BABYLON;
  26073. (function (BABYLON) {
  26074. var GroundMesh = (function (_super) {
  26075. __extends(GroundMesh, _super);
  26076. function GroundMesh(name, scene) {
  26077. _super.call(this, name, scene);
  26078. this.generateOctree = false;
  26079. this._worldInverse = new BABYLON.Matrix();
  26080. }
  26081. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26082. get: function () {
  26083. return this._subdivisions;
  26084. },
  26085. enumerable: true,
  26086. configurable: true
  26087. });
  26088. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26089. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26090. this._subdivisions = chunksCount;
  26091. this.subdivide(this._subdivisions);
  26092. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26093. };
  26094. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26095. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26096. this.getWorldMatrix().invertToRef(this._worldInverse);
  26097. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26098. var pickInfo = this.intersects(ray);
  26099. if (pickInfo.hit) {
  26100. return pickInfo.pickedPoint.y;
  26101. }
  26102. return 0;
  26103. };
  26104. return GroundMesh;
  26105. })(BABYLON.Mesh);
  26106. BABYLON.GroundMesh = GroundMesh;
  26107. })(BABYLON || (BABYLON = {}));
  26108. var BABYLON;
  26109. (function (BABYLON) {
  26110. var LinesMesh = (function (_super) {
  26111. __extends(LinesMesh, _super);
  26112. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26113. if (parent === void 0) { parent = null; }
  26114. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26115. this.color = new BABYLON.Color3(1, 1, 1);
  26116. this.alpha = 1;
  26117. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26118. attributes: ["position"],
  26119. uniforms: ["worldViewProjection", "color"],
  26120. needAlphaBlending: true
  26121. });
  26122. }
  26123. Object.defineProperty(LinesMesh.prototype, "material", {
  26124. get: function () {
  26125. return this._colorShader;
  26126. },
  26127. enumerable: true,
  26128. configurable: true
  26129. });
  26130. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26131. get: function () {
  26132. return false;
  26133. },
  26134. enumerable: true,
  26135. configurable: true
  26136. });
  26137. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26138. get: function () {
  26139. return false;
  26140. },
  26141. enumerable: true,
  26142. configurable: true
  26143. });
  26144. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26145. var engine = this.getScene().getEngine();
  26146. var indexToBind = this._geometry.getIndexBuffer();
  26147. // VBOs
  26148. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26149. // Color
  26150. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26151. };
  26152. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26153. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26154. return;
  26155. }
  26156. var engine = this.getScene().getEngine();
  26157. // Draw order
  26158. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26159. };
  26160. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26161. return null;
  26162. };
  26163. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26164. this._colorShader.dispose();
  26165. _super.prototype.dispose.call(this, doNotRecurse);
  26166. };
  26167. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  26168. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  26169. };
  26170. return LinesMesh;
  26171. })(BABYLON.Mesh);
  26172. BABYLON.LinesMesh = LinesMesh;
  26173. })(BABYLON || (BABYLON = {}));
  26174. var BABYLON;
  26175. (function (BABYLON) {
  26176. var DebugLayer = (function () {
  26177. function DebugLayer(scene) {
  26178. var _this = this;
  26179. this._transformationMatrix = BABYLON.Matrix.Identity();
  26180. this._enabled = false;
  26181. this._labelsEnabled = false;
  26182. this._displayStatistics = true;
  26183. this._displayTree = false;
  26184. this._displayLogs = false;
  26185. this._identityMatrix = BABYLON.Matrix.Identity();
  26186. this.axisRatio = 0.02;
  26187. this.accentColor = "orange";
  26188. this._scene = scene;
  26189. this._syncPositions = function () {
  26190. var engine = _this._scene.getEngine();
  26191. var canvasRect = engine.getRenderingCanvasClientRect();
  26192. if (_this._showUI) {
  26193. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26194. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26195. _this._statsDiv.style.width = "400px";
  26196. _this._statsDiv.style.height = "auto";
  26197. _this._statsSubsetDiv.style.maxHeight = "240px";
  26198. _this._optionsDiv.style.left = "0px";
  26199. _this._optionsDiv.style.top = "10px";
  26200. _this._optionsDiv.style.width = "200px";
  26201. _this._optionsDiv.style.height = "auto";
  26202. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26203. _this._logDiv.style.left = "0px";
  26204. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26205. _this._logDiv.style.width = "600px";
  26206. _this._logDiv.style.height = "160px";
  26207. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26208. _this._treeDiv.style.top = "10px";
  26209. _this._treeDiv.style.width = "300px";
  26210. _this._treeDiv.style.height = "auto";
  26211. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26212. }
  26213. _this._globalDiv.style.left = canvasRect.left + "px";
  26214. _this._globalDiv.style.top = canvasRect.top + "px";
  26215. _this._drawingCanvas.style.left = "0px";
  26216. _this._drawingCanvas.style.top = "0px";
  26217. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26218. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26219. var devicePixelRatio = window.devicePixelRatio || 1;
  26220. var context = _this._drawingContext;
  26221. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  26222. context.mozBackingStorePixelRatio ||
  26223. context.msBackingStorePixelRatio ||
  26224. context.oBackingStorePixelRatio ||
  26225. context.backingStorePixelRatio || 1;
  26226. _this._ratio = devicePixelRatio / backingStoreRatio;
  26227. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26228. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26229. };
  26230. this._onCanvasClick = function (evt) {
  26231. _this._clickPosition = {
  26232. x: evt.clientX * _this._ratio,
  26233. y: evt.clientY * _this._ratio
  26234. };
  26235. };
  26236. this._syncUI = function () {
  26237. if (_this._showUI) {
  26238. if (_this._displayStatistics) {
  26239. _this._displayStats();
  26240. _this._statsDiv.style.display = "";
  26241. }
  26242. else {
  26243. _this._statsDiv.style.display = "none";
  26244. }
  26245. if (_this._displayLogs) {
  26246. _this._logDiv.style.display = "";
  26247. }
  26248. else {
  26249. _this._logDiv.style.display = "none";
  26250. }
  26251. if (_this._displayTree) {
  26252. _this._treeDiv.style.display = "";
  26253. if (_this._needToRefreshMeshesTree) {
  26254. _this._needToRefreshMeshesTree = false;
  26255. _this._refreshMeshesTreeContent();
  26256. }
  26257. }
  26258. else {
  26259. _this._treeDiv.style.display = "none";
  26260. }
  26261. }
  26262. };
  26263. this._syncData = function () {
  26264. if (_this._labelsEnabled || !_this._showUI) {
  26265. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26266. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26267. var engine = _this._scene.getEngine();
  26268. var viewport = _this._camera.viewport;
  26269. var globalViewport = viewport.toGlobal(engine);
  26270. // Meshes
  26271. var meshes = _this._camera.getActiveMeshes();
  26272. for (var index = 0; index < meshes.length; index++) {
  26273. var mesh = meshes.data[index];
  26274. var position = mesh.getBoundingInfo().boundingSphere.center;
  26275. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26276. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26277. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26278. }
  26279. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26280. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  26281. }
  26282. }
  26283. // Cameras
  26284. var cameras = _this._scene.cameras;
  26285. for (index = 0; index < cameras.length; index++) {
  26286. var camera = cameras[index];
  26287. if (camera === _this._camera) {
  26288. continue;
  26289. }
  26290. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26291. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26292. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26293. _this._camera.detachControl(engine.getRenderingCanvas());
  26294. _this._camera = camera;
  26295. _this._camera.attachControl(engine.getRenderingCanvas());
  26296. }, function () { return "purple"; });
  26297. }
  26298. }
  26299. // Lights
  26300. var lights = _this._scene.lights;
  26301. for (index = 0; index < lights.length; index++) {
  26302. var light = lights[index];
  26303. if (light.position) {
  26304. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26305. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26306. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26307. light.setEnabled(!light.isEnabled());
  26308. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  26309. }
  26310. }
  26311. }
  26312. }
  26313. _this._clickPosition = undefined;
  26314. };
  26315. }
  26316. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26317. while (this._treeSubsetDiv.hasChildNodes()) {
  26318. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26319. }
  26320. // Add meshes
  26321. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26322. sortedArray.sort(function (a, b) {
  26323. if (a.name === b.name) {
  26324. return 0;
  26325. }
  26326. return (a.name > b.name) ? 1 : -1;
  26327. });
  26328. for (var index = 0; index < sortedArray.length; index++) {
  26329. var mesh = sortedArray[index];
  26330. if (!mesh.isEnabled()) {
  26331. continue;
  26332. }
  26333. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26334. m.isVisible = element.checked;
  26335. }, mesh);
  26336. }
  26337. };
  26338. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26339. this._drawingContext.beginPath();
  26340. this._drawingContext.moveTo(zero.x, zero.y);
  26341. this._drawingContext.lineTo(unit.x, unit.y);
  26342. this._drawingContext.strokeStyle = color;
  26343. this._drawingContext.lineWidth = 4;
  26344. this._drawingContext.stroke();
  26345. this._drawingContext.font = "normal 14px Segoe UI";
  26346. this._drawingContext.fillStyle = color;
  26347. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26348. };
  26349. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26350. var position = mesh.getBoundingInfo().boundingSphere.center;
  26351. var worldMatrix = mesh.getWorldMatrix();
  26352. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26353. var unit = (unprojectedVector.subtract(position)).length();
  26354. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26355. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26356. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26357. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26358. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26359. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26360. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26361. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26362. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26363. };
  26364. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26365. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26366. this._drawingContext.font = "normal 12px Segoe UI";
  26367. var textMetrics = this._drawingContext.measureText(text);
  26368. var centerX = projectedPosition.x - textMetrics.width / 2;
  26369. var centerY = projectedPosition.y;
  26370. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26371. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26372. onClick();
  26373. }
  26374. this._drawingContext.beginPath();
  26375. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26376. this._drawingContext.fillStyle = getFillStyle();
  26377. this._drawingContext.globalAlpha = 0.5;
  26378. this._drawingContext.fill();
  26379. this._drawingContext.globalAlpha = 1.0;
  26380. this._drawingContext.strokeStyle = '#FFFFFF';
  26381. this._drawingContext.lineWidth = 1;
  26382. this._drawingContext.stroke();
  26383. this._drawingContext.fillStyle = "#FFFFFF";
  26384. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26385. this._drawingContext.beginPath();
  26386. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26387. this._drawingContext.fill();
  26388. }
  26389. };
  26390. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26391. if (!this._clickPosition) {
  26392. return false;
  26393. }
  26394. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26395. return false;
  26396. }
  26397. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26398. return false;
  26399. }
  26400. return true;
  26401. };
  26402. DebugLayer.prototype.isVisible = function () {
  26403. return this._enabled;
  26404. };
  26405. DebugLayer.prototype.hide = function () {
  26406. if (!this._enabled) {
  26407. return;
  26408. }
  26409. this._enabled = false;
  26410. var engine = this._scene.getEngine();
  26411. this._scene.unregisterBeforeRender(this._syncData);
  26412. this._scene.unregisterAfterRender(this._syncUI);
  26413. document.body.removeChild(this._globalDiv);
  26414. window.removeEventListener("resize", this._syncPositions);
  26415. this._scene.forceShowBoundingBoxes = false;
  26416. this._scene.forceWireframe = false;
  26417. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26418. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26419. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26420. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26421. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26422. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26423. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26424. BABYLON.StandardMaterial.LightmapEnabled = true;
  26425. this._scene.shadowsEnabled = true;
  26426. this._scene.particlesEnabled = true;
  26427. this._scene.postProcessesEnabled = true;
  26428. this._scene.collisionsEnabled = true;
  26429. this._scene.lightsEnabled = true;
  26430. this._scene.texturesEnabled = true;
  26431. this._scene.lensFlaresEnabled = true;
  26432. this._scene.proceduralTexturesEnabled = true;
  26433. this._scene.renderTargetsEnabled = true;
  26434. this._scene.probesEnabled = true;
  26435. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26436. };
  26437. DebugLayer.prototype.show = function (showUI, camera) {
  26438. if (showUI === void 0) { showUI = true; }
  26439. if (camera === void 0) { camera = null; }
  26440. if (this._enabled) {
  26441. return;
  26442. }
  26443. this._enabled = true;
  26444. if (camera) {
  26445. this._camera = camera;
  26446. }
  26447. else {
  26448. this._camera = this._scene.activeCamera;
  26449. }
  26450. this._showUI = showUI;
  26451. var engine = this._scene.getEngine();
  26452. this._globalDiv = document.createElement("div");
  26453. document.body.appendChild(this._globalDiv);
  26454. this._generateDOMelements();
  26455. window.addEventListener("resize", this._syncPositions);
  26456. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26457. this._syncPositions();
  26458. this._scene.registerBeforeRender(this._syncData);
  26459. this._scene.registerAfterRender(this._syncUI);
  26460. };
  26461. DebugLayer.prototype._clearLabels = function () {
  26462. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26463. for (var index = 0; index < this._scene.meshes.length; index++) {
  26464. var mesh = this._scene.meshes[index];
  26465. mesh.renderOverlay = false;
  26466. }
  26467. };
  26468. DebugLayer.prototype._generateheader = function (root, text) {
  26469. var header = document.createElement("div");
  26470. header.innerHTML = text + "&nbsp;";
  26471. header.style.textAlign = "right";
  26472. header.style.width = "100%";
  26473. header.style.color = "white";
  26474. header.style.backgroundColor = "Black";
  26475. header.style.padding = "5px 5px 4px 0px";
  26476. header.style.marginLeft = "-5px";
  26477. header.style.fontWeight = "bold";
  26478. root.appendChild(header);
  26479. };
  26480. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26481. var label = document.createElement("label");
  26482. label.innerHTML = title;
  26483. label.style.color = color;
  26484. root.appendChild(label);
  26485. root.appendChild(document.createElement("br"));
  26486. };
  26487. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26488. if (tag === void 0) { tag = null; }
  26489. var label = document.createElement("label");
  26490. var boundingBoxesCheckbox = document.createElement("input");
  26491. boundingBoxesCheckbox.type = "checkbox";
  26492. boundingBoxesCheckbox.checked = initialState;
  26493. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26494. task(evt.target, tag);
  26495. });
  26496. label.appendChild(boundingBoxesCheckbox);
  26497. var container = document.createElement("span");
  26498. var leftPart = document.createElement("span");
  26499. var rightPart = document.createElement("span");
  26500. rightPart.style.cssFloat = "right";
  26501. leftPart.innerHTML = leftTitle;
  26502. rightPart.innerHTML = rightTitle;
  26503. rightPart.style.fontSize = "12px";
  26504. rightPart.style.maxWidth = "200px";
  26505. container.appendChild(leftPart);
  26506. container.appendChild(rightPart);
  26507. label.appendChild(container);
  26508. root.appendChild(label);
  26509. root.appendChild(document.createElement("br"));
  26510. };
  26511. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26512. if (tag === void 0) { tag = null; }
  26513. var label = document.createElement("label");
  26514. var checkBox = document.createElement("input");
  26515. checkBox.type = "checkbox";
  26516. checkBox.checked = initialState;
  26517. checkBox.addEventListener("change", function (evt) {
  26518. task(evt.target, tag);
  26519. });
  26520. label.appendChild(checkBox);
  26521. label.appendChild(document.createTextNode(title));
  26522. root.appendChild(label);
  26523. root.appendChild(document.createElement("br"));
  26524. };
  26525. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  26526. if (tag === void 0) { tag = null; }
  26527. var button = document.createElement("button");
  26528. button.innerHTML = title;
  26529. button.style.height = "24px";
  26530. button.style.color = "#444444";
  26531. button.style.border = "1px solid white";
  26532. button.className = "debugLayerButton";
  26533. button.addEventListener("click", function (evt) {
  26534. task(evt.target, tag);
  26535. });
  26536. root.appendChild(button);
  26537. root.appendChild(document.createElement("br"));
  26538. };
  26539. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26540. if (tag === void 0) { tag = null; }
  26541. var label = document.createElement("label");
  26542. var boundingBoxesRadio = document.createElement("input");
  26543. boundingBoxesRadio.type = "radio";
  26544. boundingBoxesRadio.name = name;
  26545. boundingBoxesRadio.checked = initialState;
  26546. boundingBoxesRadio.addEventListener("change", function (evt) {
  26547. task(evt.target, tag);
  26548. });
  26549. label.appendChild(boundingBoxesRadio);
  26550. label.appendChild(document.createTextNode(title));
  26551. root.appendChild(label);
  26552. root.appendChild(document.createElement("br"));
  26553. };
  26554. DebugLayer.prototype._generateDOMelements = function () {
  26555. var _this = this;
  26556. this._globalDiv.id = "DebugLayer";
  26557. this._globalDiv.style.position = "absolute";
  26558. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26559. this._globalDiv.style.fontSize = "14px";
  26560. this._globalDiv.style.color = "white";
  26561. // Drawing canvas
  26562. this._drawingCanvas = document.createElement("canvas");
  26563. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26564. this._drawingCanvas.style.position = "absolute";
  26565. this._drawingCanvas.style.pointerEvents = "none";
  26566. this._drawingContext = this._drawingCanvas.getContext("2d");
  26567. this._globalDiv.appendChild(this._drawingCanvas);
  26568. if (this._showUI) {
  26569. var background = "rgba(128, 128, 128, 0.4)";
  26570. var border = "rgb(180, 180, 180) solid 1px";
  26571. // Stats
  26572. this._statsDiv = document.createElement("div");
  26573. this._statsDiv.id = "DebugLayerStats";
  26574. this._statsDiv.style.border = border;
  26575. this._statsDiv.style.position = "absolute";
  26576. this._statsDiv.style.background = background;
  26577. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26578. this._generateheader(this._statsDiv, "STATISTICS");
  26579. this._statsSubsetDiv = document.createElement("div");
  26580. this._statsSubsetDiv.style.paddingTop = "5px";
  26581. this._statsSubsetDiv.style.paddingBottom = "5px";
  26582. this._statsSubsetDiv.style.overflowY = "auto";
  26583. this._statsDiv.appendChild(this._statsSubsetDiv);
  26584. // Tree
  26585. this._treeDiv = document.createElement("div");
  26586. this._treeDiv.id = "DebugLayerTree";
  26587. this._treeDiv.style.border = border;
  26588. this._treeDiv.style.position = "absolute";
  26589. this._treeDiv.style.background = background;
  26590. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26591. this._treeDiv.style.display = "none";
  26592. this._generateheader(this._treeDiv, "MESHES TREE");
  26593. this._treeSubsetDiv = document.createElement("div");
  26594. this._treeSubsetDiv.style.paddingTop = "5px";
  26595. this._treeSubsetDiv.style.paddingRight = "5px";
  26596. this._treeSubsetDiv.style.overflowY = "auto";
  26597. this._treeSubsetDiv.style.maxHeight = "300px";
  26598. this._treeDiv.appendChild(this._treeSubsetDiv);
  26599. this._needToRefreshMeshesTree = true;
  26600. // Logs
  26601. this._logDiv = document.createElement("div");
  26602. this._logDiv.style.border = border;
  26603. this._logDiv.id = "DebugLayerLogs";
  26604. this._logDiv.style.position = "absolute";
  26605. this._logDiv.style.background = background;
  26606. this._logDiv.style.padding = "0px 0px 0px 5px";
  26607. this._logDiv.style.display = "none";
  26608. this._generateheader(this._logDiv, "LOGS");
  26609. this._logSubsetDiv = document.createElement("div");
  26610. this._logSubsetDiv.style.height = "127px";
  26611. this._logSubsetDiv.style.paddingTop = "5px";
  26612. this._logSubsetDiv.style.overflowY = "auto";
  26613. this._logSubsetDiv.style.fontSize = "12px";
  26614. this._logSubsetDiv.style.fontFamily = "consolas";
  26615. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26616. this._logDiv.appendChild(this._logSubsetDiv);
  26617. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26618. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26619. };
  26620. // Options
  26621. this._optionsDiv = document.createElement("div");
  26622. this._optionsDiv.id = "DebugLayerOptions";
  26623. this._optionsDiv.style.border = border;
  26624. this._optionsDiv.style.position = "absolute";
  26625. this._optionsDiv.style.background = background;
  26626. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26627. this._optionsDiv.style.overflowY = "auto";
  26628. this._generateheader(this._optionsDiv, "OPTIONS");
  26629. this._optionsSubsetDiv = document.createElement("div");
  26630. this._optionsSubsetDiv.style.paddingTop = "5px";
  26631. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26632. this._optionsSubsetDiv.style.overflowY = "auto";
  26633. this._optionsSubsetDiv.style.maxHeight = "200px";
  26634. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26635. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26636. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  26637. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  26638. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26639. _this._displayTree = element.checked;
  26640. _this._needToRefreshMeshesTree = true;
  26641. });
  26642. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26643. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26644. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  26645. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26646. _this._labelsEnabled = element.checked;
  26647. if (!_this._labelsEnabled) {
  26648. _this._clearLabels();
  26649. }
  26650. });
  26651. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26652. if (element.checked) {
  26653. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26654. }
  26655. else {
  26656. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26657. }
  26658. });
  26659. ;
  26660. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26661. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26662. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26663. if (element.checked) {
  26664. _this._scene.forceWireframe = false;
  26665. _this._scene.forcePointsCloud = false;
  26666. }
  26667. });
  26668. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26669. if (element.checked) {
  26670. _this._scene.forceWireframe = true;
  26671. _this._scene.forcePointsCloud = false;
  26672. }
  26673. });
  26674. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26675. if (element.checked) {
  26676. _this._scene.forceWireframe = false;
  26677. _this._scene.forcePointsCloud = true;
  26678. }
  26679. });
  26680. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26681. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26682. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  26683. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  26684. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  26685. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  26686. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  26687. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  26688. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  26689. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  26690. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  26691. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26692. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26693. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  26694. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  26695. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  26696. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  26697. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  26698. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  26699. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  26700. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  26701. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  26702. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  26703. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  26704. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  26705. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  26706. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  26707. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26708. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26709. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  26710. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  26711. if (element.checked) {
  26712. _this._scene.headphone = true;
  26713. }
  26714. });
  26715. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  26716. if (element.checked) {
  26717. _this._scene.headphone = false;
  26718. }
  26719. });
  26720. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  26721. _this._scene.audioEnabled = !element.checked;
  26722. });
  26723. }
  26724. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26725. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  26726. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  26727. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26728. this._globalDiv.appendChild(this._statsDiv);
  26729. this._globalDiv.appendChild(this._logDiv);
  26730. this._globalDiv.appendChild(this._optionsDiv);
  26731. this._globalDiv.appendChild(this._treeDiv);
  26732. }
  26733. };
  26734. DebugLayer.prototype._displayStats = function () {
  26735. var scene = this._scene;
  26736. var engine = scene.getEngine();
  26737. var glInfo = engine.getGlInfo();
  26738. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  26739. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  26740. + "<b>Count</b><br>"
  26741. + "Total meshes: " + scene.meshes.length + "<br>"
  26742. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  26743. + "Total materials: " + scene.materials.length + "<br>"
  26744. + "Total textures: " + scene.textures.length + "<br>"
  26745. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  26746. + "Active indices: " + scene.getActiveIndices() + "<br>"
  26747. + "Active bones: " + scene.getActiveBones() + "<br>"
  26748. + "Active particles: " + scene.getActiveParticles() + "<br>"
  26749. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  26750. + "<b>Duration</b><br>"
  26751. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  26752. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  26753. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  26754. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  26755. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  26756. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  26757. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  26758. + "</div>"
  26759. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  26760. + "<b>Extensions</b><br>"
  26761. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  26762. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  26763. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  26764. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  26765. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  26766. + "<b>Caps.</b><br>"
  26767. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  26768. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  26769. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  26770. + "</div><br>"
  26771. + "<b>Info</b><br>"
  26772. + glInfo.version + "<br>"
  26773. + glInfo.renderer + "<br>";
  26774. if (this.customStatsFunction) {
  26775. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26776. }
  26777. };
  26778. return DebugLayer;
  26779. })();
  26780. BABYLON.DebugLayer = DebugLayer;
  26781. })(BABYLON || (BABYLON = {}));
  26782. var BABYLON;
  26783. (function (BABYLON) {
  26784. var DefaultLoadingScreen = (function () {
  26785. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  26786. var _this = this;
  26787. if (_loadingText === void 0) { _loadingText = ""; }
  26788. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  26789. this._renderingCanvas = _renderingCanvas;
  26790. this._loadingText = _loadingText;
  26791. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  26792. // Resize
  26793. this._resizeLoadingUI = function () {
  26794. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  26795. _this._loadingDiv.style.position = "absolute";
  26796. _this._loadingDiv.style.left = canvasRect.left + "px";
  26797. _this._loadingDiv.style.top = canvasRect.top + "px";
  26798. _this._loadingDiv.style.width = canvasRect.width + "px";
  26799. _this._loadingDiv.style.height = canvasRect.height + "px";
  26800. };
  26801. }
  26802. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  26803. var _this = this;
  26804. this._loadingDiv = document.createElement("div");
  26805. this._loadingDiv.style.opacity = "0";
  26806. this._loadingDiv.style.transition = "opacity 1.5s ease";
  26807. // Loading text
  26808. this._loadingTextDiv = document.createElement("div");
  26809. this._loadingTextDiv.style.position = "absolute";
  26810. this._loadingTextDiv.style.left = "0";
  26811. this._loadingTextDiv.style.top = "50%";
  26812. this._loadingTextDiv.style.marginTop = "80px";
  26813. this._loadingTextDiv.style.width = "100%";
  26814. this._loadingTextDiv.style.height = "20px";
  26815. this._loadingTextDiv.style.fontFamily = "Arial";
  26816. this._loadingTextDiv.style.fontSize = "14px";
  26817. this._loadingTextDiv.style.color = "white";
  26818. this._loadingTextDiv.style.textAlign = "center";
  26819. this._loadingTextDiv.innerHTML = "Loading";
  26820. this._loadingDiv.appendChild(this._loadingTextDiv);
  26821. //set the predefined text
  26822. this._loadingTextDiv.innerHTML = this._loadingText;
  26823. // Loading img
  26824. var imgBack = new Image();
  26825. 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==";
  26826. imgBack.style.position = "absolute";
  26827. imgBack.style.left = "50%";
  26828. imgBack.style.top = "50%";
  26829. imgBack.style.marginLeft = "-50px";
  26830. imgBack.style.marginTop = "-50px";
  26831. imgBack.style.transition = "transform 1.0s ease";
  26832. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  26833. var deg = 360;
  26834. var onTransitionEnd = function () {
  26835. deg += 360;
  26836. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  26837. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  26838. };
  26839. imgBack.addEventListener("transitionend", onTransitionEnd);
  26840. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  26841. this._loadingDiv.appendChild(imgBack);
  26842. // front image
  26843. var imgFront = new Image();
  26844. 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=";
  26845. imgFront.style.position = "absolute";
  26846. imgFront.style.left = "50%";
  26847. imgFront.style.top = "50%";
  26848. imgFront.style.marginLeft = "-50px";
  26849. imgFront.style.marginTop = "-50px";
  26850. this._loadingDiv.appendChild(imgFront);
  26851. this._resizeLoadingUI();
  26852. window.addEventListener("resize", this._resizeLoadingUI);
  26853. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  26854. document.body.appendChild(this._loadingDiv);
  26855. setTimeout(function () {
  26856. _this._loadingDiv.style.opacity = "1";
  26857. imgBack.style.transform = "rotateZ(360deg)";
  26858. imgBack.style.webkitTransform = "rotateZ(360deg)";
  26859. }, 0);
  26860. };
  26861. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  26862. var _this = this;
  26863. if (!this._loadingDiv) {
  26864. return;
  26865. }
  26866. var onTransitionEnd = function () {
  26867. if (!_this._loadingDiv) {
  26868. return;
  26869. }
  26870. document.body.removeChild(_this._loadingDiv);
  26871. window.removeEventListener("resize", _this._resizeLoadingUI);
  26872. _this._loadingDiv = null;
  26873. };
  26874. this._loadingDiv.style.opacity = "0";
  26875. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  26876. };
  26877. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  26878. set: function (text) {
  26879. this._loadingText = text;
  26880. if (this._loadingTextDiv) {
  26881. this._loadingTextDiv.innerHTML = this._loadingText;
  26882. }
  26883. },
  26884. enumerable: true,
  26885. configurable: true
  26886. });
  26887. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  26888. get: function () {
  26889. return this._loadingDivBackgroundColor;
  26890. },
  26891. set: function (color) {
  26892. this._loadingDivBackgroundColor = color;
  26893. if (!this._loadingDiv) {
  26894. return;
  26895. }
  26896. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  26897. },
  26898. enumerable: true,
  26899. configurable: true
  26900. });
  26901. return DefaultLoadingScreen;
  26902. })();
  26903. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  26904. })(BABYLON || (BABYLON = {}));
  26905. var BABYLON;
  26906. (function (BABYLON) {
  26907. var AudioEngine = (function () {
  26908. function AudioEngine() {
  26909. this._audioContext = null;
  26910. this._audioContextInitialized = false;
  26911. this.canUseWebAudio = false;
  26912. this.WarnedWebAudioUnsupported = false;
  26913. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  26914. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  26915. this.canUseWebAudio = true;
  26916. }
  26917. }
  26918. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  26919. get: function () {
  26920. if (!this._audioContextInitialized) {
  26921. this._initializeAudioContext();
  26922. }
  26923. return this._audioContext;
  26924. },
  26925. enumerable: true,
  26926. configurable: true
  26927. });
  26928. AudioEngine.prototype._initializeAudioContext = function () {
  26929. try {
  26930. if (this.canUseWebAudio) {
  26931. this._audioContext = new AudioContext();
  26932. // create a global volume gain node
  26933. this.masterGain = this._audioContext.createGain();
  26934. this.masterGain.gain.value = 1;
  26935. this.masterGain.connect(this._audioContext.destination);
  26936. this._audioContextInitialized = true;
  26937. }
  26938. }
  26939. catch (e) {
  26940. this.canUseWebAudio = false;
  26941. BABYLON.Tools.Error("Web Audio: " + e.message);
  26942. }
  26943. };
  26944. AudioEngine.prototype.dispose = function () {
  26945. if (this.canUseWebAudio && this._audioContextInitialized) {
  26946. if (this._connectedAnalyser) {
  26947. this._connectedAnalyser.stopDebugCanvas();
  26948. this._connectedAnalyser.dispose();
  26949. this.masterGain.disconnect();
  26950. this.masterGain.connect(this._audioContext.destination);
  26951. this._connectedAnalyser = null;
  26952. }
  26953. this.masterGain.gain.value = 1;
  26954. }
  26955. this.WarnedWebAudioUnsupported = false;
  26956. };
  26957. AudioEngine.prototype.getGlobalVolume = function () {
  26958. if (this.canUseWebAudio && this._audioContextInitialized) {
  26959. return this.masterGain.gain.value;
  26960. }
  26961. else {
  26962. return -1;
  26963. }
  26964. };
  26965. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26966. if (this.canUseWebAudio && this._audioContextInitialized) {
  26967. this.masterGain.gain.value = newVolume;
  26968. }
  26969. };
  26970. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26971. if (this._connectedAnalyser) {
  26972. this._connectedAnalyser.stopDebugCanvas();
  26973. }
  26974. if (this.canUseWebAudio && this._audioContextInitialized) {
  26975. this._connectedAnalyser = analyser;
  26976. this.masterGain.disconnect();
  26977. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  26978. }
  26979. };
  26980. return AudioEngine;
  26981. })();
  26982. BABYLON.AudioEngine = AudioEngine;
  26983. })(BABYLON || (BABYLON = {}));
  26984. var BABYLON;
  26985. (function (BABYLON) {
  26986. var Sound = (function () {
  26987. /**
  26988. * Create a sound and attach it to a scene
  26989. * @param name Name of your sound
  26990. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26991. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26992. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26993. */
  26994. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26995. var _this = this;
  26996. this.autoplay = false;
  26997. this.loop = false;
  26998. this.useCustomAttenuation = false;
  26999. this.spatialSound = false;
  27000. this.refDistance = 1;
  27001. this.rolloffFactor = 1;
  27002. this.maxDistance = 100;
  27003. this.distanceModel = "linear";
  27004. this._panningModel = "equalpower";
  27005. this._playbackRate = 1;
  27006. this._startTime = 0;
  27007. this._startOffset = 0;
  27008. this._position = BABYLON.Vector3.Zero();
  27009. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27010. this._volume = 1;
  27011. this._isLoaded = false;
  27012. this._isReadyToPlay = false;
  27013. this.isPlaying = false;
  27014. this.isPaused = false;
  27015. this._isDirectional = false;
  27016. // Used if you'd like to create a directional sound.
  27017. // If not set, the sound will be omnidirectional
  27018. this._coneInnerAngle = 360;
  27019. this._coneOuterAngle = 360;
  27020. this._coneOuterGain = 0;
  27021. this._isOutputConnected = false;
  27022. this.name = name;
  27023. this._scene = scene;
  27024. this._readyToPlayCallback = readyToPlayCallback;
  27025. // Default custom attenuation function is a linear attenuation
  27026. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  27027. if (currentDistance < maxDistance) {
  27028. return currentVolume * (1 - currentDistance / maxDistance);
  27029. }
  27030. else {
  27031. return 0;
  27032. }
  27033. };
  27034. if (options) {
  27035. this.autoplay = options.autoplay || false;
  27036. this.loop = options.loop || false;
  27037. // if volume === 0, we need another way to check this option
  27038. if (options.volume !== undefined) {
  27039. this._volume = options.volume;
  27040. }
  27041. this.spatialSound = options.spatialSound || false;
  27042. this.maxDistance = options.maxDistance || 100;
  27043. this.useCustomAttenuation = options.useCustomAttenuation || false;
  27044. this.rolloffFactor = options.rolloffFactor || 1;
  27045. this.refDistance = options.refDistance || 1;
  27046. this.distanceModel = options.distanceModel || "linear";
  27047. this._playbackRate = options.playbackRate || 1;
  27048. }
  27049. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27050. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  27051. this._soundGain.gain.value = this._volume;
  27052. this._inputAudioNode = this._soundGain;
  27053. this._ouputAudioNode = this._soundGain;
  27054. if (this.spatialSound) {
  27055. this._createSpatialParameters();
  27056. }
  27057. this._scene.mainSoundTrack.AddSound(this);
  27058. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  27059. if (urlOrArrayBuffer) {
  27060. // If it's an URL
  27061. if (typeof (urlOrArrayBuffer) === "string") {
  27062. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  27063. }
  27064. else {
  27065. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  27066. this._soundLoaded(urlOrArrayBuffer);
  27067. }
  27068. else {
  27069. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  27070. }
  27071. }
  27072. }
  27073. }
  27074. else {
  27075. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  27076. this._scene.mainSoundTrack.AddSound(this);
  27077. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  27078. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  27079. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  27080. }
  27081. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  27082. if (this._readyToPlayCallback) {
  27083. window.setTimeout(function () {
  27084. _this._readyToPlayCallback();
  27085. }, 1000);
  27086. }
  27087. }
  27088. }
  27089. Sound.prototype.dispose = function () {
  27090. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27091. if (this.isPlaying) {
  27092. this.stop();
  27093. }
  27094. this._isReadyToPlay = false;
  27095. if (this.soundTrackId === -1) {
  27096. this._scene.mainSoundTrack.RemoveSound(this);
  27097. }
  27098. else {
  27099. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27100. }
  27101. if (this._soundGain) {
  27102. this._soundGain.disconnect();
  27103. this._soundGain = null;
  27104. }
  27105. if (this._soundPanner) {
  27106. this._soundPanner.disconnect();
  27107. this._soundPanner = null;
  27108. }
  27109. if (this._soundSource) {
  27110. this._soundSource.disconnect();
  27111. this._soundSource = null;
  27112. }
  27113. this._audioBuffer = null;
  27114. if (this._connectedMesh) {
  27115. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27116. this._connectedMesh = null;
  27117. }
  27118. }
  27119. };
  27120. Sound.prototype._soundLoaded = function (audioData) {
  27121. var _this = this;
  27122. this._isLoaded = true;
  27123. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27124. _this._audioBuffer = buffer;
  27125. _this._isReadyToPlay = true;
  27126. if (_this.autoplay) {
  27127. _this.play();
  27128. }
  27129. if (_this._readyToPlayCallback) {
  27130. _this._readyToPlayCallback();
  27131. }
  27132. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  27133. };
  27134. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27135. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27136. this._audioBuffer = audioBuffer;
  27137. this._isReadyToPlay = true;
  27138. }
  27139. };
  27140. Sound.prototype.updateOptions = function (options) {
  27141. if (options) {
  27142. this.loop = options.loop || this.loop;
  27143. this.maxDistance = options.maxDistance || this.maxDistance;
  27144. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27145. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27146. this.refDistance = options.refDistance || this.refDistance;
  27147. this.distanceModel = options.distanceModel || this.distanceModel;
  27148. this._playbackRate = options.playbackRate || this._playbackRate;
  27149. this._updateSpatialParameters();
  27150. if (this.isPlaying) {
  27151. this._soundSource.playbackRate.value = this._playbackRate;
  27152. }
  27153. }
  27154. };
  27155. Sound.prototype._createSpatialParameters = function () {
  27156. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27157. if (this._scene.headphone) {
  27158. this._panningModel = "HRTF";
  27159. }
  27160. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27161. this._updateSpatialParameters();
  27162. this._soundPanner.connect(this._ouputAudioNode);
  27163. this._inputAudioNode = this._soundPanner;
  27164. }
  27165. };
  27166. Sound.prototype._updateSpatialParameters = function () {
  27167. if (this.spatialSound) {
  27168. if (this.useCustomAttenuation) {
  27169. // Tricks to disable in a way embedded Web Audio attenuation
  27170. this._soundPanner.distanceModel = "linear";
  27171. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27172. this._soundPanner.refDistance = 1;
  27173. this._soundPanner.rolloffFactor = 1;
  27174. this._soundPanner.panningModel = this._panningModel;
  27175. }
  27176. else {
  27177. this._soundPanner.distanceModel = this.distanceModel;
  27178. this._soundPanner.maxDistance = this.maxDistance;
  27179. this._soundPanner.refDistance = this.refDistance;
  27180. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27181. this._soundPanner.panningModel = this._panningModel;
  27182. }
  27183. }
  27184. };
  27185. Sound.prototype.switchPanningModelToHRTF = function () {
  27186. this._panningModel = "HRTF";
  27187. this._switchPanningModel();
  27188. };
  27189. Sound.prototype.switchPanningModelToEqualPower = function () {
  27190. this._panningModel = "equalpower";
  27191. this._switchPanningModel();
  27192. };
  27193. Sound.prototype._switchPanningModel = function () {
  27194. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27195. this._soundPanner.panningModel = this._panningModel;
  27196. }
  27197. };
  27198. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27199. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27200. if (this._isOutputConnected) {
  27201. this._ouputAudioNode.disconnect();
  27202. }
  27203. this._ouputAudioNode.connect(soundTrackAudioNode);
  27204. this._isOutputConnected = true;
  27205. }
  27206. };
  27207. /**
  27208. * Transform this sound into a directional source
  27209. * @param coneInnerAngle Size of the inner cone in degree
  27210. * @param coneOuterAngle Size of the outer cone in degree
  27211. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27212. */
  27213. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27214. if (coneOuterAngle < coneInnerAngle) {
  27215. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27216. return;
  27217. }
  27218. this._coneInnerAngle = coneInnerAngle;
  27219. this._coneOuterAngle = coneOuterAngle;
  27220. this._coneOuterGain = coneOuterGain;
  27221. this._isDirectional = true;
  27222. if (this.isPlaying && this.loop) {
  27223. this.stop();
  27224. this.play();
  27225. }
  27226. };
  27227. Sound.prototype.setPosition = function (newPosition) {
  27228. this._position = newPosition;
  27229. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27230. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27231. }
  27232. };
  27233. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27234. this._localDirection = newLocalDirection;
  27235. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27236. this._updateDirection();
  27237. }
  27238. };
  27239. Sound.prototype._updateDirection = function () {
  27240. var mat = this._connectedMesh.getWorldMatrix();
  27241. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27242. direction.normalize();
  27243. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27244. };
  27245. Sound.prototype.updateDistanceFromListener = function () {
  27246. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27247. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27248. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27249. }
  27250. };
  27251. Sound.prototype.setAttenuationFunction = function (callback) {
  27252. this._customAttenuationFunction = callback;
  27253. };
  27254. /**
  27255. * Play the sound
  27256. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27257. */
  27258. Sound.prototype.play = function (time) {
  27259. var _this = this;
  27260. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27261. try {
  27262. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27263. if (!this._soundSource) {
  27264. if (this.spatialSound) {
  27265. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27266. if (this._isDirectional) {
  27267. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27268. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27269. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27270. if (this._connectedMesh) {
  27271. this._updateDirection();
  27272. }
  27273. else {
  27274. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27275. }
  27276. }
  27277. }
  27278. }
  27279. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27280. this._soundSource.buffer = this._audioBuffer;
  27281. this._soundSource.connect(this._inputAudioNode);
  27282. this._soundSource.loop = this.loop;
  27283. this._soundSource.playbackRate.value = this._playbackRate;
  27284. this._startTime = startTime;
  27285. this._soundSource.onended = function () { _this._onended(); };
  27286. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27287. this.isPlaying = true;
  27288. this.isPaused = false;
  27289. }
  27290. catch (ex) {
  27291. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27292. }
  27293. }
  27294. };
  27295. Sound.prototype._onended = function () {
  27296. this.isPlaying = false;
  27297. if (this.onended) {
  27298. this.onended();
  27299. }
  27300. };
  27301. /**
  27302. * Stop the sound
  27303. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27304. */
  27305. Sound.prototype.stop = function (time) {
  27306. if (this.isPlaying) {
  27307. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27308. this._soundSource.stop(stopTime);
  27309. this.isPlaying = false;
  27310. }
  27311. };
  27312. Sound.prototype.pause = function () {
  27313. if (this.isPlaying) {
  27314. this.stop(0);
  27315. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27316. this.isPaused = true;
  27317. }
  27318. };
  27319. Sound.prototype.setVolume = function (newVolume, time) {
  27320. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27321. if (time) {
  27322. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27323. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27324. }
  27325. else {
  27326. this._soundGain.gain.value = newVolume;
  27327. }
  27328. }
  27329. this._volume = newVolume;
  27330. };
  27331. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27332. this._playbackRate = newPlaybackRate;
  27333. if (this.isPlaying) {
  27334. this._soundSource.playbackRate.value = this._playbackRate;
  27335. }
  27336. };
  27337. Sound.prototype.getVolume = function () {
  27338. return this._volume;
  27339. };
  27340. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27341. var _this = this;
  27342. this._connectedMesh = meshToConnectTo;
  27343. if (!this.spatialSound) {
  27344. this.spatialSound = true;
  27345. this._createSpatialParameters();
  27346. if (this.isPlaying && this.loop) {
  27347. this.stop();
  27348. this.play();
  27349. }
  27350. }
  27351. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27352. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27353. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27354. };
  27355. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27356. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27357. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27358. this._updateDirection();
  27359. }
  27360. };
  27361. return Sound;
  27362. })();
  27363. BABYLON.Sound = Sound;
  27364. })(BABYLON || (BABYLON = {}));
  27365. var BABYLON;
  27366. (function (BABYLON) {
  27367. var SoundTrack = (function () {
  27368. function SoundTrack(scene, options) {
  27369. this.id = -1;
  27370. this._isMainTrack = false;
  27371. this._scene = scene;
  27372. this._audioEngine = BABYLON.Engine.audioEngine;
  27373. this.soundCollection = new Array();
  27374. if (this._audioEngine.canUseWebAudio) {
  27375. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  27376. this._outputAudioNode.connect(this._audioEngine.masterGain);
  27377. if (options) {
  27378. if (options.volume) {
  27379. this._outputAudioNode.gain.value = options.volume;
  27380. }
  27381. if (options.mainTrack) {
  27382. this._isMainTrack = options.mainTrack;
  27383. }
  27384. }
  27385. }
  27386. if (!this._isMainTrack) {
  27387. this._scene.soundTracks.push(this);
  27388. this.id = this._scene.soundTracks.length - 1;
  27389. }
  27390. }
  27391. SoundTrack.prototype.dispose = function () {
  27392. if (this._audioEngine.canUseWebAudio) {
  27393. if (this._connectedAnalyser) {
  27394. this._connectedAnalyser.stopDebugCanvas();
  27395. }
  27396. while (this.soundCollection.length) {
  27397. this.soundCollection[0].dispose();
  27398. }
  27399. if (this._outputAudioNode) {
  27400. this._outputAudioNode.disconnect();
  27401. }
  27402. this._outputAudioNode = null;
  27403. }
  27404. };
  27405. SoundTrack.prototype.AddSound = function (sound) {
  27406. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27407. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  27408. }
  27409. if (sound.soundTrackId) {
  27410. if (sound.soundTrackId === -1) {
  27411. this._scene.mainSoundTrack.RemoveSound(sound);
  27412. }
  27413. else {
  27414. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27415. }
  27416. }
  27417. this.soundCollection.push(sound);
  27418. sound.soundTrackId = this.id;
  27419. };
  27420. SoundTrack.prototype.RemoveSound = function (sound) {
  27421. var index = this.soundCollection.indexOf(sound);
  27422. if (index !== -1) {
  27423. this.soundCollection.splice(index, 1);
  27424. }
  27425. };
  27426. SoundTrack.prototype.setVolume = function (newVolume) {
  27427. if (this._audioEngine.canUseWebAudio) {
  27428. this._outputAudioNode.gain.value = newVolume;
  27429. }
  27430. };
  27431. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27432. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27433. for (var i = 0; i < this.soundCollection.length; i++) {
  27434. this.soundCollection[i].switchPanningModelToHRTF();
  27435. }
  27436. }
  27437. };
  27438. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27439. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27440. for (var i = 0; i < this.soundCollection.length; i++) {
  27441. this.soundCollection[i].switchPanningModelToEqualPower();
  27442. }
  27443. }
  27444. };
  27445. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27446. if (this._connectedAnalyser) {
  27447. this._connectedAnalyser.stopDebugCanvas();
  27448. }
  27449. this._connectedAnalyser = analyser;
  27450. if (this._audioEngine.canUseWebAudio) {
  27451. this._outputAudioNode.disconnect();
  27452. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  27453. }
  27454. };
  27455. return SoundTrack;
  27456. })();
  27457. BABYLON.SoundTrack = SoundTrack;
  27458. })(BABYLON || (BABYLON = {}));
  27459. var BABYLON;
  27460. (function (BABYLON) {
  27461. var ShaderMaterial = (function (_super) {
  27462. __extends(ShaderMaterial, _super);
  27463. function ShaderMaterial(name, scene, shaderPath, options) {
  27464. _super.call(this, name, scene);
  27465. this._textures = new Array();
  27466. this._floats = new Array();
  27467. this._floatsArrays = {};
  27468. this._colors3 = new Array();
  27469. this._colors4 = new Array();
  27470. this._vectors2 = new Array();
  27471. this._vectors3 = new Array();
  27472. this._vectors4 = new Array();
  27473. this._matrices = new Array();
  27474. this._matrices3x3 = new Array();
  27475. this._matrices2x2 = new Array();
  27476. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  27477. this._shaderPath = shaderPath;
  27478. options.needAlphaBlending = options.needAlphaBlending || false;
  27479. options.needAlphaTesting = options.needAlphaTesting || false;
  27480. options.attributes = options.attributes || ["position", "normal", "uv"];
  27481. options.uniforms = options.uniforms || ["worldViewProjection"];
  27482. options.samplers = options.samplers || [];
  27483. options.defines = options.defines || [];
  27484. this._options = options;
  27485. }
  27486. ShaderMaterial.prototype.needAlphaBlending = function () {
  27487. return this._options.needAlphaBlending;
  27488. };
  27489. ShaderMaterial.prototype.needAlphaTesting = function () {
  27490. return this._options.needAlphaTesting;
  27491. };
  27492. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  27493. if (this._options.uniforms.indexOf(uniformName) === -1) {
  27494. this._options.uniforms.push(uniformName);
  27495. }
  27496. };
  27497. ShaderMaterial.prototype.setTexture = function (name, texture) {
  27498. if (this._options.samplers.indexOf(name) === -1) {
  27499. this._options.samplers.push(name);
  27500. }
  27501. this._textures[name] = texture;
  27502. return this;
  27503. };
  27504. ShaderMaterial.prototype.setFloat = function (name, value) {
  27505. this._checkUniform(name);
  27506. this._floats[name] = value;
  27507. return this;
  27508. };
  27509. ShaderMaterial.prototype.setFloats = function (name, value) {
  27510. this._checkUniform(name);
  27511. this._floatsArrays[name] = value;
  27512. return this;
  27513. };
  27514. ShaderMaterial.prototype.setColor3 = function (name, value) {
  27515. this._checkUniform(name);
  27516. this._colors3[name] = value;
  27517. return this;
  27518. };
  27519. ShaderMaterial.prototype.setColor4 = function (name, value) {
  27520. this._checkUniform(name);
  27521. this._colors4[name] = value;
  27522. return this;
  27523. };
  27524. ShaderMaterial.prototype.setVector2 = function (name, value) {
  27525. this._checkUniform(name);
  27526. this._vectors2[name] = value;
  27527. return this;
  27528. };
  27529. ShaderMaterial.prototype.setVector3 = function (name, value) {
  27530. this._checkUniform(name);
  27531. this._vectors3[name] = value;
  27532. return this;
  27533. };
  27534. ShaderMaterial.prototype.setVector4 = function (name, value) {
  27535. this._checkUniform(name);
  27536. this._vectors4[name] = value;
  27537. return this;
  27538. };
  27539. ShaderMaterial.prototype.setMatrix = function (name, value) {
  27540. this._checkUniform(name);
  27541. this._matrices[name] = value;
  27542. return this;
  27543. };
  27544. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  27545. this._checkUniform(name);
  27546. this._matrices3x3[name] = value;
  27547. return this;
  27548. };
  27549. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  27550. this._checkUniform(name);
  27551. this._matrices2x2[name] = value;
  27552. return this;
  27553. };
  27554. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  27555. var scene = this.getScene();
  27556. var engine = scene.getEngine();
  27557. if (!this.checkReadyOnEveryCall) {
  27558. if (this._renderId === scene.getRenderId()) {
  27559. return true;
  27560. }
  27561. }
  27562. // Instances
  27563. var defines = [];
  27564. var fallbacks = new BABYLON.EffectFallbacks();
  27565. if (useInstances) {
  27566. defines.push("#define INSTANCES");
  27567. }
  27568. for (var index = 0; index < this._options.defines.length; index++) {
  27569. defines.push(this._options.defines[index]);
  27570. }
  27571. // Bones
  27572. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27573. defines.push("#define BONES");
  27574. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27575. defines.push("#define BONES4");
  27576. fallbacks.addFallback(0, "BONES4");
  27577. }
  27578. // Alpha test
  27579. if (engine.getAlphaTesting()) {
  27580. defines.push("#define ALPHATEST");
  27581. }
  27582. var previousEffect = this._effect;
  27583. var join = defines.join("\n");
  27584. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  27585. if (!this._effect.isReady()) {
  27586. return false;
  27587. }
  27588. if (previousEffect !== this._effect) {
  27589. scene.resetCachedMaterial();
  27590. }
  27591. this._renderId = scene.getRenderId();
  27592. return true;
  27593. };
  27594. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27595. var scene = this.getScene();
  27596. if (this._options.uniforms.indexOf("world") !== -1) {
  27597. this._effect.setMatrix("world", world);
  27598. }
  27599. if (this._options.uniforms.indexOf("worldView") !== -1) {
  27600. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  27601. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  27602. }
  27603. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  27604. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  27605. }
  27606. };
  27607. ShaderMaterial.prototype.bind = function (world, mesh) {
  27608. // Std values
  27609. this.bindOnlyWorldMatrix(world);
  27610. if (this.getScene().getCachedMaterial() !== this) {
  27611. if (this._options.uniforms.indexOf("view") !== -1) {
  27612. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  27613. }
  27614. if (this._options.uniforms.indexOf("projection") !== -1) {
  27615. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  27616. }
  27617. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  27618. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27619. }
  27620. // Bones
  27621. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27622. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27623. }
  27624. // Texture
  27625. for (var name in this._textures) {
  27626. this._effect.setTexture(name, this._textures[name]);
  27627. }
  27628. // Float
  27629. for (name in this._floats) {
  27630. this._effect.setFloat(name, this._floats[name]);
  27631. }
  27632. // Float s
  27633. for (name in this._floatsArrays) {
  27634. this._effect.setArray(name, this._floatsArrays[name]);
  27635. }
  27636. // Color3
  27637. for (name in this._colors3) {
  27638. this._effect.setColor3(name, this._colors3[name]);
  27639. }
  27640. // Color4
  27641. for (name in this._colors4) {
  27642. var color = this._colors4[name];
  27643. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27644. }
  27645. // Vector2
  27646. for (name in this._vectors2) {
  27647. this._effect.setVector2(name, this._vectors2[name]);
  27648. }
  27649. // Vector3
  27650. for (name in this._vectors3) {
  27651. this._effect.setVector3(name, this._vectors3[name]);
  27652. }
  27653. // Vector4
  27654. for (name in this._vectors4) {
  27655. this._effect.setVector4(name, this._vectors4[name]);
  27656. }
  27657. // Matrix
  27658. for (name in this._matrices) {
  27659. this._effect.setMatrix(name, this._matrices[name]);
  27660. }
  27661. // Matrix 3x3
  27662. for (name in this._matrices3x3) {
  27663. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  27664. }
  27665. // Matrix 2x2
  27666. for (name in this._matrices2x2) {
  27667. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  27668. }
  27669. }
  27670. _super.prototype.bind.call(this, world, mesh);
  27671. };
  27672. ShaderMaterial.prototype.clone = function (name) {
  27673. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  27674. return newShaderMaterial;
  27675. };
  27676. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  27677. for (var name in this._textures) {
  27678. this._textures[name].dispose();
  27679. }
  27680. this._textures = [];
  27681. _super.prototype.dispose.call(this, forceDisposeEffect);
  27682. };
  27683. return ShaderMaterial;
  27684. })(BABYLON.Material);
  27685. BABYLON.ShaderMaterial = ShaderMaterial;
  27686. })(BABYLON || (BABYLON = {}));
  27687. var BABYLON;
  27688. (function (BABYLON) {
  27689. var Internals;
  27690. (function (Internals) {
  27691. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  27692. // All values and structures referenced from:
  27693. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  27694. var DDS_MAGIC = 0x20534444;
  27695. 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;
  27696. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  27697. 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;
  27698. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  27699. function FourCCToInt32(value) {
  27700. return value.charCodeAt(0) +
  27701. (value.charCodeAt(1) << 8) +
  27702. (value.charCodeAt(2) << 16) +
  27703. (value.charCodeAt(3) << 24);
  27704. }
  27705. function Int32ToFourCC(value) {
  27706. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  27707. }
  27708. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  27709. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  27710. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  27711. var headerLengthInt = 31; // The header length in 32 bit ints
  27712. // Offsets into the header array
  27713. var off_magic = 0;
  27714. var off_size = 1;
  27715. var off_flags = 2;
  27716. var off_height = 3;
  27717. var off_width = 4;
  27718. var off_mipmapCount = 7;
  27719. var off_pfFlags = 20;
  27720. var off_pfFourCC = 21;
  27721. var off_RGBbpp = 22;
  27722. var off_RMask = 23;
  27723. var off_GMask = 24;
  27724. var off_BMask = 25;
  27725. var off_AMask = 26;
  27726. var off_caps1 = 27;
  27727. var off_caps2 = 28;
  27728. ;
  27729. var DDSTools = (function () {
  27730. function DDSTools() {
  27731. }
  27732. DDSTools.GetDDSInfo = function (arrayBuffer) {
  27733. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  27734. var mipmapCount = 1;
  27735. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  27736. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27737. }
  27738. return {
  27739. width: header[off_width],
  27740. height: header[off_height],
  27741. mipmapCount: mipmapCount,
  27742. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  27743. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  27744. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  27745. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  27746. };
  27747. };
  27748. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27749. var byteArray = new Uint8Array(dataLength);
  27750. var srcData = new Uint8Array(arrayBuffer);
  27751. var index = 0;
  27752. for (var y = height - 1; y >= 0; y--) {
  27753. for (var x = 0; x < width; x++) {
  27754. var srcPos = dataOffset + (x + y * width) * 4;
  27755. byteArray[index + 2] = srcData[srcPos];
  27756. byteArray[index + 1] = srcData[srcPos + 1];
  27757. byteArray[index] = srcData[srcPos + 2];
  27758. byteArray[index + 3] = srcData[srcPos + 3];
  27759. index += 4;
  27760. }
  27761. }
  27762. return byteArray;
  27763. };
  27764. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27765. var byteArray = new Uint8Array(dataLength);
  27766. var srcData = new Uint8Array(arrayBuffer);
  27767. var index = 0;
  27768. for (var y = height - 1; y >= 0; y--) {
  27769. for (var x = 0; x < width; x++) {
  27770. var srcPos = dataOffset + (x + y * width) * 3;
  27771. byteArray[index + 2] = srcData[srcPos];
  27772. byteArray[index + 1] = srcData[srcPos + 1];
  27773. byteArray[index] = srcData[srcPos + 2];
  27774. index += 3;
  27775. }
  27776. }
  27777. return byteArray;
  27778. };
  27779. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27780. var byteArray = new Uint8Array(dataLength);
  27781. var srcData = new Uint8Array(arrayBuffer);
  27782. var index = 0;
  27783. for (var y = height - 1; y >= 0; y--) {
  27784. for (var x = 0; x < width; x++) {
  27785. var srcPos = dataOffset + (x + y * width);
  27786. byteArray[index] = srcData[srcPos];
  27787. index++;
  27788. }
  27789. }
  27790. return byteArray;
  27791. };
  27792. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  27793. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  27794. if (header[off_magic] != DDS_MAGIC) {
  27795. BABYLON.Tools.Error("Invalid magic number in DDS header");
  27796. return;
  27797. }
  27798. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  27799. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  27800. return;
  27801. }
  27802. if (info.isFourCC) {
  27803. fourCC = header[off_pfFourCC];
  27804. switch (fourCC) {
  27805. case FOURCC_DXT1:
  27806. blockBytes = 8;
  27807. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  27808. break;
  27809. case FOURCC_DXT3:
  27810. blockBytes = 16;
  27811. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  27812. break;
  27813. case FOURCC_DXT5:
  27814. blockBytes = 16;
  27815. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  27816. break;
  27817. default:
  27818. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  27819. return;
  27820. }
  27821. }
  27822. mipmapCount = 1;
  27823. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  27824. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27825. }
  27826. var bpp = header[off_RGBbpp];
  27827. for (var face = 0; face < faces; face++) {
  27828. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  27829. width = header[off_width];
  27830. height = header[off_height];
  27831. dataOffset = header[off_size] + 4;
  27832. for (i = 0; i < mipmapCount; ++i) {
  27833. if (info.isRGB) {
  27834. if (bpp === 24) {
  27835. dataLength = width * height * 3;
  27836. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27837. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  27838. }
  27839. else {
  27840. dataLength = width * height * 4;
  27841. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27842. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  27843. }
  27844. }
  27845. else if (info.isLuminance) {
  27846. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  27847. var unpaddedRowSize = width;
  27848. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  27849. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  27850. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27851. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  27852. }
  27853. else {
  27854. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  27855. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  27856. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  27857. }
  27858. dataOffset += dataLength;
  27859. width *= 0.5;
  27860. height *= 0.5;
  27861. width = Math.max(1.0, width);
  27862. height = Math.max(1.0, height);
  27863. }
  27864. }
  27865. };
  27866. return DDSTools;
  27867. })();
  27868. Internals.DDSTools = DDSTools;
  27869. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27870. })(BABYLON || (BABYLON = {}));
  27871. var BABYLON;
  27872. (function (BABYLON) {
  27873. var CannonJSPlugin = (function () {
  27874. function CannonJSPlugin() {
  27875. this._registeredMeshes = [];
  27876. this._physicsMaterials = [];
  27877. this.updateBodyPosition = function (mesh) {
  27878. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27879. var registeredMesh = this._registeredMeshes[index];
  27880. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  27881. var body = registeredMesh.body;
  27882. var center = mesh.getBoundingInfo().boundingBox.center;
  27883. body.position.set(center.x, center.y, center.z);
  27884. body.quaternion.x = mesh.rotationQuaternion.x;
  27885. body.quaternion.z = mesh.rotationQuaternion.z;
  27886. body.quaternion.y = mesh.rotationQuaternion.y;
  27887. body.quaternion.w = mesh.rotationQuaternion.w;
  27888. return;
  27889. }
  27890. }
  27891. };
  27892. }
  27893. CannonJSPlugin.prototype.initialize = function (iterations) {
  27894. if (iterations === void 0) { iterations = 10; }
  27895. this._world = new CANNON.World();
  27896. this._world.broadphase = new CANNON.NaiveBroadphase();
  27897. this._world.solver.iterations = iterations;
  27898. };
  27899. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  27900. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  27901. };
  27902. CannonJSPlugin.prototype.runOneStep = function (delta) {
  27903. this._world.step(delta);
  27904. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27905. var registeredMesh = this._registeredMeshes[index];
  27906. if (registeredMesh.isChild) {
  27907. continue;
  27908. }
  27909. // Body position
  27910. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  27911. var deltaPos = registeredMesh.delta || BABYLON.Vector3.Zero();
  27912. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  27913. registeredMesh.mesh.position.y = bodyY + deltaPos.y;
  27914. registeredMesh.mesh.position.z = bodyZ + deltaPos.z;
  27915. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  27916. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.y;
  27917. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.z;
  27918. registeredMesh.mesh.rotationQuaternion.w = registeredMesh.body.quaternion.w;
  27919. }
  27920. };
  27921. CannonJSPlugin.prototype.setGravity = function (gravity) {
  27922. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  27923. };
  27924. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  27925. this.unregisterMesh(mesh);
  27926. mesh.computeWorldMatrix(true);
  27927. var shape = this._createShape(mesh, impostor, options);
  27928. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  27929. };
  27930. CannonJSPlugin.prototype._createShape = function (mesh, impostor, options) {
  27931. switch (impostor) {
  27932. case BABYLON.PhysicsEngine.SphereImpostor:
  27933. var bbox = mesh.getBoundingInfo().boundingBox;
  27934. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  27935. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  27936. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  27937. return new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  27938. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  27939. case BABYLON.PhysicsEngine.CylinderImpostor:
  27940. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  27941. case BABYLON.PhysicsEngine.BoxImpostor:
  27942. bbox = mesh.getBoundingInfo().boundingBox;
  27943. var min = bbox.minimumWorld;
  27944. var max = bbox.maximumWorld;
  27945. var box = max.subtract(min).scale(0.5);
  27946. return new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  27947. case BABYLON.PhysicsEngine.PlaneImpostor:
  27948. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  27949. return new CANNON.Plane();
  27950. case BABYLON.PhysicsEngine.MeshImpostor:
  27951. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27952. var rawFaces = mesh.getIndices();
  27953. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  27954. }
  27955. };
  27956. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  27957. var verts = [], faces = [];
  27958. mesh.computeWorldMatrix(true);
  27959. // Get vertices
  27960. for (var i = 0; i < rawVerts.length; i += 3) {
  27961. var transformed = BABYLON.Vector3.Zero();
  27962. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  27963. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  27964. }
  27965. // Get faces
  27966. for (var j = 0; j < rawFaces.length; j += 3) {
  27967. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  27968. }
  27969. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  27970. return shape;
  27971. };
  27972. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  27973. var index;
  27974. var mat;
  27975. for (index = 0; index < this._physicsMaterials.length; index++) {
  27976. mat = this._physicsMaterials[index];
  27977. if (mat.friction === friction && mat.restitution === restitution) {
  27978. return mat;
  27979. }
  27980. }
  27981. var currentMat = new CANNON.Material("mat");
  27982. this._physicsMaterials.push(currentMat);
  27983. for (index = 0; index < this._physicsMaterials.length; index++) {
  27984. mat = this._physicsMaterials[index];
  27985. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  27986. this._world.addContactMaterial(contactMaterial);
  27987. }
  27988. return currentMat;
  27989. };
  27990. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  27991. var initialRotation = null;
  27992. if (!mesh.rotationQuaternion) {
  27993. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27994. }
  27995. // The delta between the mesh position and the mesh bounding box center
  27996. var bbox = mesh.getBoundingInfo().boundingBox;
  27997. var deltaPosition = mesh.position.subtract(bbox.center);
  27998. var material = this._addMaterial(friction, restitution);
  27999. var body = new CANNON.Body({
  28000. mass: mass,
  28001. material: material,
  28002. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28003. });
  28004. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28005. //is shape is a plane, it must be rotated 90 degs in the X axis.
  28006. if (shape.type === CANNON.Shape.types.PLANE) {
  28007. var tmpQ = new CANNON.Quaternion();
  28008. tmpQ.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);
  28009. body.quaternion = body.quaternion.mult(tmpQ);
  28010. }
  28011. //add the shape
  28012. body.addShape(shape);
  28013. this._world.add(body);
  28014. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  28015. return body;
  28016. };
  28017. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28018. var initialMesh = parts[0].mesh;
  28019. this.unregisterMesh(initialMesh);
  28020. initialMesh.computeWorldMatrix(true);
  28021. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28022. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options.mass, options.friction, options.restitution);
  28023. for (var index = 1; index < parts.length; index++) {
  28024. var mesh = parts[index].mesh;
  28025. mesh.computeWorldMatrix(true);
  28026. var shape = this._createShape(mesh, parts[index].impostor);
  28027. var localPosition = mesh.position;
  28028. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28029. }
  28030. return body;
  28031. };
  28032. CannonJSPlugin.prototype._unbindBody = function (body) {
  28033. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28034. var registeredMesh = this._registeredMeshes[index];
  28035. if (registeredMesh.body === body) {
  28036. this._world.remove(registeredMesh.body);
  28037. registeredMesh.body = null;
  28038. registeredMesh.delta = null;
  28039. }
  28040. }
  28041. };
  28042. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28043. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28044. var registeredMesh = this._registeredMeshes[index];
  28045. if (registeredMesh.mesh === mesh) {
  28046. // Remove body
  28047. if (registeredMesh.body) {
  28048. this._unbindBody(registeredMesh.body);
  28049. }
  28050. this._registeredMeshes.splice(index, 1);
  28051. return;
  28052. }
  28053. }
  28054. };
  28055. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28056. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28057. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28058. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28059. var registeredMesh = this._registeredMeshes[index];
  28060. if (registeredMesh.mesh === mesh) {
  28061. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28062. return;
  28063. }
  28064. }
  28065. };
  28066. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28067. var body1 = null, body2 = null;
  28068. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28069. var registeredMesh = this._registeredMeshes[index];
  28070. if (registeredMesh.mesh === mesh1) {
  28071. body1 = registeredMesh.body;
  28072. }
  28073. else if (registeredMesh.mesh === mesh2) {
  28074. body2 = registeredMesh.body;
  28075. }
  28076. }
  28077. if (!body1 || !body2) {
  28078. return false;
  28079. }
  28080. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.y, pivot1.z), body2, new CANNON.Vec3(pivot2.x, pivot2.y, pivot2.z));
  28081. this._world.addConstraint(constraint);
  28082. return true;
  28083. };
  28084. CannonJSPlugin.prototype.dispose = function () {
  28085. while (this._registeredMeshes.length) {
  28086. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28087. }
  28088. };
  28089. CannonJSPlugin.prototype.isSupported = function () {
  28090. return window.CANNON !== undefined;
  28091. };
  28092. return CannonJSPlugin;
  28093. })();
  28094. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28095. })(BABYLON || (BABYLON = {}));
  28096. var BABYLON;
  28097. (function (BABYLON) {
  28098. var OimoJSPlugin = (function () {
  28099. function OimoJSPlugin() {
  28100. this._registeredMeshes = [];
  28101. /**
  28102. * Update the body position according to the mesh position
  28103. * @param mesh
  28104. */
  28105. this.updateBodyPosition = function (mesh) {
  28106. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28107. var registeredMesh = this._registeredMeshes[index];
  28108. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28109. var body = registeredMesh.body.body;
  28110. mesh.computeWorldMatrix(true);
  28111. var center = mesh.getBoundingInfo().boundingBox.center;
  28112. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  28113. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  28114. body.sleeping = false;
  28115. return;
  28116. }
  28117. // Case where the parent has been updated
  28118. if (registeredMesh.mesh.parent === mesh) {
  28119. mesh.computeWorldMatrix(true);
  28120. registeredMesh.mesh.computeWorldMatrix(true);
  28121. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  28122. var absoluteRotation = mesh.rotation;
  28123. body = registeredMesh.body.body;
  28124. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  28125. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  28126. body.sleeping = false;
  28127. return;
  28128. }
  28129. }
  28130. };
  28131. }
  28132. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28133. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28134. };
  28135. OimoJSPlugin.prototype.initialize = function (iterations) {
  28136. this._world = new OIMO.World();
  28137. this._world.clear();
  28138. };
  28139. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28140. this._world.gravity = gravity;
  28141. };
  28142. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28143. var body = null;
  28144. this.unregisterMesh(mesh);
  28145. mesh.computeWorldMatrix(true);
  28146. var initialRotation = null;
  28147. if (mesh.rotationQuaternion) {
  28148. initialRotation = mesh.rotationQuaternion.clone();
  28149. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28150. mesh.computeWorldMatrix(true);
  28151. }
  28152. var bbox = mesh.getBoundingInfo().boundingBox;
  28153. // The delta between the mesh position and the mesh bounding box center
  28154. var deltaPosition = mesh.position.subtract(bbox.center);
  28155. // Transform delta position with the rotation
  28156. if (initialRotation) {
  28157. var m = new BABYLON.Matrix();
  28158. initialRotation.toRotationMatrix(m);
  28159. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  28160. }
  28161. // register mesh
  28162. switch (impostor) {
  28163. case BABYLON.PhysicsEngine.SphereImpostor:
  28164. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28165. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28166. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28167. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28168. body = new OIMO.Body({
  28169. type: 'sphere',
  28170. size: [size],
  28171. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28172. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  28173. move: options.mass != 0,
  28174. config: [options.mass, options.friction, options.restitution],
  28175. world: this._world
  28176. });
  28177. break;
  28178. case BABYLON.PhysicsEngine.PlaneImpostor:
  28179. //Oimo "fakes" a cylinder as a box, so why don't we!
  28180. case BABYLON.PhysicsEngine.CylinderImpostor:
  28181. case BABYLON.PhysicsEngine.BoxImpostor:
  28182. var min = bbox.minimumWorld;
  28183. var max = bbox.maximumWorld;
  28184. var box = max.subtract(min);
  28185. var sizeX = this._checkWithEpsilon(box.x);
  28186. var sizeY = this._checkWithEpsilon(box.y);
  28187. var sizeZ = this._checkWithEpsilon(box.z);
  28188. body = new OIMO.Body({
  28189. type: 'box',
  28190. size: [sizeX, sizeY, sizeZ],
  28191. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28192. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  28193. move: options.mass != 0,
  28194. config: [options.mass, options.friction, options.restitution],
  28195. world: this._world
  28196. });
  28197. break;
  28198. }
  28199. //If quaternion was set as the rotation of the object
  28200. if (initialRotation) {
  28201. //We have to access the rigid body's properties to set the quaternion.
  28202. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28203. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  28204. //update the internal rotation matrix
  28205. body.body.syncShapes();
  28206. }
  28207. this._registeredMeshes.push({
  28208. mesh: mesh,
  28209. body: body,
  28210. delta: deltaPosition
  28211. });
  28212. return body;
  28213. };
  28214. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28215. var types = [], sizes = [], positions = [], rotations = [];
  28216. var initialMesh = parts[0].mesh;
  28217. for (var index = 0; index < parts.length; index++) {
  28218. var part = parts[index];
  28219. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  28220. types.push(bodyParameters.type);
  28221. sizes.push.apply(sizes, bodyParameters.size);
  28222. positions.push.apply(positions, bodyParameters.pos);
  28223. rotations.push.apply(rotations, bodyParameters.rot);
  28224. }
  28225. var body = new OIMO.Body({
  28226. type: types,
  28227. size: sizes,
  28228. pos: positions,
  28229. rot: rotations,
  28230. move: options.mass != 0,
  28231. config: [options.mass, options.friction, options.restitution],
  28232. world: this._world
  28233. });
  28234. this._registeredMeshes.push({
  28235. mesh: initialMesh,
  28236. body: body
  28237. });
  28238. return body;
  28239. };
  28240. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  28241. var bodyParameters = null;
  28242. var mesh = part.mesh;
  28243. // We need the bounding box/sphere info to compute the physics body
  28244. mesh.computeWorldMatrix();
  28245. switch (part.impostor) {
  28246. case BABYLON.PhysicsEngine.SphereImpostor:
  28247. var bbox = mesh.getBoundingInfo().boundingBox;
  28248. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28249. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28250. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28251. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28252. bodyParameters = {
  28253. type: 'sphere',
  28254. /* bug with oimo : sphere needs 3 sizes in this case */
  28255. size: [size, -1, -1],
  28256. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  28257. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  28258. };
  28259. break;
  28260. case BABYLON.PhysicsEngine.PlaneImpostor:
  28261. case BABYLON.PhysicsEngine.BoxImpostor:
  28262. bbox = mesh.getBoundingInfo().boundingBox;
  28263. var min = bbox.minimumWorld;
  28264. var max = bbox.maximumWorld;
  28265. var box = max.subtract(min);
  28266. var sizeX = this._checkWithEpsilon(box.x);
  28267. var sizeY = this._checkWithEpsilon(box.y);
  28268. var sizeZ = this._checkWithEpsilon(box.z);
  28269. var relativePosition = mesh.position;
  28270. bodyParameters = {
  28271. type: 'box',
  28272. size: [sizeX, sizeY, sizeZ],
  28273. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  28274. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  28275. };
  28276. break;
  28277. }
  28278. return bodyParameters;
  28279. };
  28280. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  28281. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28282. var registeredMesh = this._registeredMeshes[index];
  28283. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28284. if (registeredMesh.body) {
  28285. this._world.removeRigidBody(registeredMesh.body.body);
  28286. this._unbindBody(registeredMesh.body);
  28287. }
  28288. this._registeredMeshes.splice(index, 1);
  28289. return;
  28290. }
  28291. }
  28292. };
  28293. OimoJSPlugin.prototype._unbindBody = function (body) {
  28294. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28295. var registeredMesh = this._registeredMeshes[index];
  28296. if (registeredMesh.body === body) {
  28297. registeredMesh.body = null;
  28298. }
  28299. }
  28300. };
  28301. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28302. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28303. var registeredMesh = this._registeredMeshes[index];
  28304. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28305. // Get object mass to have a behaviour similar to cannon.js
  28306. var mass = registeredMesh.body.body.massInfo.mass;
  28307. // The force is scaled with the mass of object
  28308. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  28309. return;
  28310. }
  28311. }
  28312. };
  28313. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  28314. var body1 = null, body2 = null;
  28315. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28316. var registeredMesh = this._registeredMeshes[index];
  28317. if (registeredMesh.mesh === mesh1) {
  28318. body1 = registeredMesh.body.body;
  28319. }
  28320. else if (registeredMesh.mesh === mesh2) {
  28321. body2 = registeredMesh.body.body;
  28322. }
  28323. }
  28324. if (!body1 || !body2) {
  28325. return false;
  28326. }
  28327. if (!options) {
  28328. options = {};
  28329. }
  28330. new OIMO.Link({
  28331. type: options.type,
  28332. body1: body1,
  28333. body2: body2,
  28334. min: options.min,
  28335. max: options.max,
  28336. axe1: options.axe1,
  28337. axe2: options.axe2,
  28338. pos1: [pivot1.x, pivot1.y, pivot1.z],
  28339. pos2: [pivot2.x, pivot2.y, pivot2.z],
  28340. collision: options.collision,
  28341. spring: options.spring,
  28342. world: this._world
  28343. });
  28344. return true;
  28345. };
  28346. OimoJSPlugin.prototype.dispose = function () {
  28347. this._world.clear();
  28348. while (this._registeredMeshes.length) {
  28349. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28350. }
  28351. };
  28352. OimoJSPlugin.prototype.isSupported = function () {
  28353. return OIMO !== undefined;
  28354. };
  28355. OimoJSPlugin.prototype._getLastShape = function (body) {
  28356. var lastShape = body.shapes;
  28357. while (lastShape.next) {
  28358. lastShape = lastShape.next;
  28359. }
  28360. return lastShape;
  28361. };
  28362. OimoJSPlugin.prototype.runOneStep = function (time) {
  28363. this._world.step();
  28364. // Update the position of all registered meshes
  28365. var i = this._registeredMeshes.length;
  28366. var m;
  28367. while (i--) {
  28368. var body = this._registeredMeshes[i].body.body;
  28369. var mesh = this._registeredMeshes[i].mesh;
  28370. var delta = this._registeredMeshes[i].delta;
  28371. if (!body.sleeping) {
  28372. if (body.shapes.next) {
  28373. var parentShape = this._getLastShape(body);
  28374. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  28375. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  28376. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  28377. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  28378. if (!mesh.rotationQuaternion) {
  28379. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28380. }
  28381. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  28382. mesh.computeWorldMatrix();
  28383. }
  28384. else {
  28385. m = body.getMatrix();
  28386. mtx = BABYLON.Matrix.FromArray(m);
  28387. // Body position
  28388. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  28389. if (!delta) {
  28390. mesh.position.x = bodyX;
  28391. mesh.position.y = bodyY;
  28392. mesh.position.z = bodyZ;
  28393. }
  28394. else {
  28395. mesh.position.x = bodyX + delta.x;
  28396. mesh.position.y = bodyY + delta.y;
  28397. mesh.position.z = bodyZ + delta.z;
  28398. }
  28399. if (!mesh.rotationQuaternion) {
  28400. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28401. }
  28402. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  28403. mesh.computeWorldMatrix();
  28404. }
  28405. }
  28406. }
  28407. };
  28408. return OimoJSPlugin;
  28409. })();
  28410. BABYLON.OimoJSPlugin = OimoJSPlugin;
  28411. })(BABYLON || (BABYLON = {}));
  28412. var BABYLON;
  28413. (function (BABYLON) {
  28414. var DisplayPassPostProcess = (function (_super) {
  28415. __extends(DisplayPassPostProcess, _super);
  28416. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28417. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28418. }
  28419. return DisplayPassPostProcess;
  28420. })(BABYLON.PostProcess);
  28421. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28422. })(BABYLON || (BABYLON = {}));
  28423. var BABYLON;
  28424. (function (BABYLON) {
  28425. var SimplificationSettings = (function () {
  28426. function SimplificationSettings(quality, distance, optimizeMesh) {
  28427. this.quality = quality;
  28428. this.distance = distance;
  28429. this.optimizeMesh = optimizeMesh;
  28430. }
  28431. return SimplificationSettings;
  28432. })();
  28433. BABYLON.SimplificationSettings = SimplificationSettings;
  28434. var SimplificationQueue = (function () {
  28435. function SimplificationQueue() {
  28436. this.running = false;
  28437. this._simplificationArray = [];
  28438. }
  28439. SimplificationQueue.prototype.addTask = function (task) {
  28440. this._simplificationArray.push(task);
  28441. };
  28442. SimplificationQueue.prototype.executeNext = function () {
  28443. var task = this._simplificationArray.pop();
  28444. if (task) {
  28445. this.running = true;
  28446. this.runSimplification(task);
  28447. }
  28448. else {
  28449. this.running = false;
  28450. }
  28451. };
  28452. SimplificationQueue.prototype.runSimplification = function (task) {
  28453. var _this = this;
  28454. if (task.parallelProcessing) {
  28455. //parallel simplifier
  28456. task.settings.forEach(function (setting) {
  28457. var simplifier = _this.getSimplifier(task);
  28458. simplifier.simplify(setting, function (newMesh) {
  28459. task.mesh.addLODLevel(setting.distance, newMesh);
  28460. newMesh.isVisible = true;
  28461. //check if it is the last
  28462. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28463. //all done, run the success callback.
  28464. task.successCallback();
  28465. }
  28466. _this.executeNext();
  28467. });
  28468. });
  28469. }
  28470. else {
  28471. //single simplifier.
  28472. var simplifier = this.getSimplifier(task);
  28473. var runDecimation = function (setting, callback) {
  28474. simplifier.simplify(setting, function (newMesh) {
  28475. task.mesh.addLODLevel(setting.distance, newMesh);
  28476. newMesh.isVisible = true;
  28477. //run the next quality level
  28478. callback();
  28479. });
  28480. };
  28481. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28482. runDecimation(task.settings[loop.index], function () {
  28483. loop.executeNext();
  28484. });
  28485. }, function () {
  28486. //execution ended, run the success callback.
  28487. if (task.successCallback) {
  28488. task.successCallback();
  28489. }
  28490. _this.executeNext();
  28491. });
  28492. }
  28493. };
  28494. SimplificationQueue.prototype.getSimplifier = function (task) {
  28495. switch (task.simplificationType) {
  28496. case SimplificationType.QUADRATIC:
  28497. default:
  28498. return new QuadraticErrorSimplification(task.mesh);
  28499. }
  28500. };
  28501. return SimplificationQueue;
  28502. })();
  28503. BABYLON.SimplificationQueue = SimplificationQueue;
  28504. /**
  28505. * The implemented types of simplification.
  28506. * At the moment only Quadratic Error Decimation is implemented.
  28507. */
  28508. (function (SimplificationType) {
  28509. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28510. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28511. var SimplificationType = BABYLON.SimplificationType;
  28512. var DecimationTriangle = (function () {
  28513. function DecimationTriangle(vertices) {
  28514. this.vertices = vertices;
  28515. this.error = new Array(4);
  28516. this.deleted = false;
  28517. this.isDirty = false;
  28518. this.deletePending = false;
  28519. this.borderFactor = 0;
  28520. }
  28521. return DecimationTriangle;
  28522. })();
  28523. BABYLON.DecimationTriangle = DecimationTriangle;
  28524. var DecimationVertex = (function () {
  28525. function DecimationVertex(position, id) {
  28526. this.position = position;
  28527. this.id = id;
  28528. this.isBorder = true;
  28529. this.q = new QuadraticMatrix();
  28530. this.triangleCount = 0;
  28531. this.triangleStart = 0;
  28532. this.originalOffsets = [];
  28533. }
  28534. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28535. this.position.copyFrom(newPosition);
  28536. };
  28537. return DecimationVertex;
  28538. })();
  28539. BABYLON.DecimationVertex = DecimationVertex;
  28540. var QuadraticMatrix = (function () {
  28541. function QuadraticMatrix(data) {
  28542. this.data = new Array(10);
  28543. for (var i = 0; i < 10; ++i) {
  28544. if (data && data[i]) {
  28545. this.data[i] = data[i];
  28546. }
  28547. else {
  28548. this.data[i] = 0;
  28549. }
  28550. }
  28551. }
  28552. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28553. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  28554. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  28555. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  28556. return det;
  28557. };
  28558. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28559. for (var i = 0; i < 10; ++i) {
  28560. this.data[i] += matrix.data[i];
  28561. }
  28562. };
  28563. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28564. for (var i = 0; i < 10; ++i) {
  28565. this.data[i] += data[i];
  28566. }
  28567. };
  28568. QuadraticMatrix.prototype.add = function (matrix) {
  28569. var m = new QuadraticMatrix();
  28570. for (var i = 0; i < 10; ++i) {
  28571. m.data[i] = this.data[i] + matrix.data[i];
  28572. }
  28573. return m;
  28574. };
  28575. QuadraticMatrix.FromData = function (a, b, c, d) {
  28576. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28577. };
  28578. //returning an array to avoid garbage collection
  28579. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28580. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28581. };
  28582. return QuadraticMatrix;
  28583. })();
  28584. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28585. var Reference = (function () {
  28586. function Reference(vertexId, triangleId) {
  28587. this.vertexId = vertexId;
  28588. this.triangleId = triangleId;
  28589. }
  28590. return Reference;
  28591. })();
  28592. BABYLON.Reference = Reference;
  28593. /**
  28594. * An implementation of the Quadratic Error simplification algorithm.
  28595. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28596. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28597. * @author RaananW
  28598. */
  28599. var QuadraticErrorSimplification = (function () {
  28600. function QuadraticErrorSimplification(_mesh) {
  28601. this._mesh = _mesh;
  28602. this.initialized = false;
  28603. this.syncIterations = 5000;
  28604. this.aggressiveness = 7;
  28605. this.decimationIterations = 100;
  28606. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28607. }
  28608. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28609. var _this = this;
  28610. this.initDecimatedMesh();
  28611. //iterating through the submeshes array, one after the other.
  28612. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28613. _this.initWithMesh(loop.index, function () {
  28614. _this.runDecimation(settings, loop.index, function () {
  28615. loop.executeNext();
  28616. });
  28617. }, settings.optimizeMesh);
  28618. }, function () {
  28619. setTimeout(function () {
  28620. successCallback(_this._reconstructedMesh);
  28621. }, 0);
  28622. });
  28623. };
  28624. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28625. var _this = this;
  28626. var gCount = 0;
  28627. triangle.vertices.forEach(function (vertex) {
  28628. var count = 0;
  28629. var vPos = vertex.position;
  28630. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28631. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28632. ++count;
  28633. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  28634. ++count;
  28635. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  28636. ++count;
  28637. if (count > 1) {
  28638. ++gCount;
  28639. }
  28640. ;
  28641. });
  28642. if (gCount > 1) {
  28643. console.log(triangle, gCount);
  28644. }
  28645. return gCount > 1;
  28646. };
  28647. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28648. var _this = this;
  28649. var targetCount = ~~(this.triangles.length * settings.quality);
  28650. var deletedTriangles = 0;
  28651. var triangleCount = this.triangles.length;
  28652. var iterationFunction = function (iteration, callback) {
  28653. setTimeout(function () {
  28654. if (iteration % 5 === 0) {
  28655. _this.updateMesh(iteration === 0);
  28656. }
  28657. for (var i = 0; i < _this.triangles.length; ++i) {
  28658. _this.triangles[i].isDirty = false;
  28659. }
  28660. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28661. var trianglesIterator = function (i) {
  28662. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28663. var t = _this.triangles[tIdx];
  28664. if (!t)
  28665. return;
  28666. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28667. return;
  28668. }
  28669. for (var j = 0; j < 3; ++j) {
  28670. if (t.error[j] < threshold) {
  28671. var deleted0 = [];
  28672. var deleted1 = [];
  28673. var v0 = t.vertices[j];
  28674. var v1 = t.vertices[(j + 1) % 3];
  28675. if (v0.isBorder !== v1.isBorder)
  28676. continue;
  28677. var p = BABYLON.Vector3.Zero();
  28678. var n = BABYLON.Vector3.Zero();
  28679. var uv = BABYLON.Vector2.Zero();
  28680. var color = new BABYLON.Color4(0, 0, 0, 1);
  28681. _this.calculateError(v0, v1, p, n, uv, color);
  28682. var delTr = [];
  28683. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28684. continue;
  28685. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28686. continue;
  28687. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28688. continue;
  28689. var uniqueArray = [];
  28690. delTr.forEach(function (deletedT) {
  28691. if (uniqueArray.indexOf(deletedT) === -1) {
  28692. deletedT.deletePending = true;
  28693. uniqueArray.push(deletedT);
  28694. }
  28695. });
  28696. if (uniqueArray.length % 2 !== 0) {
  28697. continue;
  28698. }
  28699. v0.q = v1.q.add(v0.q);
  28700. v0.updatePosition(p);
  28701. var tStart = _this.references.length;
  28702. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28703. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28704. var tCount = _this.references.length - tStart;
  28705. if (tCount <= v0.triangleCount) {
  28706. if (tCount) {
  28707. for (var c = 0; c < tCount; c++) {
  28708. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28709. }
  28710. }
  28711. }
  28712. else {
  28713. v0.triangleStart = tStart;
  28714. }
  28715. v0.triangleCount = tCount;
  28716. break;
  28717. }
  28718. }
  28719. };
  28720. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  28721. }, 0);
  28722. };
  28723. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28724. if (triangleCount - deletedTriangles <= targetCount)
  28725. loop.breakLoop();
  28726. else {
  28727. iterationFunction(loop.index, function () {
  28728. loop.executeNext();
  28729. });
  28730. }
  28731. }, function () {
  28732. setTimeout(function () {
  28733. //reconstruct this part of the mesh
  28734. _this.reconstructMesh(submeshIndex);
  28735. successCallback();
  28736. }, 0);
  28737. });
  28738. };
  28739. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  28740. var _this = this;
  28741. this.vertices = [];
  28742. this.triangles = [];
  28743. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28744. var indices = this._mesh.getIndices();
  28745. var submesh = this._mesh.subMeshes[submeshIndex];
  28746. var findInVertices = function (positionToSearch) {
  28747. if (optimizeMesh) {
  28748. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  28749. if (_this.vertices[ii].position.equals(positionToSearch)) {
  28750. return _this.vertices[ii];
  28751. }
  28752. }
  28753. }
  28754. return null;
  28755. };
  28756. var vertexReferences = [];
  28757. var vertexInit = function (i) {
  28758. var offset = i + submesh.verticesStart;
  28759. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  28760. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  28761. vertex.originalOffsets.push(offset);
  28762. if (vertex.id === _this.vertices.length) {
  28763. _this.vertices.push(vertex);
  28764. }
  28765. vertexReferences.push(vertex.id);
  28766. };
  28767. //var totalVertices = mesh.getTotalVertices();
  28768. var totalVertices = submesh.verticesCount;
  28769. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  28770. var indicesInit = function (i) {
  28771. var offset = (submesh.indexStart / 3) + i;
  28772. var pos = (offset * 3);
  28773. var i0 = indices[pos + 0];
  28774. var i1 = indices[pos + 1];
  28775. var i2 = indices[pos + 2];
  28776. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  28777. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  28778. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  28779. var triangle = new DecimationTriangle([v0, v1, v2]);
  28780. triangle.originalOffset = pos;
  28781. _this.triangles.push(triangle);
  28782. };
  28783. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28784. _this.init(callback);
  28785. });
  28786. });
  28787. };
  28788. QuadraticErrorSimplification.prototype.init = function (callback) {
  28789. var _this = this;
  28790. var triangleInit1 = function (i) {
  28791. var t = _this.triangles[i];
  28792. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  28793. for (var j = 0; j < 3; j++) {
  28794. 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))));
  28795. }
  28796. };
  28797. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28798. var triangleInit2 = function (i) {
  28799. var t = _this.triangles[i];
  28800. for (var j = 0; j < 3; ++j) {
  28801. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  28802. }
  28803. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28804. };
  28805. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28806. _this.initialized = true;
  28807. callback();
  28808. });
  28809. });
  28810. };
  28811. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28812. var newTriangles = [];
  28813. var i;
  28814. for (i = 0; i < this.vertices.length; ++i) {
  28815. this.vertices[i].triangleCount = 0;
  28816. }
  28817. var t;
  28818. var j;
  28819. for (i = 0; i < this.triangles.length; ++i) {
  28820. if (!this.triangles[i].deleted) {
  28821. t = this.triangles[i];
  28822. for (j = 0; j < 3; ++j) {
  28823. t.vertices[j].triangleCount = 1;
  28824. }
  28825. newTriangles.push(t);
  28826. }
  28827. }
  28828. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  28829. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  28830. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  28831. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  28832. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28833. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28834. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28835. var vertexCount = 0;
  28836. for (i = 0; i < this.vertices.length; ++i) {
  28837. var vertex = this.vertices[i];
  28838. vertex.id = vertexCount;
  28839. if (vertex.triangleCount) {
  28840. vertex.originalOffsets.forEach(function (originalOffset) {
  28841. newPositionData.push(vertex.position.x);
  28842. newPositionData.push(vertex.position.y);
  28843. newPositionData.push(vertex.position.z);
  28844. newNormalData.push(normalData[originalOffset * 3]);
  28845. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  28846. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  28847. if (uvs && uvs.length) {
  28848. newUVsData.push(uvs[(originalOffset * 2)]);
  28849. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  28850. }
  28851. else if (colorsData && colorsData.length) {
  28852. newColorsData.push(colorsData[(originalOffset * 4)]);
  28853. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  28854. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  28855. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  28856. }
  28857. ++vertexCount;
  28858. });
  28859. }
  28860. }
  28861. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28862. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28863. var submeshesArray = this._reconstructedMesh.subMeshes;
  28864. this._reconstructedMesh.subMeshes = [];
  28865. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28866. var originalIndices = this._mesh.getIndices();
  28867. for (i = 0; i < newTriangles.length; ++i) {
  28868. t = newTriangles[i]; //now get the new referencing point for each vertex
  28869. [0, 1, 2].forEach(function (idx) {
  28870. var id = originalIndices[t.originalOffset + idx];
  28871. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  28872. if (offset < 0)
  28873. offset = 0;
  28874. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  28875. });
  28876. }
  28877. //overwriting the old vertex buffers and indices.
  28878. this._reconstructedMesh.setIndices(newIndicesArray);
  28879. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28880. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28881. if (newUVsData.length > 0)
  28882. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28883. if (newColorsData.length > 0)
  28884. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28885. //create submesh
  28886. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28887. if (submeshIndex > 0) {
  28888. this._reconstructedMesh.subMeshes = [];
  28889. submeshesArray.forEach(function (submesh) {
  28890. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28891. });
  28892. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28893. }
  28894. };
  28895. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28896. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28897. this._reconstructedMesh.material = this._mesh.material;
  28898. this._reconstructedMesh.parent = this._mesh.parent;
  28899. this._reconstructedMesh.isVisible = false;
  28900. };
  28901. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  28902. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28903. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28904. if (t.deleted)
  28905. continue;
  28906. var s = this.references[vertex1.triangleStart + i].vertexId;
  28907. var v1 = t.vertices[(s + 1) % 3];
  28908. var v2 = t.vertices[(s + 2) % 3];
  28909. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  28910. deletedArray[i] = true;
  28911. delTr.push(t);
  28912. continue;
  28913. }
  28914. var d1 = v1.position.subtract(point);
  28915. d1 = d1.normalize();
  28916. var d2 = v2.position.subtract(point);
  28917. d2 = d2.normalize();
  28918. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28919. return true;
  28920. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28921. deletedArray[i] = false;
  28922. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28923. return true;
  28924. }
  28925. return false;
  28926. };
  28927. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  28928. var newDeleted = deletedTriangles;
  28929. for (var i = 0; i < vertex.triangleCount; ++i) {
  28930. var ref = this.references[vertex.triangleStart + i];
  28931. var t = this.triangles[ref.triangleId];
  28932. if (t.deleted)
  28933. continue;
  28934. if (deletedArray[i] && t.deletePending) {
  28935. t.deleted = true;
  28936. newDeleted++;
  28937. continue;
  28938. }
  28939. t.vertices[ref.vertexId] = origVertex;
  28940. t.isDirty = true;
  28941. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  28942. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  28943. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  28944. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28945. this.references.push(ref);
  28946. }
  28947. return newDeleted;
  28948. };
  28949. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28950. for (var i = 0; i < this.vertices.length; ++i) {
  28951. var vCount = [];
  28952. var vId = [];
  28953. var v = this.vertices[i];
  28954. var j;
  28955. for (j = 0; j < v.triangleCount; ++j) {
  28956. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28957. for (var ii = 0; ii < 3; ii++) {
  28958. var ofs = 0;
  28959. var vv = triangle.vertices[ii];
  28960. while (ofs < vCount.length) {
  28961. if (vId[ofs] === vv.id)
  28962. break;
  28963. ++ofs;
  28964. }
  28965. if (ofs === vCount.length) {
  28966. vCount.push(1);
  28967. vId.push(vv.id);
  28968. }
  28969. else {
  28970. vCount[ofs]++;
  28971. }
  28972. }
  28973. }
  28974. for (j = 0; j < vCount.length; ++j) {
  28975. if (vCount[j] === 1) {
  28976. this.vertices[vId[j]].isBorder = true;
  28977. }
  28978. else {
  28979. this.vertices[vId[j]].isBorder = false;
  28980. }
  28981. }
  28982. }
  28983. };
  28984. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28985. if (identifyBorders === void 0) { identifyBorders = false; }
  28986. var i;
  28987. if (!identifyBorders) {
  28988. var newTrianglesVector = [];
  28989. for (i = 0; i < this.triangles.length; ++i) {
  28990. if (!this.triangles[i].deleted) {
  28991. newTrianglesVector.push(this.triangles[i]);
  28992. }
  28993. }
  28994. this.triangles = newTrianglesVector;
  28995. }
  28996. for (i = 0; i < this.vertices.length; ++i) {
  28997. this.vertices[i].triangleCount = 0;
  28998. this.vertices[i].triangleStart = 0;
  28999. }
  29000. var t;
  29001. var j;
  29002. var v;
  29003. for (i = 0; i < this.triangles.length; ++i) {
  29004. t = this.triangles[i];
  29005. for (j = 0; j < 3; ++j) {
  29006. v = t.vertices[j];
  29007. v.triangleCount++;
  29008. }
  29009. }
  29010. var tStart = 0;
  29011. for (i = 0; i < this.vertices.length; ++i) {
  29012. this.vertices[i].triangleStart = tStart;
  29013. tStart += this.vertices[i].triangleCount;
  29014. this.vertices[i].triangleCount = 0;
  29015. }
  29016. var newReferences = new Array(this.triangles.length * 3);
  29017. for (i = 0; i < this.triangles.length; ++i) {
  29018. t = this.triangles[i];
  29019. for (j = 0; j < 3; ++j) {
  29020. v = t.vertices[j];
  29021. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29022. v.triangleCount++;
  29023. }
  29024. }
  29025. this.references = newReferences;
  29026. if (identifyBorders) {
  29027. this.identifyBorder();
  29028. }
  29029. };
  29030. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29031. var x = point.x;
  29032. var y = point.y;
  29033. var z = point.z;
  29034. 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
  29035. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29036. };
  29037. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29038. var q = vertex1.q.add(vertex2.q);
  29039. var border = vertex1.isBorder && vertex2.isBorder;
  29040. var error = 0;
  29041. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29042. if (qDet !== 0 && !border) {
  29043. if (!pointResult) {
  29044. pointResult = BABYLON.Vector3.Zero();
  29045. }
  29046. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29047. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29048. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29049. error = this.vertexError(q, pointResult);
  29050. }
  29051. else {
  29052. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29053. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29054. var error1 = this.vertexError(q, vertex1.position);
  29055. var error2 = this.vertexError(q, vertex2.position);
  29056. var error3 = this.vertexError(q, p3);
  29057. error = Math.min(error1, error2, error3);
  29058. if (error === error1) {
  29059. if (pointResult) {
  29060. pointResult.copyFrom(vertex1.position);
  29061. }
  29062. }
  29063. else if (error === error2) {
  29064. if (pointResult) {
  29065. pointResult.copyFrom(vertex2.position);
  29066. }
  29067. }
  29068. else {
  29069. if (pointResult) {
  29070. pointResult.copyFrom(p3);
  29071. }
  29072. }
  29073. }
  29074. return error;
  29075. };
  29076. return QuadraticErrorSimplification;
  29077. })();
  29078. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29079. })(BABYLON || (BABYLON = {}));
  29080. var BABYLON;
  29081. (function (BABYLON) {
  29082. var serializeLight = function (light) {
  29083. var serializationObject = {};
  29084. serializationObject.name = light.name;
  29085. serializationObject.id = light.id;
  29086. serializationObject.tags = BABYLON.Tags.GetTags(light);
  29087. if (light instanceof BABYLON.PointLight) {
  29088. serializationObject.type = 0;
  29089. serializationObject.position = (light).position.asArray();
  29090. }
  29091. else if (light instanceof BABYLON.DirectionalLight) {
  29092. serializationObject.type = 1;
  29093. var directionalLight = light;
  29094. serializationObject.position = directionalLight.position.asArray();
  29095. serializationObject.direction = directionalLight.direction.asArray();
  29096. }
  29097. else if (light instanceof BABYLON.SpotLight) {
  29098. serializationObject.type = 2;
  29099. var spotLight = light;
  29100. serializationObject.position = spotLight.position.asArray();
  29101. serializationObject.direction = spotLight.position.asArray();
  29102. serializationObject.angle = spotLight.angle;
  29103. serializationObject.exponent = spotLight.exponent;
  29104. }
  29105. else if (light instanceof BABYLON.HemisphericLight) {
  29106. serializationObject.type = 3;
  29107. var hemisphericLight = light;
  29108. serializationObject.direction = hemisphericLight.direction.asArray();
  29109. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  29110. }
  29111. if (light.intensity) {
  29112. serializationObject.intensity = light.intensity;
  29113. }
  29114. serializationObject.range = light.range;
  29115. serializationObject.diffuse = light.diffuse.asArray();
  29116. serializationObject.specular = light.specular.asArray();
  29117. return serializationObject;
  29118. };
  29119. var serializeFresnelParameter = function (fresnelParameter) {
  29120. var serializationObject = {};
  29121. serializationObject.isEnabled = fresnelParameter.isEnabled;
  29122. serializationObject.leftColor = fresnelParameter.leftColor;
  29123. serializationObject.rightColor = fresnelParameter.rightColor;
  29124. serializationObject.bias = fresnelParameter.bias;
  29125. serializationObject.power = fresnelParameter.power;
  29126. return serializationObject;
  29127. };
  29128. var serializeAnimation;
  29129. var appendAnimations = function (source, destination) {
  29130. if (source.animations) {
  29131. destination.animations = [];
  29132. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29133. var animation = source.animations[animationIndex];
  29134. destination.animations.push(serializeAnimation(animation));
  29135. }
  29136. }
  29137. };
  29138. var serializeCamera = function (camera) {
  29139. var serializationObject = {};
  29140. serializationObject.name = camera.name;
  29141. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  29142. serializationObject.id = camera.id;
  29143. serializationObject.position = camera.position.asArray();
  29144. // Parent
  29145. if (camera.parent) {
  29146. serializationObject.parentId = camera.parent.id;
  29147. }
  29148. serializationObject.fov = camera.fov;
  29149. serializationObject.minZ = camera.minZ;
  29150. serializationObject.maxZ = camera.maxZ;
  29151. serializationObject.inertia = camera.inertia;
  29152. //setting the type
  29153. if (camera instanceof BABYLON.FreeCamera) {
  29154. serializationObject.type = "FreeCamera";
  29155. }
  29156. else if (camera instanceof BABYLON.ArcRotateCamera) {
  29157. serializationObject.type = "ArcRotateCamera";
  29158. }
  29159. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29160. serializationObject.type = "AnaglyphArcRotateCamera";
  29161. }
  29162. else if (camera instanceof BABYLON.GamepadCamera) {
  29163. serializationObject.type = "GamepadCamera";
  29164. }
  29165. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  29166. serializationObject.type = "AnaglyphFreeCamera";
  29167. }
  29168. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  29169. serializationObject.type = "DeviceOrientationCamera";
  29170. }
  29171. else if (camera instanceof BABYLON.FollowCamera) {
  29172. serializationObject.type = "FollowCamera";
  29173. }
  29174. else if (camera instanceof BABYLON.TouchCamera) {
  29175. serializationObject.type = "TouchCamera";
  29176. }
  29177. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  29178. serializationObject.type = "VirtualJoysticksCamera";
  29179. }
  29180. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  29181. serializationObject.type = "WebVRFreeCamera";
  29182. }
  29183. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  29184. serializationObject.type = "VRDeviceOrientationFreeCamera";
  29185. }
  29186. //special properties of specific cameras
  29187. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29188. var arcCamera = camera;
  29189. serializationObject.alpha = arcCamera.alpha;
  29190. serializationObject.beta = arcCamera.beta;
  29191. serializationObject.radius = arcCamera.radius;
  29192. if (arcCamera.target && arcCamera.target.id) {
  29193. serializationObject.lockedTargetId = arcCamera.target.id;
  29194. }
  29195. }
  29196. else if (camera instanceof BABYLON.FollowCamera) {
  29197. var followCam = camera;
  29198. serializationObject.radius = followCam.radius;
  29199. serializationObject.heightOffset = followCam.heightOffset;
  29200. serializationObject.rotationOffset = followCam.rotationOffset;
  29201. }
  29202. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29203. //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.
  29204. if (camera['_interaxialDistance'] !== undefined) {
  29205. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  29206. }
  29207. }
  29208. //general properties that not all cameras have. The [] is due to typescript's type safety
  29209. if (camera['speed'] !== undefined) {
  29210. serializationObject.speed = camera['speed'];
  29211. }
  29212. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  29213. serializationObject.target = camera['target'].asArray();
  29214. }
  29215. // Target
  29216. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  29217. serializationObject.rotation = camera['rotation'].asArray();
  29218. }
  29219. // Locked target
  29220. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  29221. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  29222. }
  29223. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  29224. serializationObject.applyGravity = camera['applyGravity'] || false;
  29225. if (camera['ellipsoid']) {
  29226. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  29227. }
  29228. // Animations
  29229. appendAnimations(camera, serializationObject);
  29230. // Layer mask
  29231. serializationObject.layerMask = camera.layerMask;
  29232. return serializationObject;
  29233. };
  29234. serializeAnimation = function (animation) {
  29235. var serializationObject = {};
  29236. serializationObject.name = animation.name;
  29237. serializationObject.property = animation.targetProperty;
  29238. serializationObject.framePerSecond = animation.framePerSecond;
  29239. serializationObject.dataType = animation.dataType;
  29240. serializationObject.loopBehavior = animation.loopMode;
  29241. var dataType = animation.dataType;
  29242. serializationObject.keys = [];
  29243. var keys = animation.getKeys();
  29244. for (var index = 0; index < keys.length; index++) {
  29245. var animationKey = keys[index];
  29246. var key = {};
  29247. key.frame = animationKey.frame;
  29248. switch (dataType) {
  29249. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  29250. key.values = [animationKey.value];
  29251. break;
  29252. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  29253. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  29254. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  29255. key.values = animationKey.value.asArray();
  29256. break;
  29257. }
  29258. serializationObject.keys.push(key);
  29259. }
  29260. return serializationObject;
  29261. };
  29262. var serializeMultiMaterial = function (material) {
  29263. var serializationObject = {};
  29264. serializationObject.name = material.name;
  29265. serializationObject.id = material.id;
  29266. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29267. serializationObject.materials = [];
  29268. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  29269. var subMat = material.subMaterials[matIndex];
  29270. if (subMat) {
  29271. serializationObject.materials.push(subMat.id);
  29272. }
  29273. else {
  29274. serializationObject.materials.push(null);
  29275. }
  29276. }
  29277. return serializationObject;
  29278. };
  29279. var serializeTexture;
  29280. var serializeMaterial = function (material) {
  29281. var serializationObject = {};
  29282. serializationObject.name = material.name;
  29283. serializationObject.ambient = material.ambientColor.asArray();
  29284. serializationObject.diffuse = material.diffuseColor.asArray();
  29285. serializationObject.specular = material.specularColor.asArray();
  29286. serializationObject.specularPower = material.specularPower;
  29287. serializationObject.emissive = material.emissiveColor.asArray();
  29288. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  29289. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  29290. serializationObject.alpha = material.alpha;
  29291. serializationObject.id = material.id;
  29292. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29293. serializationObject.backFaceCulling = material.backFaceCulling;
  29294. if (material.diffuseTexture) {
  29295. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  29296. }
  29297. if (material.diffuseFresnelParameters) {
  29298. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  29299. }
  29300. if (material.ambientTexture) {
  29301. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  29302. }
  29303. if (material.opacityTexture) {
  29304. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  29305. }
  29306. if (material.opacityFresnelParameters) {
  29307. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  29308. }
  29309. if (material.reflectionTexture) {
  29310. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  29311. }
  29312. if (material.reflectionFresnelParameters) {
  29313. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  29314. }
  29315. if (material.emissiveTexture) {
  29316. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  29317. }
  29318. if (material.lightmapTexture) {
  29319. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  29320. serializationObject.lightmapThreshold = material.lightmapThreshold;
  29321. }
  29322. if (material.emissiveFresnelParameters) {
  29323. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  29324. }
  29325. if (material.specularTexture) {
  29326. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  29327. }
  29328. if (material.bumpTexture) {
  29329. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  29330. }
  29331. return serializationObject;
  29332. };
  29333. serializeTexture = function (texture) {
  29334. var serializationObject = {};
  29335. if (!texture.name) {
  29336. return null;
  29337. }
  29338. if (texture instanceof BABYLON.CubeTexture) {
  29339. serializationObject.name = texture.name;
  29340. serializationObject.hasAlpha = texture.hasAlpha;
  29341. serializationObject.isCube = true;
  29342. serializationObject.level = texture.level;
  29343. serializationObject.coordinatesMode = texture.coordinatesMode;
  29344. return serializationObject;
  29345. }
  29346. var index;
  29347. if (texture instanceof BABYLON.MirrorTexture) {
  29348. var mirrorTexture = texture;
  29349. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  29350. serializationObject.renderList = [];
  29351. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  29352. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  29353. }
  29354. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  29355. }
  29356. else if (texture instanceof BABYLON.RenderTargetTexture) {
  29357. var renderTargetTexture = texture;
  29358. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  29359. serializationObject.renderList = [];
  29360. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  29361. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  29362. }
  29363. }
  29364. var regularTexture = texture;
  29365. serializationObject.name = texture.name;
  29366. serializationObject.hasAlpha = texture.hasAlpha;
  29367. serializationObject.level = texture.level;
  29368. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  29369. serializationObject.coordinatesMode = texture.coordinatesMode;
  29370. serializationObject.uOffset = regularTexture.uOffset;
  29371. serializationObject.vOffset = regularTexture.vOffset;
  29372. serializationObject.uScale = regularTexture.uScale;
  29373. serializationObject.vScale = regularTexture.vScale;
  29374. serializationObject.uAng = regularTexture.uAng;
  29375. serializationObject.vAng = regularTexture.vAng;
  29376. serializationObject.wAng = regularTexture.wAng;
  29377. serializationObject.wrapU = texture.wrapU;
  29378. serializationObject.wrapV = texture.wrapV;
  29379. // Animations
  29380. appendAnimations(texture, serializationObject);
  29381. return serializationObject;
  29382. };
  29383. var serializeSkeleton = function (skeleton) {
  29384. var serializationObject = {};
  29385. serializationObject.name = skeleton.name;
  29386. serializationObject.id = skeleton.id;
  29387. serializationObject.bones = [];
  29388. for (var index = 0; index < skeleton.bones.length; index++) {
  29389. var bone = skeleton.bones[index];
  29390. var serializedBone = {
  29391. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  29392. name: bone.name,
  29393. matrix: bone.getLocalMatrix().toArray()
  29394. };
  29395. serializationObject.bones.push(serializedBone);
  29396. if (bone.animations && bone.animations.length > 0) {
  29397. serializedBone.animation = serializeAnimation(bone.animations[0]);
  29398. }
  29399. }
  29400. return serializationObject;
  29401. };
  29402. var serializeParticleSystem = function (particleSystem) {
  29403. var serializationObject = {};
  29404. serializationObject.emitterId = particleSystem.emitter.id;
  29405. serializationObject.capacity = particleSystem.getCapacity();
  29406. if (particleSystem.particleTexture) {
  29407. serializationObject.textureName = particleSystem.particleTexture.name;
  29408. }
  29409. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  29410. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  29411. serializationObject.minSize = particleSystem.minSize;
  29412. serializationObject.maxSize = particleSystem.maxSize;
  29413. serializationObject.minLifeTime = particleSystem.minLifeTime;
  29414. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  29415. serializationObject.emitRate = particleSystem.emitRate;
  29416. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  29417. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  29418. serializationObject.gravity = particleSystem.gravity.asArray();
  29419. serializationObject.direction1 = particleSystem.direction1.asArray();
  29420. serializationObject.direction2 = particleSystem.direction2.asArray();
  29421. serializationObject.color1 = particleSystem.color1.asArray();
  29422. serializationObject.color2 = particleSystem.color2.asArray();
  29423. serializationObject.colorDead = particleSystem.colorDead.asArray();
  29424. serializationObject.updateSpeed = particleSystem.updateSpeed;
  29425. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  29426. serializationObject.textureMask = particleSystem.textureMask.asArray();
  29427. serializationObject.blendMode = particleSystem.blendMode;
  29428. return serializationObject;
  29429. };
  29430. var serializeLensFlareSystem = function (lensFlareSystem) {
  29431. var serializationObject = {};
  29432. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  29433. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  29434. serializationObject.flares = [];
  29435. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  29436. var flare = lensFlareSystem.lensFlares[index];
  29437. serializationObject.flares.push({
  29438. size: flare.size,
  29439. position: flare.position,
  29440. color: flare.color.asArray(),
  29441. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  29442. });
  29443. }
  29444. return serializationObject;
  29445. };
  29446. var serializeShadowGenerator = function (light) {
  29447. var serializationObject = {};
  29448. var shadowGenerator = light.getShadowGenerator();
  29449. serializationObject.lightId = light.id;
  29450. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  29451. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  29452. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  29453. serializationObject.renderList = [];
  29454. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  29455. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  29456. serializationObject.renderList.push(mesh.id);
  29457. }
  29458. return serializationObject;
  29459. };
  29460. var serializedGeometries = [];
  29461. var serializeVertexData;
  29462. var serializeTorusKnot;
  29463. var serializePlane;
  29464. var serializeGround;
  29465. var serializeTorus;
  29466. var serializeCylinder;
  29467. var serializeSphere;
  29468. var serializeBox;
  29469. var serializeGeometry = function (geometry, serializationGeometries) {
  29470. if (serializedGeometries[geometry.id]) {
  29471. return;
  29472. }
  29473. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29474. serializationGeometries.boxes.push(serializeBox(geometry));
  29475. }
  29476. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29477. serializationGeometries.spheres.push(serializeSphere(geometry));
  29478. }
  29479. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29480. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  29481. }
  29482. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29483. serializationGeometries.toruses.push(serializeTorus(geometry));
  29484. }
  29485. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29486. serializationGeometries.grounds.push(serializeGround(geometry));
  29487. }
  29488. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29489. serializationGeometries.planes.push(serializePlane(geometry));
  29490. }
  29491. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29492. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  29493. }
  29494. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29495. throw new Error("Unknown primitive type");
  29496. }
  29497. else {
  29498. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  29499. }
  29500. serializedGeometries[geometry.id] = true;
  29501. };
  29502. var serializeGeometryBase = function (geometry) {
  29503. var serializationObject = {};
  29504. serializationObject.id = geometry.id;
  29505. if (BABYLON.Tags.HasTags(geometry)) {
  29506. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  29507. }
  29508. return serializationObject;
  29509. };
  29510. serializeVertexData = function (vertexData) {
  29511. var serializationObject = serializeGeometryBase(vertexData);
  29512. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29513. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29514. }
  29515. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29516. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29517. }
  29518. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29519. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29520. }
  29521. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29522. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29523. }
  29524. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29525. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29526. }
  29527. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29528. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29529. }
  29530. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29531. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29532. }
  29533. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29534. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29535. }
  29536. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29537. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29538. }
  29539. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29540. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29541. serializationObject.matricesIndices._isExpanded = true;
  29542. }
  29543. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29544. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29545. }
  29546. serializationObject.indices = vertexData.getIndices();
  29547. return serializationObject;
  29548. };
  29549. var serializePrimitive = function (primitive) {
  29550. var serializationObject = serializeGeometryBase(primitive);
  29551. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  29552. return serializationObject;
  29553. };
  29554. serializeBox = function (box) {
  29555. var serializationObject = serializePrimitive(box);
  29556. serializationObject.size = box.size;
  29557. return serializationObject;
  29558. };
  29559. serializeSphere = function (sphere) {
  29560. var serializationObject = serializePrimitive(sphere);
  29561. serializationObject.segments = sphere.segments;
  29562. serializationObject.diameter = sphere.diameter;
  29563. return serializationObject;
  29564. };
  29565. serializeCylinder = function (cylinder) {
  29566. var serializationObject = serializePrimitive(cylinder);
  29567. serializationObject.height = cylinder.height;
  29568. serializationObject.diameterTop = cylinder.diameterTop;
  29569. serializationObject.diameterBottom = cylinder.diameterBottom;
  29570. serializationObject.tessellation = cylinder.tessellation;
  29571. return serializationObject;
  29572. };
  29573. serializeTorus = function (torus) {
  29574. var serializationObject = serializePrimitive(torus);
  29575. serializationObject.diameter = torus.diameter;
  29576. serializationObject.thickness = torus.thickness;
  29577. serializationObject.tessellation = torus.tessellation;
  29578. return serializationObject;
  29579. };
  29580. serializeGround = function (ground) {
  29581. var serializationObject = serializePrimitive(ground);
  29582. serializationObject.width = ground.width;
  29583. serializationObject.height = ground.height;
  29584. serializationObject.subdivisions = ground.subdivisions;
  29585. return serializationObject;
  29586. };
  29587. serializePlane = function (plane) {
  29588. var serializationObject = serializePrimitive(plane);
  29589. serializationObject.size = plane.size;
  29590. return serializationObject;
  29591. };
  29592. serializeTorusKnot = function (torusKnot) {
  29593. var serializationObject = serializePrimitive(torusKnot);
  29594. serializationObject.radius = torusKnot.radius;
  29595. serializationObject.tube = torusKnot.tube;
  29596. serializationObject.radialSegments = torusKnot.radialSegments;
  29597. serializationObject.tubularSegments = torusKnot.tubularSegments;
  29598. serializationObject.p = torusKnot.p;
  29599. serializationObject.q = torusKnot.q;
  29600. return serializationObject;
  29601. };
  29602. var serializeMesh = function (mesh, serializationScene) {
  29603. var serializationObject = {};
  29604. serializationObject.name = mesh.name;
  29605. serializationObject.id = mesh.id;
  29606. if (BABYLON.Tags.HasTags(mesh)) {
  29607. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29608. }
  29609. serializationObject.position = mesh.position.asArray();
  29610. if (mesh.rotationQuaternion) {
  29611. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29612. }
  29613. else if (mesh.rotation) {
  29614. serializationObject.rotation = mesh.rotation.asArray();
  29615. }
  29616. serializationObject.scaling = mesh.scaling.asArray();
  29617. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29618. serializationObject.isEnabled = mesh.isEnabled();
  29619. serializationObject.isVisible = mesh.isVisible;
  29620. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29621. serializationObject.pickable = mesh.isPickable;
  29622. serializationObject.receiveShadows = mesh.receiveShadows;
  29623. serializationObject.billboardMode = mesh.billboardMode;
  29624. serializationObject.visibility = mesh.visibility;
  29625. serializationObject.checkCollisions = mesh.checkCollisions;
  29626. // Parent
  29627. if (mesh.parent) {
  29628. serializationObject.parentId = mesh.parent.id;
  29629. }
  29630. // Geometry
  29631. var geometry = mesh._geometry;
  29632. if (geometry) {
  29633. var geometryId = geometry.id;
  29634. serializationObject.geometryId = geometryId;
  29635. if (!mesh.getScene().getGeometryByID(geometryId)) {
  29636. // 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
  29637. serializeGeometry(geometry, serializationScene.geometries);
  29638. }
  29639. // SubMeshes
  29640. serializationObject.subMeshes = [];
  29641. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29642. var subMesh = mesh.subMeshes[subIndex];
  29643. serializationObject.subMeshes.push({
  29644. materialIndex: subMesh.materialIndex,
  29645. verticesStart: subMesh.verticesStart,
  29646. verticesCount: subMesh.verticesCount,
  29647. indexStart: subMesh.indexStart,
  29648. indexCount: subMesh.indexCount
  29649. });
  29650. }
  29651. }
  29652. // Material
  29653. if (mesh.material) {
  29654. serializationObject.materialId = mesh.material.id;
  29655. }
  29656. else {
  29657. mesh.material = null;
  29658. }
  29659. // Skeleton
  29660. if (mesh.skeleton) {
  29661. serializationObject.skeletonId = mesh.skeleton.id;
  29662. }
  29663. // Physics
  29664. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  29665. serializationObject.physicsMass = mesh.getPhysicsMass();
  29666. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  29667. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  29668. switch (mesh.getPhysicsImpostor()) {
  29669. case BABYLON.PhysicsEngine.BoxImpostor:
  29670. serializationObject.physicsImpostor = 1;
  29671. break;
  29672. case BABYLON.PhysicsEngine.SphereImpostor:
  29673. serializationObject.physicsImpostor = 2;
  29674. break;
  29675. }
  29676. }
  29677. // Instances
  29678. serializationObject.instances = [];
  29679. for (var index = 0; index < mesh.instances.length; index++) {
  29680. var instance = mesh.instances[index];
  29681. var serializationInstance = {
  29682. name: instance.name,
  29683. position: instance.position.asArray(),
  29684. rotation: instance.rotation.asArray(),
  29685. rotationQuaternion: instance.rotationQuaternion.asArray(),
  29686. scaling: instance.scaling.asArray()
  29687. };
  29688. serializationObject.instances.push(serializationInstance);
  29689. // Animations
  29690. appendAnimations(instance, serializationInstance);
  29691. }
  29692. // Animations
  29693. appendAnimations(mesh, serializationObject);
  29694. // Layer mask
  29695. serializationObject.layerMask = mesh.layerMask;
  29696. return serializationObject;
  29697. };
  29698. var finalizeSingleMesh = function (mesh, serializationObject) {
  29699. //only works if the mesh is already loaded
  29700. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29701. //serialize material
  29702. if (mesh.material) {
  29703. if (mesh.material instanceof BABYLON.StandardMaterial) {
  29704. serializationObject.materials = serializationObject.materials || [];
  29705. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29706. serializationObject.materials.push(serializeMaterial(mesh.material));
  29707. }
  29708. }
  29709. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  29710. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  29711. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29712. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  29713. }
  29714. }
  29715. }
  29716. //serialize geometry
  29717. var geometry = mesh._geometry;
  29718. if (geometry) {
  29719. if (!serializationObject.geometries) {
  29720. serializationObject.geometries = {};
  29721. serializationObject.geometries.boxes = [];
  29722. serializationObject.geometries.spheres = [];
  29723. serializationObject.geometries.cylinders = [];
  29724. serializationObject.geometries.toruses = [];
  29725. serializationObject.geometries.grounds = [];
  29726. serializationObject.geometries.planes = [];
  29727. serializationObject.geometries.torusKnots = [];
  29728. serializationObject.geometries.vertexData = [];
  29729. }
  29730. serializeGeometry(geometry, serializationObject.geometries);
  29731. }
  29732. // Skeletons
  29733. if (mesh.skeleton) {
  29734. serializationObject.skeletons = serializationObject.skeletons || [];
  29735. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  29736. }
  29737. //serialize the actual mesh
  29738. serializationObject.meshes = serializationObject.meshes || [];
  29739. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29740. }
  29741. };
  29742. var SceneSerializer = (function () {
  29743. function SceneSerializer() {
  29744. }
  29745. SceneSerializer.Serialize = function (scene) {
  29746. var serializationObject = {};
  29747. // Scene
  29748. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  29749. serializationObject.autoClear = scene.autoClear;
  29750. serializationObject.clearColor = scene.clearColor.asArray();
  29751. serializationObject.ambientColor = scene.ambientColor.asArray();
  29752. serializationObject.gravity = scene.gravity.asArray();
  29753. // Fog
  29754. if (scene.fogMode && scene.fogMode !== 0) {
  29755. serializationObject.fogMode = scene.fogMode;
  29756. serializationObject.fogColor = scene.fogColor.asArray();
  29757. serializationObject.fogStart = scene.fogStart;
  29758. serializationObject.fogEnd = scene.fogEnd;
  29759. serializationObject.fogDensity = scene.fogDensity;
  29760. }
  29761. // Lights
  29762. serializationObject.lights = [];
  29763. var index;
  29764. var light;
  29765. for (index = 0; index < scene.lights.length; index++) {
  29766. light = scene.lights[index];
  29767. serializationObject.lights.push(serializeLight(light));
  29768. }
  29769. // Cameras
  29770. serializationObject.cameras = [];
  29771. for (index = 0; index < scene.cameras.length; index++) {
  29772. var camera = scene.cameras[index];
  29773. serializationObject.cameras.push(serializeCamera(camera));
  29774. }
  29775. if (scene.activeCamera) {
  29776. serializationObject.activeCameraID = scene.activeCamera.id;
  29777. }
  29778. // Materials
  29779. serializationObject.materials = [];
  29780. serializationObject.multiMaterials = [];
  29781. var material;
  29782. for (index = 0; index < scene.materials.length; index++) {
  29783. material = scene.materials[index];
  29784. serializationObject.materials.push(serializeMaterial(material));
  29785. }
  29786. // MultiMaterials
  29787. serializationObject.multiMaterials = [];
  29788. for (index = 0; index < scene.multiMaterials.length; index++) {
  29789. var multiMaterial = scene.multiMaterials[index];
  29790. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  29791. }
  29792. for (index = 0; index < scene.materials.length; index++) {
  29793. material = scene.materials[index];
  29794. if (material instanceof BABYLON.StandardMaterial) {
  29795. serializationObject.materials.push(serializeMaterial(material));
  29796. }
  29797. else if (material instanceof BABYLON.MultiMaterial) {
  29798. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  29799. }
  29800. }
  29801. // Skeletons
  29802. serializationObject.skeletons = [];
  29803. for (index = 0; index < scene.skeletons.length; index++) {
  29804. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  29805. }
  29806. // Geometries
  29807. serializationObject.geometries = {};
  29808. serializationObject.geometries.boxes = [];
  29809. serializationObject.geometries.spheres = [];
  29810. serializationObject.geometries.cylinders = [];
  29811. serializationObject.geometries.toruses = [];
  29812. serializationObject.geometries.grounds = [];
  29813. serializationObject.geometries.planes = [];
  29814. serializationObject.geometries.torusKnots = [];
  29815. serializationObject.geometries.vertexData = [];
  29816. serializedGeometries = [];
  29817. var geometries = scene.getGeometries();
  29818. for (index = 0; index < geometries.length; index++) {
  29819. var geometry = geometries[index];
  29820. if (geometry.isReady()) {
  29821. serializeGeometry(geometry, serializationObject.geometries);
  29822. }
  29823. }
  29824. // Meshes
  29825. serializationObject.meshes = [];
  29826. for (index = 0; index < scene.meshes.length; index++) {
  29827. var abstractMesh = scene.meshes[index];
  29828. if (abstractMesh instanceof BABYLON.Mesh) {
  29829. var mesh = abstractMesh;
  29830. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29831. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29832. }
  29833. }
  29834. }
  29835. // Particles Systems
  29836. serializationObject.particleSystems = [];
  29837. for (index = 0; index < scene.particleSystems.length; index++) {
  29838. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  29839. }
  29840. // Lens flares
  29841. serializationObject.lensFlareSystems = [];
  29842. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  29843. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  29844. }
  29845. // Shadows
  29846. serializationObject.shadowGenerators = [];
  29847. for (index = 0; index < scene.lights.length; index++) {
  29848. light = scene.lights[index];
  29849. if (light.getShadowGenerator()) {
  29850. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  29851. }
  29852. }
  29853. return serializationObject;
  29854. };
  29855. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  29856. if (withParents === void 0) { withParents = false; }
  29857. if (withChildren === void 0) { withChildren = false; }
  29858. var serializationObject = {};
  29859. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  29860. if (withParents || withChildren) {
  29861. //deliberate for loop! not for each, appended should be processed as well.
  29862. for (var i = 0; i < toSerialize.length; ++i) {
  29863. if (withChildren) {
  29864. toSerialize[i].getDescendants().forEach(function (node) {
  29865. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  29866. toSerialize.push(node);
  29867. }
  29868. });
  29869. }
  29870. //make sure the array doesn't contain the object already
  29871. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  29872. toSerialize.push(toSerialize[i].parent);
  29873. }
  29874. }
  29875. }
  29876. toSerialize.forEach(function (mesh) {
  29877. finalizeSingleMesh(mesh, serializationObject);
  29878. });
  29879. return serializationObject;
  29880. };
  29881. return SceneSerializer;
  29882. })();
  29883. BABYLON.SceneSerializer = SceneSerializer;
  29884. })(BABYLON || (BABYLON = {}));
  29885. var BABYLON;
  29886. (function (BABYLON) {
  29887. // Unique ID when we import meshes from Babylon to CSG
  29888. var currentCSGMeshId = 0;
  29889. // # class Vertex
  29890. // Represents a vertex of a polygon. Use your own vertex class instead of this
  29891. // one to provide additional features like texture coordinates and vertex
  29892. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  29893. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  29894. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  29895. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  29896. // is not used anywhere else.
  29897. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  29898. var Vertex = (function () {
  29899. function Vertex(pos, normal, uv) {
  29900. this.pos = pos;
  29901. this.normal = normal;
  29902. this.uv = uv;
  29903. }
  29904. Vertex.prototype.clone = function () {
  29905. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  29906. };
  29907. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  29908. // orientation of a polygon is flipped.
  29909. Vertex.prototype.flip = function () {
  29910. this.normal = this.normal.scale(-1);
  29911. };
  29912. // Create a new vertex between this vertex and `other` by linearly
  29913. // interpolating all properties using a parameter of `t`. Subclasses should
  29914. // override this to interpolate additional properties.
  29915. Vertex.prototype.interpolate = function (other, t) {
  29916. 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));
  29917. };
  29918. return Vertex;
  29919. })();
  29920. // # class Plane
  29921. // Represents a plane in 3D space.
  29922. var Plane = (function () {
  29923. function Plane(normal, w) {
  29924. this.normal = normal;
  29925. this.w = w;
  29926. }
  29927. Plane.FromPoints = function (a, b, c) {
  29928. var v0 = c.subtract(a);
  29929. var v1 = b.subtract(a);
  29930. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  29931. return null;
  29932. }
  29933. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  29934. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  29935. };
  29936. Plane.prototype.clone = function () {
  29937. return new Plane(this.normal.clone(), this.w);
  29938. };
  29939. Plane.prototype.flip = function () {
  29940. this.normal.scaleInPlace(-1);
  29941. this.w = -this.w;
  29942. };
  29943. // Split `polygon` by this plane if needed, then put the polygon or polygon
  29944. // fragments in the appropriate lists. Coplanar polygons go into either
  29945. // `coplanarFront` or `coplanarBack` depending on their orientation with
  29946. // respect to this plane. Polygons in front or in back of this plane go into
  29947. // either `front` or `back`.
  29948. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  29949. var COPLANAR = 0;
  29950. var FRONT = 1;
  29951. var BACK = 2;
  29952. var SPANNING = 3;
  29953. // Classify each point as well as the entire polygon into one of the above
  29954. // four classes.
  29955. var polygonType = 0;
  29956. var types = [];
  29957. for (var i = 0; i < polygon.vertices.length; i++) {
  29958. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  29959. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  29960. polygonType |= type;
  29961. types.push(type);
  29962. }
  29963. // Put the polygon in the correct list, splitting it when necessary.
  29964. switch (polygonType) {
  29965. case COPLANAR:
  29966. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  29967. break;
  29968. case FRONT:
  29969. front.push(polygon);
  29970. break;
  29971. case BACK:
  29972. back.push(polygon);
  29973. break;
  29974. case SPANNING:
  29975. var f = [], b = [];
  29976. for (i = 0; i < polygon.vertices.length; i++) {
  29977. var j = (i + 1) % polygon.vertices.length;
  29978. var ti = types[i], tj = types[j];
  29979. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  29980. if (ti != BACK)
  29981. f.push(vi);
  29982. if (ti != FRONT)
  29983. b.push(ti != BACK ? vi.clone() : vi);
  29984. if ((ti | tj) == SPANNING) {
  29985. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  29986. var v = vi.interpolate(vj, t);
  29987. f.push(v);
  29988. b.push(v.clone());
  29989. }
  29990. }
  29991. if (f.length >= 3) {
  29992. var poly = new Polygon(f, polygon.shared);
  29993. if (poly.plane)
  29994. front.push(poly);
  29995. }
  29996. if (b.length >= 3) {
  29997. poly = new Polygon(b, polygon.shared);
  29998. if (poly.plane)
  29999. back.push(poly);
  30000. }
  30001. break;
  30002. }
  30003. };
  30004. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30005. // point is on the plane.
  30006. Plane.EPSILON = 1e-5;
  30007. return Plane;
  30008. })();
  30009. // # class Polygon
  30010. // Represents a convex polygon. The vertices used to initialize a polygon must
  30011. // be coplanar and form a convex loop.
  30012. //
  30013. // Each convex polygon has a `shared` property, which is shared between all
  30014. // polygons that are clones of each other or were split from the same polygon.
  30015. // This can be used to define per-polygon properties (such as surface color).
  30016. var Polygon = (function () {
  30017. function Polygon(vertices, shared) {
  30018. this.vertices = vertices;
  30019. this.shared = shared;
  30020. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30021. }
  30022. Polygon.prototype.clone = function () {
  30023. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30024. return new Polygon(vertices, this.shared);
  30025. };
  30026. Polygon.prototype.flip = function () {
  30027. this.vertices.reverse().map(function (v) { v.flip(); });
  30028. this.plane.flip();
  30029. };
  30030. return Polygon;
  30031. })();
  30032. // # class Node
  30033. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30034. // by picking a polygon to split along. That polygon (and all other coplanar
  30035. // polygons) are added directly to that node and the other polygons are added to
  30036. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30037. // no distinction between internal and leaf nodes.
  30038. var Node = (function () {
  30039. function Node(polygons) {
  30040. this.plane = null;
  30041. this.front = null;
  30042. this.back = null;
  30043. this.polygons = [];
  30044. if (polygons) {
  30045. this.build(polygons);
  30046. }
  30047. }
  30048. Node.prototype.clone = function () {
  30049. var node = new Node();
  30050. node.plane = this.plane && this.plane.clone();
  30051. node.front = this.front && this.front.clone();
  30052. node.back = this.back && this.back.clone();
  30053. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30054. return node;
  30055. };
  30056. // Convert solid space to empty space and empty space to solid space.
  30057. Node.prototype.invert = function () {
  30058. for (var i = 0; i < this.polygons.length; i++) {
  30059. this.polygons[i].flip();
  30060. }
  30061. if (this.plane) {
  30062. this.plane.flip();
  30063. }
  30064. if (this.front) {
  30065. this.front.invert();
  30066. }
  30067. if (this.back) {
  30068. this.back.invert();
  30069. }
  30070. var temp = this.front;
  30071. this.front = this.back;
  30072. this.back = temp;
  30073. };
  30074. // Recursively remove all polygons in `polygons` that are inside this BSP
  30075. // tree.
  30076. Node.prototype.clipPolygons = function (polygons) {
  30077. if (!this.plane)
  30078. return polygons.slice();
  30079. var front = [], back = [];
  30080. for (var i = 0; i < polygons.length; i++) {
  30081. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30082. }
  30083. if (this.front) {
  30084. front = this.front.clipPolygons(front);
  30085. }
  30086. if (this.back) {
  30087. back = this.back.clipPolygons(back);
  30088. }
  30089. else {
  30090. back = [];
  30091. }
  30092. return front.concat(back);
  30093. };
  30094. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30095. // `bsp`.
  30096. Node.prototype.clipTo = function (bsp) {
  30097. this.polygons = bsp.clipPolygons(this.polygons);
  30098. if (this.front)
  30099. this.front.clipTo(bsp);
  30100. if (this.back)
  30101. this.back.clipTo(bsp);
  30102. };
  30103. // Return a list of all polygons in this BSP tree.
  30104. Node.prototype.allPolygons = function () {
  30105. var polygons = this.polygons.slice();
  30106. if (this.front)
  30107. polygons = polygons.concat(this.front.allPolygons());
  30108. if (this.back)
  30109. polygons = polygons.concat(this.back.allPolygons());
  30110. return polygons;
  30111. };
  30112. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30113. // new polygons are filtered down to the bottom of the tree and become new
  30114. // nodes there. Each set of polygons is partitioned using the first polygon
  30115. // (no heuristic is used to pick a good split).
  30116. Node.prototype.build = function (polygons) {
  30117. if (!polygons.length)
  30118. return;
  30119. if (!this.plane)
  30120. this.plane = polygons[0].plane.clone();
  30121. var front = [], back = [];
  30122. for (var i = 0; i < polygons.length; i++) {
  30123. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30124. }
  30125. if (front.length) {
  30126. if (!this.front)
  30127. this.front = new Node();
  30128. this.front.build(front);
  30129. }
  30130. if (back.length) {
  30131. if (!this.back)
  30132. this.back = new Node();
  30133. this.back.build(back);
  30134. }
  30135. };
  30136. return Node;
  30137. })();
  30138. var CSG = (function () {
  30139. function CSG() {
  30140. this.polygons = new Array();
  30141. }
  30142. // Convert BABYLON.Mesh to BABYLON.CSG
  30143. CSG.FromMesh = function (mesh) {
  30144. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30145. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30146. if (mesh instanceof BABYLON.Mesh) {
  30147. mesh.computeWorldMatrix(true);
  30148. matrix = mesh.getWorldMatrix();
  30149. meshPosition = mesh.position.clone();
  30150. meshRotation = mesh.rotation.clone();
  30151. if (mesh.rotationQuaternion) {
  30152. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30153. }
  30154. meshScaling = mesh.scaling.clone();
  30155. }
  30156. else {
  30157. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30158. }
  30159. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30160. var subMeshes = mesh.subMeshes;
  30161. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30162. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30163. vertices = [];
  30164. for (var j = 0; j < 3; j++) {
  30165. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30166. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30167. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30168. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30169. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30170. vertex = new Vertex(position, normal, uv);
  30171. vertices.push(vertex);
  30172. }
  30173. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30174. // To handle the case of degenerated triangle
  30175. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30176. if (polygon.plane)
  30177. polygons.push(polygon);
  30178. }
  30179. }
  30180. var csg = CSG.FromPolygons(polygons);
  30181. csg.matrix = matrix;
  30182. csg.position = meshPosition;
  30183. csg.rotation = meshRotation;
  30184. csg.scaling = meshScaling;
  30185. csg.rotationQuaternion = meshRotationQuaternion;
  30186. currentCSGMeshId++;
  30187. return csg;
  30188. };
  30189. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30190. CSG.FromPolygons = function (polygons) {
  30191. var csg = new CSG();
  30192. csg.polygons = polygons;
  30193. return csg;
  30194. };
  30195. CSG.prototype.clone = function () {
  30196. var csg = new CSG();
  30197. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30198. csg.copyTransformAttributes(this);
  30199. return csg;
  30200. };
  30201. CSG.prototype.toPolygons = function () {
  30202. return this.polygons;
  30203. };
  30204. CSG.prototype.union = function (csg) {
  30205. var a = new Node(this.clone().polygons);
  30206. var b = new Node(csg.clone().polygons);
  30207. a.clipTo(b);
  30208. b.clipTo(a);
  30209. b.invert();
  30210. b.clipTo(a);
  30211. b.invert();
  30212. a.build(b.allPolygons());
  30213. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30214. };
  30215. CSG.prototype.unionInPlace = function (csg) {
  30216. var a = new Node(this.polygons);
  30217. var b = new Node(csg.polygons);
  30218. a.clipTo(b);
  30219. b.clipTo(a);
  30220. b.invert();
  30221. b.clipTo(a);
  30222. b.invert();
  30223. a.build(b.allPolygons());
  30224. this.polygons = a.allPolygons();
  30225. };
  30226. CSG.prototype.subtract = function (csg) {
  30227. var a = new Node(this.clone().polygons);
  30228. var b = new Node(csg.clone().polygons);
  30229. a.invert();
  30230. a.clipTo(b);
  30231. b.clipTo(a);
  30232. b.invert();
  30233. b.clipTo(a);
  30234. b.invert();
  30235. a.build(b.allPolygons());
  30236. a.invert();
  30237. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30238. };
  30239. CSG.prototype.subtractInPlace = function (csg) {
  30240. var a = new Node(this.polygons);
  30241. var b = new Node(csg.polygons);
  30242. a.invert();
  30243. a.clipTo(b);
  30244. b.clipTo(a);
  30245. b.invert();
  30246. b.clipTo(a);
  30247. b.invert();
  30248. a.build(b.allPolygons());
  30249. a.invert();
  30250. this.polygons = a.allPolygons();
  30251. };
  30252. CSG.prototype.intersect = function (csg) {
  30253. var a = new Node(this.clone().polygons);
  30254. var b = new Node(csg.clone().polygons);
  30255. a.invert();
  30256. b.clipTo(a);
  30257. b.invert();
  30258. a.clipTo(b);
  30259. b.clipTo(a);
  30260. a.build(b.allPolygons());
  30261. a.invert();
  30262. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30263. };
  30264. CSG.prototype.intersectInPlace = function (csg) {
  30265. var a = new Node(this.polygons);
  30266. var b = new Node(csg.polygons);
  30267. a.invert();
  30268. b.clipTo(a);
  30269. b.invert();
  30270. a.clipTo(b);
  30271. b.clipTo(a);
  30272. a.build(b.allPolygons());
  30273. a.invert();
  30274. this.polygons = a.allPolygons();
  30275. };
  30276. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30277. // not modified.
  30278. CSG.prototype.inverse = function () {
  30279. var csg = this.clone();
  30280. csg.inverseInPlace();
  30281. return csg;
  30282. };
  30283. CSG.prototype.inverseInPlace = function () {
  30284. this.polygons.map(function (p) { p.flip(); });
  30285. };
  30286. // This is used to keep meshes transformations so they can be restored
  30287. // when we build back a Babylon Mesh
  30288. // NB : All CSG operations are performed in world coordinates
  30289. CSG.prototype.copyTransformAttributes = function (csg) {
  30290. this.matrix = csg.matrix;
  30291. this.position = csg.position;
  30292. this.rotation = csg.rotation;
  30293. this.scaling = csg.scaling;
  30294. this.rotationQuaternion = csg.rotationQuaternion;
  30295. return this;
  30296. };
  30297. // Build Raw mesh from CSG
  30298. // Coordinates here are in world space
  30299. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30300. var matrix = this.matrix.clone();
  30301. matrix.invert();
  30302. 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;
  30303. if (keepSubMeshes) {
  30304. // Sort Polygons, since subMeshes are indices range
  30305. polygons.sort(function (a, b) {
  30306. if (a.shared.meshId === b.shared.meshId) {
  30307. return a.shared.subMeshId - b.shared.subMeshId;
  30308. }
  30309. else {
  30310. return a.shared.meshId - b.shared.meshId;
  30311. }
  30312. });
  30313. }
  30314. for (var i = 0, il = polygons.length; i < il; i++) {
  30315. polygon = polygons[i];
  30316. // Building SubMeshes
  30317. if (!subMesh_dict[polygon.shared.meshId]) {
  30318. subMesh_dict[polygon.shared.meshId] = {};
  30319. }
  30320. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30321. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30322. indexStart: +Infinity,
  30323. indexEnd: -Infinity,
  30324. materialIndex: polygon.shared.materialIndex
  30325. };
  30326. }
  30327. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30328. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30329. polygonIndices[0] = 0;
  30330. polygonIndices[1] = j - 1;
  30331. polygonIndices[2] = j;
  30332. for (var k = 0; k < 3; k++) {
  30333. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30334. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30335. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30336. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30337. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30338. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30339. // Check if 2 points can be merged
  30340. if (!(typeof vertex_idx !== 'undefined' &&
  30341. normals[vertex_idx * 3] === localNormal.x &&
  30342. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30343. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30344. uvs[vertex_idx * 2] === uv.x &&
  30345. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30346. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30347. uvs.push(uv.x, uv.y);
  30348. normals.push(normal.x, normal.y, normal.z);
  30349. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30350. }
  30351. indices.push(vertex_idx);
  30352. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30353. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30354. currentIndex++;
  30355. }
  30356. }
  30357. }
  30358. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30359. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30360. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30361. mesh.setIndices(indices);
  30362. if (keepSubMeshes) {
  30363. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30364. var materialIndexOffset = 0, materialMaxIndex;
  30365. mesh.subMeshes.length = 0;
  30366. for (var m in subMesh_dict) {
  30367. materialMaxIndex = -1;
  30368. for (var sm in subMesh_dict[m]) {
  30369. subMesh_obj = subMesh_dict[m][sm];
  30370. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30371. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30372. }
  30373. materialIndexOffset += ++materialMaxIndex;
  30374. }
  30375. }
  30376. return mesh;
  30377. };
  30378. // Build Mesh from CSG taking material and transforms into account
  30379. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30380. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30381. mesh.material = material;
  30382. mesh.position.copyFrom(this.position);
  30383. mesh.rotation.copyFrom(this.rotation);
  30384. if (this.rotationQuaternion) {
  30385. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30386. }
  30387. mesh.scaling.copyFrom(this.scaling);
  30388. mesh.computeWorldMatrix(true);
  30389. return mesh;
  30390. };
  30391. return CSG;
  30392. })();
  30393. BABYLON.CSG = CSG;
  30394. })(BABYLON || (BABYLON = {}));
  30395. var BABYLON;
  30396. (function (BABYLON) {
  30397. var VRDistortionCorrectionPostProcess = (function (_super) {
  30398. __extends(VRDistortionCorrectionPostProcess, _super);
  30399. //ANY
  30400. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30401. var _this = this;
  30402. _super.call(this, name, "vrDistortionCorrection", [
  30403. 'LensCenter',
  30404. 'Scale',
  30405. 'ScaleIn',
  30406. 'HmdWarpParam'
  30407. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30408. this._isRightEye = isRightEye;
  30409. this._distortionFactors = vrMetrics.distortionK;
  30410. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30411. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30412. this.onSizeChanged = function () {
  30413. _this.aspectRatio = _this.width * .5 / _this.height;
  30414. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30415. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30416. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30417. };
  30418. this.onApply = function (effect) {
  30419. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30420. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30421. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30422. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30423. };
  30424. }
  30425. return VRDistortionCorrectionPostProcess;
  30426. })(BABYLON.PostProcess);
  30427. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30428. })(BABYLON || (BABYLON = {}));
  30429. // Mainly based on these 2 articles :
  30430. // 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
  30431. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30432. var BABYLON;
  30433. (function (BABYLON) {
  30434. (function (JoystickAxis) {
  30435. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30436. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30437. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30438. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30439. var JoystickAxis = BABYLON.JoystickAxis;
  30440. var VirtualJoystick = (function () {
  30441. function VirtualJoystick(leftJoystick) {
  30442. var _this = this;
  30443. if (leftJoystick) {
  30444. this._leftJoystick = true;
  30445. }
  30446. else {
  30447. this._leftJoystick = false;
  30448. }
  30449. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30450. VirtualJoystick._globalJoystickIndex++;
  30451. // By default left & right arrow keys are moving the X
  30452. // and up & down keys are moving the Y
  30453. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30454. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30455. this.reverseLeftRight = false;
  30456. this.reverseUpDown = false;
  30457. // collections of pointers
  30458. this._touches = new BABYLON.SmartCollection();
  30459. this.deltaPosition = BABYLON.Vector3.Zero();
  30460. this._joystickSensibility = 25;
  30461. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30462. this._rotationSpeed = 25;
  30463. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30464. this._rotateOnAxisRelativeToMesh = false;
  30465. this._onResize = function (evt) {
  30466. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30467. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30468. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30469. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30470. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30471. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30472. };
  30473. // injecting a canvas element on top of the canvas 3D game
  30474. if (!VirtualJoystick.vjCanvas) {
  30475. window.addEventListener("resize", this._onResize, false);
  30476. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30477. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30478. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30479. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30480. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30481. VirtualJoystick.vjCanvas.style.width = "100%";
  30482. VirtualJoystick.vjCanvas.style.height = "100%";
  30483. VirtualJoystick.vjCanvas.style.position = "absolute";
  30484. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30485. VirtualJoystick.vjCanvas.style.top = "0px";
  30486. VirtualJoystick.vjCanvas.style.left = "0px";
  30487. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30488. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30489. // Support for jQuery PEP polyfill
  30490. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30491. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30492. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30493. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30494. document.body.appendChild(VirtualJoystick.vjCanvas);
  30495. }
  30496. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30497. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30498. this.pressed = false;
  30499. // default joystick color
  30500. this._joystickColor = "cyan";
  30501. this._joystickPointerID = -1;
  30502. // current joystick position
  30503. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30504. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30505. // origin joystick position
  30506. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30507. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30508. this._onPointerDownHandlerRef = function (evt) {
  30509. _this._onPointerDown(evt);
  30510. };
  30511. this._onPointerMoveHandlerRef = function (evt) {
  30512. _this._onPointerMove(evt);
  30513. };
  30514. this._onPointerOutHandlerRef = function (evt) {
  30515. _this._onPointerUp(evt);
  30516. };
  30517. this._onPointerUpHandlerRef = function (evt) {
  30518. _this._onPointerUp(evt);
  30519. };
  30520. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30521. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30522. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30523. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30524. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30525. evt.preventDefault(); // Disables system menu
  30526. }, false);
  30527. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30528. }
  30529. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30530. this._joystickSensibility = newJoystickSensibility;
  30531. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30532. };
  30533. VirtualJoystick.prototype._onPointerDown = function (e) {
  30534. var positionOnScreenCondition;
  30535. e.preventDefault();
  30536. if (this._leftJoystick === true) {
  30537. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30538. }
  30539. else {
  30540. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30541. }
  30542. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30543. // First contact will be dedicated to the virtual joystick
  30544. this._joystickPointerID = e.pointerId;
  30545. this._joystickPointerStartPos.x = e.clientX;
  30546. this._joystickPointerStartPos.y = e.clientY;
  30547. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30548. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30549. this._deltaJoystickVector.x = 0;
  30550. this._deltaJoystickVector.y = 0;
  30551. this.pressed = true;
  30552. this._touches.add(e.pointerId.toString(), e);
  30553. }
  30554. else {
  30555. // You can only trigger the action buttons with a joystick declared
  30556. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30557. this._action();
  30558. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30559. }
  30560. }
  30561. };
  30562. VirtualJoystick.prototype._onPointerMove = function (e) {
  30563. // If the current pointer is the one associated to the joystick (first touch contact)
  30564. if (this._joystickPointerID == e.pointerId) {
  30565. this._joystickPointerPos.x = e.clientX;
  30566. this._joystickPointerPos.y = e.clientY;
  30567. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30568. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30569. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30570. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30571. switch (this._axisTargetedByLeftAndRight) {
  30572. case JoystickAxis.X:
  30573. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30574. break;
  30575. case JoystickAxis.Y:
  30576. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30577. break;
  30578. case JoystickAxis.Z:
  30579. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30580. break;
  30581. }
  30582. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30583. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30584. switch (this._axisTargetedByUpAndDown) {
  30585. case JoystickAxis.X:
  30586. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30587. break;
  30588. case JoystickAxis.Y:
  30589. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30590. break;
  30591. case JoystickAxis.Z:
  30592. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30593. break;
  30594. }
  30595. }
  30596. else {
  30597. if (this._touches.item(e.pointerId.toString())) {
  30598. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30599. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30600. }
  30601. }
  30602. };
  30603. VirtualJoystick.prototype._onPointerUp = function (e) {
  30604. if (this._joystickPointerID == e.pointerId) {
  30605. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30606. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30607. this._joystickPointerID = -1;
  30608. this.pressed = false;
  30609. }
  30610. else {
  30611. var touch = this._touches.item(e.pointerId.toString());
  30612. if (touch) {
  30613. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30614. }
  30615. }
  30616. this._deltaJoystickVector.x = 0;
  30617. this._deltaJoystickVector.y = 0;
  30618. this._touches.remove(e.pointerId.toString());
  30619. };
  30620. /**
  30621. * Change the color of the virtual joystick
  30622. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30623. */
  30624. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30625. this._joystickColor = newColor;
  30626. };
  30627. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  30628. this._action = action;
  30629. };
  30630. // Define which axis you'd like to control for left & right
  30631. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  30632. switch (axis) {
  30633. case JoystickAxis.X:
  30634. case JoystickAxis.Y:
  30635. case JoystickAxis.Z:
  30636. this._axisTargetedByLeftAndRight = axis;
  30637. break;
  30638. default:
  30639. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30640. break;
  30641. }
  30642. };
  30643. // Define which axis you'd like to control for up & down
  30644. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  30645. switch (axis) {
  30646. case JoystickAxis.X:
  30647. case JoystickAxis.Y:
  30648. case JoystickAxis.Z:
  30649. this._axisTargetedByUpAndDown = axis;
  30650. break;
  30651. default:
  30652. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30653. break;
  30654. }
  30655. };
  30656. VirtualJoystick.prototype._clearCanvas = function () {
  30657. if (this._leftJoystick) {
  30658. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  30659. }
  30660. else {
  30661. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  30662. }
  30663. };
  30664. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  30665. var _this = this;
  30666. if (this.pressed) {
  30667. this._touches.forEach(function (touch) {
  30668. if (touch.pointerId === _this._joystickPointerID) {
  30669. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  30670. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  30671. VirtualJoystick.vjCanvasContext.beginPath();
  30672. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30673. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30674. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  30675. VirtualJoystick.vjCanvasContext.stroke();
  30676. VirtualJoystick.vjCanvasContext.closePath();
  30677. VirtualJoystick.vjCanvasContext.beginPath();
  30678. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30679. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30680. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  30681. VirtualJoystick.vjCanvasContext.stroke();
  30682. VirtualJoystick.vjCanvasContext.closePath();
  30683. VirtualJoystick.vjCanvasContext.beginPath();
  30684. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30685. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  30686. VirtualJoystick.vjCanvasContext.stroke();
  30687. VirtualJoystick.vjCanvasContext.closePath();
  30688. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  30689. }
  30690. else {
  30691. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30692. VirtualJoystick.vjCanvasContext.beginPath();
  30693. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  30694. VirtualJoystick.vjCanvasContext.beginPath();
  30695. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  30696. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30697. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  30698. VirtualJoystick.vjCanvasContext.stroke();
  30699. VirtualJoystick.vjCanvasContext.closePath();
  30700. touch.prevX = touch.x;
  30701. touch.prevY = touch.y;
  30702. }
  30703. ;
  30704. });
  30705. }
  30706. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30707. };
  30708. VirtualJoystick.prototype.releaseCanvas = function () {
  30709. if (VirtualJoystick.vjCanvas) {
  30710. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  30711. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  30712. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  30713. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  30714. window.removeEventListener("resize", this._onResize);
  30715. document.body.removeChild(VirtualJoystick.vjCanvas);
  30716. VirtualJoystick.vjCanvas = null;
  30717. }
  30718. };
  30719. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  30720. VirtualJoystick._globalJoystickIndex = 0;
  30721. return VirtualJoystick;
  30722. })();
  30723. BABYLON.VirtualJoystick = VirtualJoystick;
  30724. })(BABYLON || (BABYLON = {}));
  30725. var BABYLON;
  30726. (function (BABYLON) {
  30727. // We're mainly based on the logic defined into the FreeCamera code
  30728. var VirtualJoysticksCamera = (function (_super) {
  30729. __extends(VirtualJoysticksCamera, _super);
  30730. function VirtualJoysticksCamera(name, position, scene) {
  30731. _super.call(this, name, position, scene);
  30732. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  30733. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  30734. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  30735. this._leftjoystick.setJoystickSensibility(0.15);
  30736. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  30737. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  30738. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  30739. this._rightjoystick.reverseUpDown = true;
  30740. this._rightjoystick.setJoystickSensibility(0.05);
  30741. this._rightjoystick.setJoystickColor("yellow");
  30742. }
  30743. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  30744. return this._leftjoystick;
  30745. };
  30746. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  30747. return this._rightjoystick;
  30748. };
  30749. VirtualJoysticksCamera.prototype._checkInputs = function () {
  30750. var speed = this._computeLocalCameraSpeed() * 50;
  30751. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  30752. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  30753. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  30754. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  30755. if (!this._leftjoystick.pressed) {
  30756. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  30757. }
  30758. if (!this._rightjoystick.pressed) {
  30759. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  30760. }
  30761. _super.prototype._checkInputs.call(this);
  30762. };
  30763. VirtualJoysticksCamera.prototype.dispose = function () {
  30764. this._leftjoystick.releaseCanvas();
  30765. _super.prototype.dispose.call(this);
  30766. };
  30767. return VirtualJoysticksCamera;
  30768. })(BABYLON.FreeCamera);
  30769. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  30770. })(BABYLON || (BABYLON = {}));
  30771. var BABYLON;
  30772. (function (BABYLON) {
  30773. var AnaglyphPostProcess = (function (_super) {
  30774. __extends(AnaglyphPostProcess, _super);
  30775. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  30776. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  30777. }
  30778. return AnaglyphPostProcess;
  30779. })(BABYLON.PostProcess);
  30780. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  30781. })(BABYLON || (BABYLON = {}));
  30782. var BABYLON;
  30783. (function (BABYLON) {
  30784. var OutlineRenderer = (function () {
  30785. function OutlineRenderer(scene) {
  30786. this._scene = scene;
  30787. }
  30788. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  30789. var _this = this;
  30790. if (useOverlay === void 0) { useOverlay = false; }
  30791. var scene = this._scene;
  30792. var engine = this._scene.getEngine();
  30793. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  30794. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  30795. return;
  30796. }
  30797. var mesh = subMesh.getRenderingMesh();
  30798. var material = subMesh.getMaterial();
  30799. engine.enableEffect(this._effect);
  30800. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  30801. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  30802. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30803. // Bones
  30804. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30805. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30806. }
  30807. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  30808. // Alpha test
  30809. if (material && material.needAlphaTesting()) {
  30810. var alphaTexture = material.getAlphaTestTexture();
  30811. this._effect.setTexture("diffuseSampler", alphaTexture);
  30812. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30813. }
  30814. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  30815. };
  30816. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  30817. var defines = [];
  30818. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  30819. var mesh = subMesh.getMesh();
  30820. var material = subMesh.getMaterial();
  30821. // Alpha test
  30822. if (material && material.needAlphaTesting()) {
  30823. defines.push("#define ALPHATEST");
  30824. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30825. attribs.push(BABYLON.VertexBuffer.UVKind);
  30826. defines.push("#define UV1");
  30827. }
  30828. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30829. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30830. defines.push("#define UV2");
  30831. }
  30832. }
  30833. // Bones
  30834. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30835. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30836. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30837. defines.push("#define BONES");
  30838. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30839. }
  30840. // Instances
  30841. if (useInstances) {
  30842. defines.push("#define INSTANCES");
  30843. attribs.push("world0");
  30844. attribs.push("world1");
  30845. attribs.push("world2");
  30846. attribs.push("world3");
  30847. }
  30848. // Get correct effect
  30849. var join = defines.join("\n");
  30850. if (this._cachedDefines !== join) {
  30851. this._cachedDefines = join;
  30852. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  30853. }
  30854. return this._effect.isReady();
  30855. };
  30856. return OutlineRenderer;
  30857. })();
  30858. BABYLON.OutlineRenderer = OutlineRenderer;
  30859. })(BABYLON || (BABYLON = {}));
  30860. var BABYLON;
  30861. (function (BABYLON) {
  30862. var MeshAssetTask = (function () {
  30863. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  30864. this.name = name;
  30865. this.meshesNames = meshesNames;
  30866. this.rootUrl = rootUrl;
  30867. this.sceneFilename = sceneFilename;
  30868. this.isCompleted = false;
  30869. }
  30870. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30871. var _this = this;
  30872. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  30873. _this.loadedMeshes = meshes;
  30874. _this.loadedParticleSystems = particleSystems;
  30875. _this.loadedSkeletons = skeletons;
  30876. _this.isCompleted = true;
  30877. if (_this.onSuccess) {
  30878. _this.onSuccess(_this);
  30879. }
  30880. onSuccess();
  30881. }, null, function () {
  30882. if (_this.onError) {
  30883. _this.onError(_this);
  30884. }
  30885. onError();
  30886. });
  30887. };
  30888. return MeshAssetTask;
  30889. })();
  30890. BABYLON.MeshAssetTask = MeshAssetTask;
  30891. var TextFileAssetTask = (function () {
  30892. function TextFileAssetTask(name, url) {
  30893. this.name = name;
  30894. this.url = url;
  30895. this.isCompleted = false;
  30896. }
  30897. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30898. var _this = this;
  30899. BABYLON.Tools.LoadFile(this.url, function (data) {
  30900. _this.text = data;
  30901. _this.isCompleted = true;
  30902. if (_this.onSuccess) {
  30903. _this.onSuccess(_this);
  30904. }
  30905. onSuccess();
  30906. }, null, scene.database, false, function () {
  30907. if (_this.onError) {
  30908. _this.onError(_this);
  30909. }
  30910. onError();
  30911. });
  30912. };
  30913. return TextFileAssetTask;
  30914. })();
  30915. BABYLON.TextFileAssetTask = TextFileAssetTask;
  30916. var BinaryFileAssetTask = (function () {
  30917. function BinaryFileAssetTask(name, url) {
  30918. this.name = name;
  30919. this.url = url;
  30920. this.isCompleted = false;
  30921. }
  30922. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30923. var _this = this;
  30924. BABYLON.Tools.LoadFile(this.url, function (data) {
  30925. _this.data = data;
  30926. _this.isCompleted = true;
  30927. if (_this.onSuccess) {
  30928. _this.onSuccess(_this);
  30929. }
  30930. onSuccess();
  30931. }, null, scene.database, true, function () {
  30932. if (_this.onError) {
  30933. _this.onError(_this);
  30934. }
  30935. onError();
  30936. });
  30937. };
  30938. return BinaryFileAssetTask;
  30939. })();
  30940. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  30941. var ImageAssetTask = (function () {
  30942. function ImageAssetTask(name, url) {
  30943. this.name = name;
  30944. this.url = url;
  30945. this.isCompleted = false;
  30946. }
  30947. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30948. var _this = this;
  30949. var img = new Image();
  30950. img.onload = function () {
  30951. _this.image = img;
  30952. _this.isCompleted = true;
  30953. if (_this.onSuccess) {
  30954. _this.onSuccess(_this);
  30955. }
  30956. onSuccess();
  30957. };
  30958. img.onerror = function () {
  30959. if (_this.onError) {
  30960. _this.onError(_this);
  30961. }
  30962. onError();
  30963. };
  30964. img.src = this.url;
  30965. };
  30966. return ImageAssetTask;
  30967. })();
  30968. BABYLON.ImageAssetTask = ImageAssetTask;
  30969. var TextureAssetTask = (function () {
  30970. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  30971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30972. this.name = name;
  30973. this.url = url;
  30974. this.noMipmap = noMipmap;
  30975. this.invertY = invertY;
  30976. this.samplingMode = samplingMode;
  30977. this.isCompleted = false;
  30978. }
  30979. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30980. var _this = this;
  30981. var onload = function () {
  30982. _this.isCompleted = true;
  30983. if (_this.onSuccess) {
  30984. _this.onSuccess(_this);
  30985. }
  30986. onSuccess();
  30987. };
  30988. var onerror = function () {
  30989. if (_this.onError) {
  30990. _this.onError(_this);
  30991. }
  30992. onError();
  30993. };
  30994. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  30995. };
  30996. return TextureAssetTask;
  30997. })();
  30998. BABYLON.TextureAssetTask = TextureAssetTask;
  30999. var AssetsManager = (function () {
  31000. function AssetsManager(scene) {
  31001. this._tasks = new Array();
  31002. this._waitingTasksCount = 0;
  31003. this.useDefaultLoadingScreen = true;
  31004. this._scene = scene;
  31005. }
  31006. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31007. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31008. this._tasks.push(task);
  31009. return task;
  31010. };
  31011. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31012. var task = new TextFileAssetTask(taskName, url);
  31013. this._tasks.push(task);
  31014. return task;
  31015. };
  31016. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31017. var task = new BinaryFileAssetTask(taskName, url);
  31018. this._tasks.push(task);
  31019. return task;
  31020. };
  31021. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31022. var task = new ImageAssetTask(taskName, url);
  31023. this._tasks.push(task);
  31024. return task;
  31025. };
  31026. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31027. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31028. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31029. this._tasks.push(task);
  31030. return task;
  31031. };
  31032. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31033. this._waitingTasksCount--;
  31034. if (this._waitingTasksCount === 0) {
  31035. if (this.onFinish) {
  31036. this.onFinish(this._tasks);
  31037. }
  31038. this._scene.getEngine().hideLoadingUI();
  31039. }
  31040. };
  31041. AssetsManager.prototype._runTask = function (task) {
  31042. var _this = this;
  31043. task.run(this._scene, function () {
  31044. if (_this.onTaskSuccess) {
  31045. _this.onTaskSuccess(task);
  31046. }
  31047. _this._decreaseWaitingTasksCount();
  31048. }, function () {
  31049. if (_this.onTaskError) {
  31050. _this.onTaskError(task);
  31051. }
  31052. _this._decreaseWaitingTasksCount();
  31053. });
  31054. };
  31055. AssetsManager.prototype.reset = function () {
  31056. this._tasks = new Array();
  31057. return this;
  31058. };
  31059. AssetsManager.prototype.load = function () {
  31060. this._waitingTasksCount = this._tasks.length;
  31061. if (this._waitingTasksCount === 0) {
  31062. if (this.onFinish) {
  31063. this.onFinish(this._tasks);
  31064. }
  31065. return this;
  31066. }
  31067. if (this.useDefaultLoadingScreen) {
  31068. this._scene.getEngine().displayLoadingUI();
  31069. }
  31070. for (var index = 0; index < this._tasks.length; index++) {
  31071. var task = this._tasks[index];
  31072. this._runTask(task);
  31073. }
  31074. return this;
  31075. };
  31076. return AssetsManager;
  31077. })();
  31078. BABYLON.AssetsManager = AssetsManager;
  31079. })(BABYLON || (BABYLON = {}));
  31080. var BABYLON;
  31081. (function (BABYLON) {
  31082. var VRDeviceOrientationFreeCamera = (function (_super) {
  31083. __extends(VRDeviceOrientationFreeCamera, _super);
  31084. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31085. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31086. _super.call(this, name, position, scene);
  31087. this._alpha = 0;
  31088. this._beta = 0;
  31089. this._gamma = 0;
  31090. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31091. metrics.compensateDistortion = compensateDistortion;
  31092. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31093. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31094. }
  31095. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31096. this._alpha = +evt.alpha | 0;
  31097. this._beta = +evt.beta | 0;
  31098. this._gamma = +evt.gamma | 0;
  31099. if (this._gamma < 0) {
  31100. this._gamma = 90 + this._gamma;
  31101. }
  31102. else {
  31103. // Incline it in the correct angle.
  31104. this._gamma = 270 - this._gamma;
  31105. }
  31106. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31107. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31108. this.rotation.z = this._beta / 180.0 * Math.PI;
  31109. };
  31110. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31111. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31112. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31113. };
  31114. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31115. _super.prototype.detachControl.call(this, element);
  31116. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31117. };
  31118. return VRDeviceOrientationFreeCamera;
  31119. })(BABYLON.FreeCamera);
  31120. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31121. })(BABYLON || (BABYLON = {}));
  31122. var BABYLON;
  31123. (function (BABYLON) {
  31124. var WebVRFreeCamera = (function (_super) {
  31125. __extends(WebVRFreeCamera, _super);
  31126. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31127. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31128. _super.call(this, name, position, scene);
  31129. this._hmdDevice = null;
  31130. this._sensorDevice = null;
  31131. this._cacheState = null;
  31132. this._cacheQuaternion = new BABYLON.Quaternion();
  31133. this._cacheRotation = BABYLON.Vector3.Zero();
  31134. this._vrEnabled = false;
  31135. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31136. metrics.compensateDistortion = compensateDistortion;
  31137. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31138. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31139. }
  31140. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31141. var size = devices.length;
  31142. var i = 0;
  31143. // Reset devices.
  31144. this._sensorDevice = null;
  31145. this._hmdDevice = null;
  31146. // Search for a HmdDevice.
  31147. while (i < size && this._hmdDevice === null) {
  31148. if (devices[i] instanceof HMDVRDevice) {
  31149. this._hmdDevice = devices[i];
  31150. }
  31151. i++;
  31152. }
  31153. i = 0;
  31154. while (i < size && this._sensorDevice === null) {
  31155. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31156. this._sensorDevice = devices[i];
  31157. }
  31158. i++;
  31159. }
  31160. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31161. };
  31162. WebVRFreeCamera.prototype._checkInputs = function () {
  31163. if (this._vrEnabled) {
  31164. this._cacheState = this._sensorDevice.getState();
  31165. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31166. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31167. this.rotation.x = -this._cacheRotation.z;
  31168. this.rotation.y = -this._cacheRotation.y;
  31169. this.rotation.z = this._cacheRotation.x;
  31170. }
  31171. _super.prototype._checkInputs.call(this);
  31172. };
  31173. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31174. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31175. if (navigator.getVRDevices) {
  31176. navigator.getVRDevices().then(this._getWebVRDevices);
  31177. }
  31178. else if (navigator.mozGetVRDevices) {
  31179. navigator.mozGetVRDevices(this._getWebVRDevices);
  31180. }
  31181. };
  31182. WebVRFreeCamera.prototype.detachControl = function (element) {
  31183. _super.prototype.detachControl.call(this, element);
  31184. this._vrEnabled = false;
  31185. };
  31186. return WebVRFreeCamera;
  31187. })(BABYLON.FreeCamera);
  31188. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31189. })(BABYLON || (BABYLON = {}));
  31190. var BABYLON;
  31191. (function (BABYLON) {
  31192. // Standard optimizations
  31193. var SceneOptimization = (function () {
  31194. function SceneOptimization(priority) {
  31195. if (priority === void 0) { priority = 0; }
  31196. this.priority = priority;
  31197. this.apply = function (scene) {
  31198. return true; // Return true if everything that can be done was applied
  31199. };
  31200. }
  31201. return SceneOptimization;
  31202. })();
  31203. BABYLON.SceneOptimization = SceneOptimization;
  31204. var TextureOptimization = (function (_super) {
  31205. __extends(TextureOptimization, _super);
  31206. function TextureOptimization(priority, maximumSize) {
  31207. var _this = this;
  31208. if (priority === void 0) { priority = 0; }
  31209. if (maximumSize === void 0) { maximumSize = 1024; }
  31210. _super.call(this, priority);
  31211. this.priority = priority;
  31212. this.maximumSize = maximumSize;
  31213. this.apply = function (scene) {
  31214. var allDone = true;
  31215. for (var index = 0; index < scene.textures.length; index++) {
  31216. var texture = scene.textures[index];
  31217. if (!texture.canRescale) {
  31218. continue;
  31219. }
  31220. var currentSize = texture.getSize();
  31221. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31222. if (maxDimension > _this.maximumSize) {
  31223. texture.scale(0.5);
  31224. allDone = false;
  31225. }
  31226. }
  31227. return allDone;
  31228. };
  31229. }
  31230. return TextureOptimization;
  31231. })(SceneOptimization);
  31232. BABYLON.TextureOptimization = TextureOptimization;
  31233. var HardwareScalingOptimization = (function (_super) {
  31234. __extends(HardwareScalingOptimization, _super);
  31235. function HardwareScalingOptimization(priority, maximumScale) {
  31236. var _this = this;
  31237. if (priority === void 0) { priority = 0; }
  31238. if (maximumScale === void 0) { maximumScale = 2; }
  31239. _super.call(this, priority);
  31240. this.priority = priority;
  31241. this.maximumScale = maximumScale;
  31242. this._currentScale = 1;
  31243. this.apply = function (scene) {
  31244. _this._currentScale++;
  31245. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31246. return _this._currentScale >= _this.maximumScale;
  31247. };
  31248. }
  31249. return HardwareScalingOptimization;
  31250. })(SceneOptimization);
  31251. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31252. var ShadowsOptimization = (function (_super) {
  31253. __extends(ShadowsOptimization, _super);
  31254. function ShadowsOptimization() {
  31255. _super.apply(this, arguments);
  31256. this.apply = function (scene) {
  31257. scene.shadowsEnabled = false;
  31258. return true;
  31259. };
  31260. }
  31261. return ShadowsOptimization;
  31262. })(SceneOptimization);
  31263. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31264. var PostProcessesOptimization = (function (_super) {
  31265. __extends(PostProcessesOptimization, _super);
  31266. function PostProcessesOptimization() {
  31267. _super.apply(this, arguments);
  31268. this.apply = function (scene) {
  31269. scene.postProcessesEnabled = false;
  31270. return true;
  31271. };
  31272. }
  31273. return PostProcessesOptimization;
  31274. })(SceneOptimization);
  31275. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31276. var LensFlaresOptimization = (function (_super) {
  31277. __extends(LensFlaresOptimization, _super);
  31278. function LensFlaresOptimization() {
  31279. _super.apply(this, arguments);
  31280. this.apply = function (scene) {
  31281. scene.lensFlaresEnabled = false;
  31282. return true;
  31283. };
  31284. }
  31285. return LensFlaresOptimization;
  31286. })(SceneOptimization);
  31287. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31288. var ParticlesOptimization = (function (_super) {
  31289. __extends(ParticlesOptimization, _super);
  31290. function ParticlesOptimization() {
  31291. _super.apply(this, arguments);
  31292. this.apply = function (scene) {
  31293. scene.particlesEnabled = false;
  31294. return true;
  31295. };
  31296. }
  31297. return ParticlesOptimization;
  31298. })(SceneOptimization);
  31299. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31300. var RenderTargetsOptimization = (function (_super) {
  31301. __extends(RenderTargetsOptimization, _super);
  31302. function RenderTargetsOptimization() {
  31303. _super.apply(this, arguments);
  31304. this.apply = function (scene) {
  31305. scene.renderTargetsEnabled = false;
  31306. return true;
  31307. };
  31308. }
  31309. return RenderTargetsOptimization;
  31310. })(SceneOptimization);
  31311. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31312. var MergeMeshesOptimization = (function (_super) {
  31313. __extends(MergeMeshesOptimization, _super);
  31314. function MergeMeshesOptimization() {
  31315. var _this = this;
  31316. _super.apply(this, arguments);
  31317. this._canBeMerged = function (abstractMesh) {
  31318. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31319. return false;
  31320. }
  31321. var mesh = abstractMesh;
  31322. if (!mesh.isVisible || !mesh.isEnabled()) {
  31323. return false;
  31324. }
  31325. if (mesh.instances.length > 0) {
  31326. return false;
  31327. }
  31328. if (mesh.skeleton || mesh.hasLODLevels) {
  31329. return false;
  31330. }
  31331. return true;
  31332. };
  31333. this.apply = function (scene, updateSelectionTree) {
  31334. var globalPool = scene.meshes.slice(0);
  31335. var globalLength = globalPool.length;
  31336. for (var index = 0; index < globalLength; index++) {
  31337. var currentPool = new Array();
  31338. var current = globalPool[index];
  31339. // Checks
  31340. if (!_this._canBeMerged(current)) {
  31341. continue;
  31342. }
  31343. currentPool.push(current);
  31344. // Find compatible meshes
  31345. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31346. var otherMesh = globalPool[subIndex];
  31347. if (!_this._canBeMerged(otherMesh)) {
  31348. continue;
  31349. }
  31350. if (otherMesh.material !== current.material) {
  31351. continue;
  31352. }
  31353. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31354. continue;
  31355. }
  31356. currentPool.push(otherMesh);
  31357. globalLength--;
  31358. globalPool.splice(subIndex, 1);
  31359. subIndex--;
  31360. }
  31361. if (currentPool.length < 2) {
  31362. continue;
  31363. }
  31364. // Merge meshes
  31365. BABYLON.Mesh.MergeMeshes(currentPool);
  31366. }
  31367. if (updateSelectionTree != undefined) {
  31368. if (updateSelectionTree) {
  31369. scene.createOrUpdateSelectionOctree();
  31370. }
  31371. }
  31372. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31373. scene.createOrUpdateSelectionOctree();
  31374. }
  31375. return true;
  31376. };
  31377. }
  31378. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31379. get: function () {
  31380. return MergeMeshesOptimization._UpdateSelectionTree;
  31381. },
  31382. set: function (value) {
  31383. MergeMeshesOptimization._UpdateSelectionTree = value;
  31384. },
  31385. enumerable: true,
  31386. configurable: true
  31387. });
  31388. MergeMeshesOptimization._UpdateSelectionTree = false;
  31389. return MergeMeshesOptimization;
  31390. })(SceneOptimization);
  31391. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31392. // Options
  31393. var SceneOptimizerOptions = (function () {
  31394. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31395. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31396. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31397. this.targetFrameRate = targetFrameRate;
  31398. this.trackerDuration = trackerDuration;
  31399. this.optimizations = new Array();
  31400. }
  31401. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31402. var result = new SceneOptimizerOptions(targetFrameRate);
  31403. var priority = 0;
  31404. result.optimizations.push(new MergeMeshesOptimization(priority));
  31405. result.optimizations.push(new ShadowsOptimization(priority));
  31406. result.optimizations.push(new LensFlaresOptimization(priority));
  31407. // Next priority
  31408. priority++;
  31409. result.optimizations.push(new PostProcessesOptimization(priority));
  31410. result.optimizations.push(new ParticlesOptimization(priority));
  31411. // Next priority
  31412. priority++;
  31413. result.optimizations.push(new TextureOptimization(priority, 1024));
  31414. return result;
  31415. };
  31416. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31417. var result = new SceneOptimizerOptions(targetFrameRate);
  31418. var priority = 0;
  31419. result.optimizations.push(new MergeMeshesOptimization(priority));
  31420. result.optimizations.push(new ShadowsOptimization(priority));
  31421. result.optimizations.push(new LensFlaresOptimization(priority));
  31422. // Next priority
  31423. priority++;
  31424. result.optimizations.push(new PostProcessesOptimization(priority));
  31425. result.optimizations.push(new ParticlesOptimization(priority));
  31426. // Next priority
  31427. priority++;
  31428. result.optimizations.push(new TextureOptimization(priority, 512));
  31429. // Next priority
  31430. priority++;
  31431. result.optimizations.push(new RenderTargetsOptimization(priority));
  31432. // Next priority
  31433. priority++;
  31434. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31435. return result;
  31436. };
  31437. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31438. var result = new SceneOptimizerOptions(targetFrameRate);
  31439. var priority = 0;
  31440. result.optimizations.push(new MergeMeshesOptimization(priority));
  31441. result.optimizations.push(new ShadowsOptimization(priority));
  31442. result.optimizations.push(new LensFlaresOptimization(priority));
  31443. // Next priority
  31444. priority++;
  31445. result.optimizations.push(new PostProcessesOptimization(priority));
  31446. result.optimizations.push(new ParticlesOptimization(priority));
  31447. // Next priority
  31448. priority++;
  31449. result.optimizations.push(new TextureOptimization(priority, 256));
  31450. // Next priority
  31451. priority++;
  31452. result.optimizations.push(new RenderTargetsOptimization(priority));
  31453. // Next priority
  31454. priority++;
  31455. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31456. return result;
  31457. };
  31458. return SceneOptimizerOptions;
  31459. })();
  31460. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31461. // Scene optimizer tool
  31462. var SceneOptimizer = (function () {
  31463. function SceneOptimizer() {
  31464. }
  31465. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31466. // TODO: add an epsilon
  31467. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31468. if (onSuccess) {
  31469. onSuccess();
  31470. }
  31471. return;
  31472. }
  31473. // Apply current level of optimizations
  31474. var allDone = true;
  31475. var noOptimizationApplied = true;
  31476. for (var index = 0; index < options.optimizations.length; index++) {
  31477. var optimization = options.optimizations[index];
  31478. if (optimization.priority === currentPriorityLevel) {
  31479. noOptimizationApplied = false;
  31480. allDone = allDone && optimization.apply(scene);
  31481. }
  31482. }
  31483. // If no optimization was applied, this is a failure :(
  31484. if (noOptimizationApplied) {
  31485. if (onFailure) {
  31486. onFailure();
  31487. }
  31488. return;
  31489. }
  31490. // If all optimizations were done, move to next level
  31491. if (allDone) {
  31492. currentPriorityLevel++;
  31493. }
  31494. // Let's the system running for a specific amount of time before checking FPS
  31495. scene.executeWhenReady(function () {
  31496. setTimeout(function () {
  31497. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31498. }, options.trackerDuration);
  31499. });
  31500. };
  31501. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31502. if (!options) {
  31503. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31504. }
  31505. // Let's the system running for a specific amount of time before checking FPS
  31506. scene.executeWhenReady(function () {
  31507. setTimeout(function () {
  31508. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31509. }, options.trackerDuration);
  31510. });
  31511. };
  31512. return SceneOptimizer;
  31513. })();
  31514. BABYLON.SceneOptimizer = SceneOptimizer;
  31515. })(BABYLON || (BABYLON = {}));
  31516. var BABYLON;
  31517. (function (BABYLON) {
  31518. var Internals;
  31519. (function (Internals) {
  31520. var MeshLODLevel = (function () {
  31521. function MeshLODLevel(distance, mesh) {
  31522. this.distance = distance;
  31523. this.mesh = mesh;
  31524. }
  31525. return MeshLODLevel;
  31526. })();
  31527. Internals.MeshLODLevel = MeshLODLevel;
  31528. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31529. })(BABYLON || (BABYLON = {}));
  31530. var BABYLON;
  31531. (function (BABYLON) {
  31532. var RawTexture = (function (_super) {
  31533. __extends(RawTexture, _super);
  31534. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31535. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31536. if (invertY === void 0) { invertY = false; }
  31537. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31538. _super.call(this, null, scene, !generateMipMaps, invertY);
  31539. this.format = format;
  31540. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31541. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31542. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31543. }
  31544. RawTexture.prototype.update = function (data) {
  31545. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31546. };
  31547. // Statics
  31548. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31549. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31550. if (invertY === void 0) { invertY = false; }
  31551. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31552. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31553. };
  31554. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31555. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31556. if (invertY === void 0) { invertY = false; }
  31557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31558. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31559. };
  31560. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31561. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31562. if (invertY === void 0) { invertY = false; }
  31563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31564. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31565. };
  31566. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31567. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31568. if (invertY === void 0) { invertY = false; }
  31569. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31570. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31571. };
  31572. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31573. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31574. if (invertY === void 0) { invertY = false; }
  31575. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31576. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31577. };
  31578. return RawTexture;
  31579. })(BABYLON.Texture);
  31580. BABYLON.RawTexture = RawTexture;
  31581. })(BABYLON || (BABYLON = {}));
  31582. var BABYLON;
  31583. (function (BABYLON) {
  31584. var IndexedVector2 = (function (_super) {
  31585. __extends(IndexedVector2, _super);
  31586. function IndexedVector2(original, index) {
  31587. _super.call(this, original.x, original.y);
  31588. this.index = index;
  31589. }
  31590. return IndexedVector2;
  31591. })(BABYLON.Vector2);
  31592. var PolygonPoints = (function () {
  31593. function PolygonPoints() {
  31594. this.elements = new Array();
  31595. }
  31596. PolygonPoints.prototype.add = function (originalPoints) {
  31597. var _this = this;
  31598. var result = new Array();
  31599. originalPoints.forEach(function (point) {
  31600. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31601. var newPoint = new IndexedVector2(point, _this.elements.length);
  31602. result.push(newPoint);
  31603. _this.elements.push(newPoint);
  31604. }
  31605. });
  31606. return result;
  31607. };
  31608. PolygonPoints.prototype.computeBounds = function () {
  31609. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31610. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31611. this.elements.forEach(function (point) {
  31612. // x
  31613. if (point.x < lmin.x) {
  31614. lmin.x = point.x;
  31615. }
  31616. else if (point.x > lmax.x) {
  31617. lmax.x = point.x;
  31618. }
  31619. // y
  31620. if (point.y < lmin.y) {
  31621. lmin.y = point.y;
  31622. }
  31623. else if (point.y > lmax.y) {
  31624. lmax.y = point.y;
  31625. }
  31626. });
  31627. return {
  31628. min: lmin,
  31629. max: lmax,
  31630. width: lmax.x - lmin.x,
  31631. height: lmax.y - lmin.y
  31632. };
  31633. };
  31634. return PolygonPoints;
  31635. })();
  31636. var Polygon = (function () {
  31637. function Polygon() {
  31638. }
  31639. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31640. return [
  31641. new BABYLON.Vector2(xmin, ymin),
  31642. new BABYLON.Vector2(xmax, ymin),
  31643. new BABYLON.Vector2(xmax, ymax),
  31644. new BABYLON.Vector2(xmin, ymax)
  31645. ];
  31646. };
  31647. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31648. if (cx === void 0) { cx = 0; }
  31649. if (cy === void 0) { cy = 0; }
  31650. if (numberOfSides === void 0) { numberOfSides = 32; }
  31651. var result = new Array();
  31652. var angle = 0;
  31653. var increment = (Math.PI * 2) / numberOfSides;
  31654. for (var i = 0; i < numberOfSides; i++) {
  31655. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31656. angle -= increment;
  31657. }
  31658. return result;
  31659. };
  31660. Polygon.Parse = function (input) {
  31661. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31662. var i, result = [];
  31663. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31664. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31665. }
  31666. return result;
  31667. };
  31668. Polygon.StartingAt = function (x, y) {
  31669. return BABYLON.Path2.StartingAt(x, y);
  31670. };
  31671. return Polygon;
  31672. })();
  31673. BABYLON.Polygon = Polygon;
  31674. var PolygonMeshBuilder = (function () {
  31675. function PolygonMeshBuilder(name, contours, scene) {
  31676. this._points = new PolygonPoints();
  31677. this._outlinepoints = new PolygonPoints();
  31678. this._holes = [];
  31679. if (!("poly2tri" in window)) {
  31680. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31681. }
  31682. this._name = name;
  31683. this._scene = scene;
  31684. var points;
  31685. if (contours instanceof BABYLON.Path2) {
  31686. points = contours.getPoints();
  31687. }
  31688. else {
  31689. points = contours;
  31690. }
  31691. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31692. this._outlinepoints.add(points);
  31693. }
  31694. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31695. this._swctx.addHole(this._points.add(hole));
  31696. var holepoints = new PolygonPoints();
  31697. holepoints.add(hole);
  31698. this._holes.push(holepoints);
  31699. return this;
  31700. };
  31701. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31702. var _this = this;
  31703. if (updatable === void 0) { updatable = false; }
  31704. var result = new BABYLON.Mesh(this._name, this._scene);
  31705. var normals = [];
  31706. var positions = [];
  31707. var uvs = [];
  31708. var bounds = this._points.computeBounds();
  31709. this._points.elements.forEach(function (p) {
  31710. normals.push(0, 1.0, 0);
  31711. positions.push(p.x, 0, p.y);
  31712. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31713. });
  31714. var indices = [];
  31715. this._swctx.triangulate();
  31716. this._swctx.getTriangles().forEach(function (triangle) {
  31717. triangle.getPoints().forEach(function (point) {
  31718. indices.push(point.index);
  31719. });
  31720. });
  31721. if (depth > 0) {
  31722. var positionscount = (positions.length / 3); //get the current pointcount
  31723. this._points.elements.forEach(function (p) {
  31724. normals.push(0, -1.0, 0);
  31725. positions.push(p.x, -depth, p.y);
  31726. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31727. });
  31728. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31729. var p2;
  31730. var poscounter = 0;
  31731. this._swctx.getTriangles().forEach(function (triangle) {
  31732. triangle.getPoints().forEach(function (point) {
  31733. switch (poscounter) {
  31734. case 0:
  31735. p1 = point;
  31736. break;
  31737. case 1:
  31738. p2 = point;
  31739. break;
  31740. case 2:
  31741. indices.push(point.index + positionscount);
  31742. indices.push(p2.index + positionscount);
  31743. indices.push(p1.index + positionscount);
  31744. poscounter = -1;
  31745. break;
  31746. }
  31747. poscounter++;
  31748. //indices.push((<IndexedVector2>point).index + positionscount);
  31749. });
  31750. });
  31751. //Add the sides
  31752. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31753. this._holes.forEach(function (hole) {
  31754. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31755. });
  31756. }
  31757. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31758. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31759. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31760. result.setIndices(indices);
  31761. return result;
  31762. };
  31763. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31764. var StartIndex = positions.length / 3;
  31765. var ulength = 0;
  31766. for (var i = 0; i < points.elements.length; i++) {
  31767. var p = points.elements[i];
  31768. var p1;
  31769. if ((i + 1) > points.elements.length - 1) {
  31770. p1 = points.elements[0];
  31771. }
  31772. else {
  31773. p1 = points.elements[i + 1];
  31774. }
  31775. positions.push(p.x, 0, p.y);
  31776. positions.push(p.x, -depth, p.y);
  31777. positions.push(p1.x, 0, p1.y);
  31778. positions.push(p1.x, -depth, p1.y);
  31779. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31780. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31781. var v3 = v2.subtract(v1);
  31782. var v4 = new BABYLON.Vector3(0, 1, 0);
  31783. var vn = BABYLON.Vector3.Cross(v3, v4);
  31784. vn = vn.normalize();
  31785. uvs.push(ulength / bounds.width, 0);
  31786. uvs.push(ulength / bounds.width, 1);
  31787. ulength += v3.length();
  31788. uvs.push((ulength / bounds.width), 0);
  31789. uvs.push((ulength / bounds.width), 1);
  31790. if (!flip) {
  31791. normals.push(-vn.x, -vn.y, -vn.z);
  31792. normals.push(-vn.x, -vn.y, -vn.z);
  31793. normals.push(-vn.x, -vn.y, -vn.z);
  31794. normals.push(-vn.x, -vn.y, -vn.z);
  31795. indices.push(StartIndex);
  31796. indices.push(StartIndex + 1);
  31797. indices.push(StartIndex + 2);
  31798. indices.push(StartIndex + 1);
  31799. indices.push(StartIndex + 3);
  31800. indices.push(StartIndex + 2);
  31801. }
  31802. else {
  31803. normals.push(vn.x, vn.y, vn.z);
  31804. normals.push(vn.x, vn.y, vn.z);
  31805. normals.push(vn.x, vn.y, vn.z);
  31806. normals.push(vn.x, vn.y, vn.z);
  31807. indices.push(StartIndex);
  31808. indices.push(StartIndex + 2);
  31809. indices.push(StartIndex + 1);
  31810. indices.push(StartIndex + 1);
  31811. indices.push(StartIndex + 2);
  31812. indices.push(StartIndex + 3);
  31813. }
  31814. StartIndex += 4;
  31815. }
  31816. ;
  31817. };
  31818. return PolygonMeshBuilder;
  31819. })();
  31820. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31821. })(BABYLON || (BABYLON = {}));
  31822. var BABYLON;
  31823. (function (BABYLON) {
  31824. var Octree = (function () {
  31825. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  31826. if (maxDepth === void 0) { maxDepth = 2; }
  31827. this.maxDepth = maxDepth;
  31828. this.dynamicContent = new Array();
  31829. this._maxBlockCapacity = maxBlockCapacity || 64;
  31830. this._selectionContent = new BABYLON.SmartArray(1024);
  31831. this._creationFunc = creationFunc;
  31832. }
  31833. // Methods
  31834. Octree.prototype.update = function (worldMin, worldMax, entries) {
  31835. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  31836. };
  31837. Octree.prototype.addMesh = function (entry) {
  31838. for (var index = 0; index < this.blocks.length; index++) {
  31839. var block = this.blocks[index];
  31840. block.addEntry(entry);
  31841. }
  31842. };
  31843. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  31844. this._selectionContent.reset();
  31845. for (var index = 0; index < this.blocks.length; index++) {
  31846. var block = this.blocks[index];
  31847. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  31848. }
  31849. if (allowDuplicate) {
  31850. this._selectionContent.concat(this.dynamicContent);
  31851. }
  31852. else {
  31853. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31854. }
  31855. return this._selectionContent;
  31856. };
  31857. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  31858. this._selectionContent.reset();
  31859. for (var index = 0; index < this.blocks.length; index++) {
  31860. var block = this.blocks[index];
  31861. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  31862. }
  31863. if (allowDuplicate) {
  31864. this._selectionContent.concat(this.dynamicContent);
  31865. }
  31866. else {
  31867. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31868. }
  31869. return this._selectionContent;
  31870. };
  31871. Octree.prototype.intersectsRay = function (ray) {
  31872. this._selectionContent.reset();
  31873. for (var index = 0; index < this.blocks.length; index++) {
  31874. var block = this.blocks[index];
  31875. block.intersectsRay(ray, this._selectionContent);
  31876. }
  31877. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31878. return this._selectionContent;
  31879. };
  31880. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  31881. target.blocks = new Array();
  31882. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  31883. // Segmenting space
  31884. for (var x = 0; x < 2; x++) {
  31885. for (var y = 0; y < 2; y++) {
  31886. for (var z = 0; z < 2; z++) {
  31887. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  31888. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  31889. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  31890. block.addEntries(entries);
  31891. target.blocks.push(block);
  31892. }
  31893. }
  31894. }
  31895. };
  31896. Octree.CreationFuncForMeshes = function (entry, block) {
  31897. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  31898. block.entries.push(entry);
  31899. }
  31900. };
  31901. Octree.CreationFuncForSubMeshes = function (entry, block) {
  31902. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  31903. block.entries.push(entry);
  31904. }
  31905. };
  31906. return Octree;
  31907. })();
  31908. BABYLON.Octree = Octree;
  31909. })(BABYLON || (BABYLON = {}));
  31910. var BABYLON;
  31911. (function (BABYLON) {
  31912. var OctreeBlock = (function () {
  31913. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  31914. this.entries = new Array();
  31915. this._boundingVectors = new Array();
  31916. this._capacity = capacity;
  31917. this._depth = depth;
  31918. this._maxDepth = maxDepth;
  31919. this._creationFunc = creationFunc;
  31920. this._minPoint = minPoint;
  31921. this._maxPoint = maxPoint;
  31922. this._boundingVectors.push(minPoint.clone());
  31923. this._boundingVectors.push(maxPoint.clone());
  31924. this._boundingVectors.push(minPoint.clone());
  31925. this._boundingVectors[2].x = maxPoint.x;
  31926. this._boundingVectors.push(minPoint.clone());
  31927. this._boundingVectors[3].y = maxPoint.y;
  31928. this._boundingVectors.push(minPoint.clone());
  31929. this._boundingVectors[4].z = maxPoint.z;
  31930. this._boundingVectors.push(maxPoint.clone());
  31931. this._boundingVectors[5].z = minPoint.z;
  31932. this._boundingVectors.push(maxPoint.clone());
  31933. this._boundingVectors[6].x = minPoint.x;
  31934. this._boundingVectors.push(maxPoint.clone());
  31935. this._boundingVectors[7].y = minPoint.y;
  31936. }
  31937. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  31938. // Property
  31939. get: function () {
  31940. return this._capacity;
  31941. },
  31942. enumerable: true,
  31943. configurable: true
  31944. });
  31945. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  31946. get: function () {
  31947. return this._minPoint;
  31948. },
  31949. enumerable: true,
  31950. configurable: true
  31951. });
  31952. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  31953. get: function () {
  31954. return this._maxPoint;
  31955. },
  31956. enumerable: true,
  31957. configurable: true
  31958. });
  31959. // Methods
  31960. OctreeBlock.prototype.addEntry = function (entry) {
  31961. if (this.blocks) {
  31962. for (var index = 0; index < this.blocks.length; index++) {
  31963. var block = this.blocks[index];
  31964. block.addEntry(entry);
  31965. }
  31966. return;
  31967. }
  31968. this._creationFunc(entry, this);
  31969. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  31970. this.createInnerBlocks();
  31971. }
  31972. };
  31973. OctreeBlock.prototype.addEntries = function (entries) {
  31974. for (var index = 0; index < entries.length; index++) {
  31975. var mesh = entries[index];
  31976. this.addEntry(mesh);
  31977. }
  31978. };
  31979. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  31980. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  31981. if (this.blocks) {
  31982. for (var index = 0; index < this.blocks.length; index++) {
  31983. var block = this.blocks[index];
  31984. block.select(frustumPlanes, selection, allowDuplicate);
  31985. }
  31986. return;
  31987. }
  31988. if (allowDuplicate) {
  31989. selection.concat(this.entries);
  31990. }
  31991. else {
  31992. selection.concatWithNoDuplicate(this.entries);
  31993. }
  31994. }
  31995. };
  31996. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  31997. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  31998. if (this.blocks) {
  31999. for (var index = 0; index < this.blocks.length; index++) {
  32000. var block = this.blocks[index];
  32001. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32002. }
  32003. return;
  32004. }
  32005. if (allowDuplicate) {
  32006. selection.concat(this.entries);
  32007. }
  32008. else {
  32009. selection.concatWithNoDuplicate(this.entries);
  32010. }
  32011. }
  32012. };
  32013. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32014. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32015. if (this.blocks) {
  32016. for (var index = 0; index < this.blocks.length; index++) {
  32017. var block = this.blocks[index];
  32018. block.intersectsRay(ray, selection);
  32019. }
  32020. return;
  32021. }
  32022. selection.concatWithNoDuplicate(this.entries);
  32023. }
  32024. };
  32025. OctreeBlock.prototype.createInnerBlocks = function () {
  32026. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32027. };
  32028. return OctreeBlock;
  32029. })();
  32030. BABYLON.OctreeBlock = OctreeBlock;
  32031. })(BABYLON || (BABYLON = {}));
  32032. var BABYLON;
  32033. (function (BABYLON) {
  32034. var BlurPostProcess = (function (_super) {
  32035. __extends(BlurPostProcess, _super);
  32036. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32037. var _this = this;
  32038. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32039. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32040. this.direction = direction;
  32041. this.blurWidth = blurWidth;
  32042. this.onApply = function (effect) {
  32043. effect.setFloat2("screenSize", _this.width, _this.height);
  32044. effect.setVector2("direction", _this.direction);
  32045. effect.setFloat("blurWidth", _this.blurWidth);
  32046. };
  32047. }
  32048. return BlurPostProcess;
  32049. })(BABYLON.PostProcess);
  32050. BABYLON.BlurPostProcess = BlurPostProcess;
  32051. })(BABYLON || (BABYLON = {}));
  32052. var BABYLON;
  32053. (function (BABYLON) {
  32054. var RefractionPostProcess = (function (_super) {
  32055. __extends(RefractionPostProcess, _super);
  32056. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32057. var _this = this;
  32058. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32059. this.color = color;
  32060. this.depth = depth;
  32061. this.colorLevel = colorLevel;
  32062. this.onActivate = function (cam) {
  32063. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32064. };
  32065. this.onApply = function (effect) {
  32066. effect.setColor3("baseColor", _this.color);
  32067. effect.setFloat("depth", _this.depth);
  32068. effect.setFloat("colorLevel", _this.colorLevel);
  32069. effect.setTexture("refractionSampler", _this._refRexture);
  32070. };
  32071. }
  32072. // Methods
  32073. RefractionPostProcess.prototype.dispose = function (camera) {
  32074. if (this._refRexture) {
  32075. this._refRexture.dispose();
  32076. }
  32077. _super.prototype.dispose.call(this, camera);
  32078. };
  32079. return RefractionPostProcess;
  32080. })(BABYLON.PostProcess);
  32081. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32082. })(BABYLON || (BABYLON = {}));
  32083. var BABYLON;
  32084. (function (BABYLON) {
  32085. var BlackAndWhitePostProcess = (function (_super) {
  32086. __extends(BlackAndWhitePostProcess, _super);
  32087. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32088. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32089. }
  32090. return BlackAndWhitePostProcess;
  32091. })(BABYLON.PostProcess);
  32092. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32093. })(BABYLON || (BABYLON = {}));
  32094. var BABYLON;
  32095. (function (BABYLON) {
  32096. var ConvolutionPostProcess = (function (_super) {
  32097. __extends(ConvolutionPostProcess, _super);
  32098. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32099. var _this = this;
  32100. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32101. this.kernel = kernel;
  32102. this.onApply = function (effect) {
  32103. effect.setFloat2("screenSize", _this.width, _this.height);
  32104. effect.setArray("kernel", _this.kernel);
  32105. };
  32106. }
  32107. // Statics
  32108. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32109. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32110. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32111. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32112. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32113. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32114. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32115. return ConvolutionPostProcess;
  32116. })(BABYLON.PostProcess);
  32117. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32118. })(BABYLON || (BABYLON = {}));
  32119. var BABYLON;
  32120. (function (BABYLON) {
  32121. var FilterPostProcess = (function (_super) {
  32122. __extends(FilterPostProcess, _super);
  32123. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32124. var _this = this;
  32125. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32126. this.kernelMatrix = kernelMatrix;
  32127. this.onApply = function (effect) {
  32128. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32129. };
  32130. }
  32131. return FilterPostProcess;
  32132. })(BABYLON.PostProcess);
  32133. BABYLON.FilterPostProcess = FilterPostProcess;
  32134. })(BABYLON || (BABYLON = {}));
  32135. var BABYLON;
  32136. (function (BABYLON) {
  32137. var FxaaPostProcess = (function (_super) {
  32138. __extends(FxaaPostProcess, _super);
  32139. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32140. var _this = this;
  32141. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32142. this.onSizeChanged = function () {
  32143. _this.texelWidth = 1.0 / _this.width;
  32144. _this.texelHeight = 1.0 / _this.height;
  32145. };
  32146. this.onApply = function (effect) {
  32147. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32148. };
  32149. }
  32150. return FxaaPostProcess;
  32151. })(BABYLON.PostProcess);
  32152. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32153. })(BABYLON || (BABYLON = {}));
  32154. var BABYLON;
  32155. (function (BABYLON) {
  32156. var StereoscopicInterlacePostProcess = (function (_super) {
  32157. __extends(StereoscopicInterlacePostProcess, _super);
  32158. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32159. var _this = this;
  32160. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32161. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32162. this.onSizeChanged = function () {
  32163. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32164. };
  32165. this.onApply = function (effect) {
  32166. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32167. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32168. };
  32169. }
  32170. return StereoscopicInterlacePostProcess;
  32171. })(BABYLON.PostProcess);
  32172. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32173. })(BABYLON || (BABYLON = {}));
  32174. var BABYLON;
  32175. (function (BABYLON) {
  32176. var LensFlare = (function () {
  32177. function LensFlare(size, position, color, imgUrl, system) {
  32178. this.size = size;
  32179. this.position = position;
  32180. this.dispose = function () {
  32181. if (this.texture) {
  32182. this.texture.dispose();
  32183. }
  32184. // Remove from scene
  32185. var index = this._system.lensFlares.indexOf(this);
  32186. this._system.lensFlares.splice(index, 1);
  32187. };
  32188. this.color = color || new BABYLON.Color3(1, 1, 1);
  32189. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32190. this._system = system;
  32191. system.lensFlares.push(this);
  32192. }
  32193. return LensFlare;
  32194. })();
  32195. BABYLON.LensFlare = LensFlare;
  32196. })(BABYLON || (BABYLON = {}));
  32197. var BABYLON;
  32198. (function (BABYLON) {
  32199. var LensFlareSystem = (function () {
  32200. function LensFlareSystem(name, emitter, scene) {
  32201. this.name = name;
  32202. this.lensFlares = new Array();
  32203. this.borderLimit = 300;
  32204. this.layerMask = 0x0FFFFFFF;
  32205. this._vertexDeclaration = [2];
  32206. this._vertexStrideSize = 2 * 4;
  32207. this._isEnabled = true;
  32208. this._scene = scene;
  32209. this._emitter = emitter;
  32210. scene.lensFlareSystems.push(this);
  32211. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32212. // VBO
  32213. var vertices = [];
  32214. vertices.push(1, 1);
  32215. vertices.push(-1, 1);
  32216. vertices.push(-1, -1);
  32217. vertices.push(1, -1);
  32218. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32219. // Indices
  32220. var indices = [];
  32221. indices.push(0);
  32222. indices.push(1);
  32223. indices.push(2);
  32224. indices.push(0);
  32225. indices.push(2);
  32226. indices.push(3);
  32227. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32228. // Effects
  32229. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32230. }
  32231. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32232. get: function () {
  32233. return this._isEnabled;
  32234. },
  32235. set: function (value) {
  32236. this._isEnabled = value;
  32237. },
  32238. enumerable: true,
  32239. configurable: true
  32240. });
  32241. LensFlareSystem.prototype.getScene = function () {
  32242. return this._scene;
  32243. };
  32244. LensFlareSystem.prototype.getEmitter = function () {
  32245. return this._emitter;
  32246. };
  32247. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32248. this._emitter = newEmitter;
  32249. };
  32250. LensFlareSystem.prototype.getEmitterPosition = function () {
  32251. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32252. };
  32253. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32254. var position = this.getEmitterPosition();
  32255. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32256. this._positionX = position.x;
  32257. this._positionY = position.y;
  32258. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32259. if (position.z > 0) {
  32260. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32261. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32262. return true;
  32263. }
  32264. }
  32265. return false;
  32266. };
  32267. LensFlareSystem.prototype._isVisible = function () {
  32268. if (!this._isEnabled) {
  32269. return false;
  32270. }
  32271. var emitterPosition = this.getEmitterPosition();
  32272. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32273. var distance = direction.length();
  32274. direction.normalize();
  32275. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32276. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32277. return !pickInfo.hit || pickInfo.distance > distance;
  32278. };
  32279. LensFlareSystem.prototype.render = function () {
  32280. if (!this._effect.isReady())
  32281. return false;
  32282. var engine = this._scene.getEngine();
  32283. var viewport = this._scene.activeCamera.viewport;
  32284. var globalViewport = viewport.toGlobal(engine);
  32285. // Position
  32286. if (!this.computeEffectivePosition(globalViewport)) {
  32287. return false;
  32288. }
  32289. // Visibility
  32290. if (!this._isVisible()) {
  32291. return false;
  32292. }
  32293. // Intensity
  32294. var awayX;
  32295. var awayY;
  32296. if (this._positionX < this.borderLimit + globalViewport.x) {
  32297. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32298. }
  32299. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32300. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32301. }
  32302. else {
  32303. awayX = 0;
  32304. }
  32305. if (this._positionY < this.borderLimit + globalViewport.y) {
  32306. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32307. }
  32308. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32309. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32310. }
  32311. else {
  32312. awayY = 0;
  32313. }
  32314. var away = (awayX > awayY) ? awayX : awayY;
  32315. if (away > this.borderLimit) {
  32316. away = this.borderLimit;
  32317. }
  32318. var intensity = 1.0 - (away / this.borderLimit);
  32319. if (intensity < 0) {
  32320. return false;
  32321. }
  32322. if (intensity > 1.0) {
  32323. intensity = 1.0;
  32324. }
  32325. // Position
  32326. var centerX = globalViewport.x + globalViewport.width / 2;
  32327. var centerY = globalViewport.y + globalViewport.height / 2;
  32328. var distX = centerX - this._positionX;
  32329. var distY = centerY - this._positionY;
  32330. // Effects
  32331. engine.enableEffect(this._effect);
  32332. engine.setState(false);
  32333. engine.setDepthBuffer(false);
  32334. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32335. // VBOs
  32336. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32337. // Flares
  32338. for (var index = 0; index < this.lensFlares.length; index++) {
  32339. var flare = this.lensFlares[index];
  32340. var x = centerX - (distX * flare.position);
  32341. var y = centerY - (distY * flare.position);
  32342. var cw = flare.size;
  32343. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32344. var cx = 2 * (x / globalViewport.width) - 1.0;
  32345. var cy = 1.0 - 2 * (y / globalViewport.height);
  32346. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32347. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32348. // Texture
  32349. this._effect.setTexture("textureSampler", flare.texture);
  32350. // Color
  32351. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32352. // Draw order
  32353. engine.draw(true, 0, 6);
  32354. }
  32355. engine.setDepthBuffer(true);
  32356. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32357. return true;
  32358. };
  32359. LensFlareSystem.prototype.dispose = function () {
  32360. if (this._vertexBuffer) {
  32361. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32362. this._vertexBuffer = null;
  32363. }
  32364. if (this._indexBuffer) {
  32365. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32366. this._indexBuffer = null;
  32367. }
  32368. while (this.lensFlares.length) {
  32369. this.lensFlares[0].dispose();
  32370. }
  32371. // Remove from scene
  32372. var index = this._scene.lensFlareSystems.indexOf(this);
  32373. this._scene.lensFlareSystems.splice(index, 1);
  32374. };
  32375. return LensFlareSystem;
  32376. })();
  32377. BABYLON.LensFlareSystem = LensFlareSystem;
  32378. })(BABYLON || (BABYLON = {}));
  32379. var BABYLON;
  32380. (function (BABYLON) {
  32381. // We're mainly based on the logic defined into the FreeCamera code
  32382. var DeviceOrientationCamera = (function (_super) {
  32383. __extends(DeviceOrientationCamera, _super);
  32384. function DeviceOrientationCamera(name, position, scene) {
  32385. var _this = this;
  32386. _super.call(this, name, position, scene);
  32387. this._offsetX = null;
  32388. this._offsetY = null;
  32389. this._orientationGamma = 0;
  32390. this._orientationBeta = 0;
  32391. this._initialOrientationGamma = 0;
  32392. this._initialOrientationBeta = 0;
  32393. this.angularSensibility = 10000.0;
  32394. this.moveSensibility = 50.0;
  32395. window.addEventListener("resize", function () {
  32396. _this._initialOrientationGamma = null;
  32397. }, false);
  32398. }
  32399. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32400. var _this = this;
  32401. if (this._attachedCanvas) {
  32402. return;
  32403. }
  32404. this._attachedCanvas = canvas;
  32405. if (!this._orientationChanged) {
  32406. this._orientationChanged = function (evt) {
  32407. if (!_this._initialOrientationGamma) {
  32408. _this._initialOrientationGamma = evt.gamma;
  32409. _this._initialOrientationBeta = evt.beta;
  32410. }
  32411. _this._orientationGamma = evt.gamma;
  32412. _this._orientationBeta = evt.beta;
  32413. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32414. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32415. };
  32416. }
  32417. window.addEventListener("deviceorientation", this._orientationChanged);
  32418. };
  32419. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32420. if (this._attachedCanvas != canvas) {
  32421. return;
  32422. }
  32423. window.removeEventListener("deviceorientation", this._orientationChanged);
  32424. this._attachedCanvas = null;
  32425. this._orientationGamma = 0;
  32426. this._orientationBeta = 0;
  32427. this._initialOrientationGamma = 0;
  32428. this._initialOrientationBeta = 0;
  32429. };
  32430. DeviceOrientationCamera.prototype._checkInputs = function () {
  32431. if (!this._offsetX) {
  32432. return;
  32433. }
  32434. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32435. var speed = this._computeLocalCameraSpeed();
  32436. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32437. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32438. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32439. _super.prototype._checkInputs.call(this);
  32440. };
  32441. return DeviceOrientationCamera;
  32442. })(BABYLON.FreeCamera);
  32443. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32444. })(BABYLON || (BABYLON = {}));
  32445. var BABYLON;
  32446. (function (BABYLON) {
  32447. var Gamepads = (function () {
  32448. function Gamepads(ongamedpadconnected) {
  32449. var _this = this;
  32450. this.babylonGamepads = [];
  32451. this.oneGamepadConnected = false;
  32452. this.isMonitoring = false;
  32453. this.gamepadEventSupported = 'GamepadEvent' in window;
  32454. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32455. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32456. 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=";
  32457. this._callbackGamepadConnected = ongamedpadconnected;
  32458. if (this.gamepadSupportAvailable) {
  32459. // Checking if the gamepad connected event is supported (like in Firefox)
  32460. if (this.gamepadEventSupported) {
  32461. window.addEventListener('gamepadconnected', function (evt) {
  32462. _this._onGamepadConnected(evt);
  32463. }, false);
  32464. window.addEventListener('gamepaddisconnected', function (evt) {
  32465. _this._onGamepadDisconnected(evt);
  32466. }, false);
  32467. }
  32468. else {
  32469. this._startMonitoringGamepads();
  32470. }
  32471. if (!this.oneGamepadConnected) {
  32472. this._insertGamepadDOMInstructions();
  32473. }
  32474. }
  32475. else {
  32476. this._insertGamepadDOMNotSupported();
  32477. }
  32478. }
  32479. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32480. Gamepads.gamepadDOMInfo = document.createElement("div");
  32481. var buttonAImage = document.createElement("img");
  32482. buttonAImage.src = this.buttonADataURL;
  32483. var spanMessage = document.createElement("span");
  32484. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32485. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32486. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32487. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32488. Gamepads.gamepadDOMInfo.style.width = "100%";
  32489. Gamepads.gamepadDOMInfo.style.height = "48px";
  32490. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32491. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32492. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32493. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32494. buttonAImage.style.position = "relative";
  32495. buttonAImage.style.bottom = "8px";
  32496. spanMessage.style.position = "relative";
  32497. spanMessage.style.fontSize = "32px";
  32498. spanMessage.style.bottom = "32px";
  32499. spanMessage.style.color = "green";
  32500. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32501. };
  32502. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32503. Gamepads.gamepadDOMInfo = document.createElement("div");
  32504. var spanMessage = document.createElement("span");
  32505. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32506. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32507. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32508. Gamepads.gamepadDOMInfo.style.width = "100%";
  32509. Gamepads.gamepadDOMInfo.style.height = "40px";
  32510. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32511. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32512. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32513. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32514. spanMessage.style.position = "relative";
  32515. spanMessage.style.fontSize = "32px";
  32516. spanMessage.style.color = "red";
  32517. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32518. };
  32519. Gamepads.prototype.dispose = function () {
  32520. if (Gamepads.gamepadDOMInfo) {
  32521. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32522. }
  32523. };
  32524. Gamepads.prototype._onGamepadConnected = function (evt) {
  32525. var newGamepad = this._addNewGamepad(evt.gamepad);
  32526. if (this._callbackGamepadConnected)
  32527. this._callbackGamepadConnected(newGamepad);
  32528. this._startMonitoringGamepads();
  32529. };
  32530. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32531. if (!this.oneGamepadConnected) {
  32532. this.oneGamepadConnected = true;
  32533. if (Gamepads.gamepadDOMInfo) {
  32534. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32535. Gamepads.gamepadDOMInfo = null;
  32536. }
  32537. }
  32538. var newGamepad;
  32539. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32540. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32541. }
  32542. else {
  32543. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32544. }
  32545. this.babylonGamepads.push(newGamepad);
  32546. return newGamepad;
  32547. };
  32548. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32549. // Remove the gamepad from the list of gamepads to monitor.
  32550. for (var i in this.babylonGamepads) {
  32551. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32552. this.babylonGamepads.splice(i, 1);
  32553. break;
  32554. }
  32555. }
  32556. // If no gamepads are left, stop the polling loop.
  32557. if (this.babylonGamepads.length == 0) {
  32558. this._stopMonitoringGamepads();
  32559. }
  32560. };
  32561. Gamepads.prototype._startMonitoringGamepads = function () {
  32562. if (!this.isMonitoring) {
  32563. this.isMonitoring = true;
  32564. this._checkGamepadsStatus();
  32565. }
  32566. };
  32567. Gamepads.prototype._stopMonitoringGamepads = function () {
  32568. this.isMonitoring = false;
  32569. };
  32570. Gamepads.prototype._checkGamepadsStatus = function () {
  32571. var _this = this;
  32572. // updating gamepad objects
  32573. this._updateGamepadObjects();
  32574. for (var i in this.babylonGamepads) {
  32575. this.babylonGamepads[i].update();
  32576. }
  32577. if (this.isMonitoring) {
  32578. if (window.requestAnimationFrame) {
  32579. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32580. }
  32581. else if (window.mozRequestAnimationFrame) {
  32582. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32583. }
  32584. else if (window.webkitRequestAnimationFrame) {
  32585. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32586. }
  32587. }
  32588. };
  32589. // This function is called only on Chrome, which does not yet support
  32590. // connection/disconnection events, but requires you to monitor
  32591. // an array for changes.
  32592. Gamepads.prototype._updateGamepadObjects = function () {
  32593. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32594. for (var i = 0; i < gamepads.length; i++) {
  32595. if (gamepads[i]) {
  32596. if (!(gamepads[i].index in this.babylonGamepads)) {
  32597. var newGamepad = this._addNewGamepad(gamepads[i]);
  32598. if (this._callbackGamepadConnected) {
  32599. this._callbackGamepadConnected(newGamepad);
  32600. }
  32601. }
  32602. else {
  32603. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32604. }
  32605. }
  32606. }
  32607. };
  32608. return Gamepads;
  32609. })();
  32610. BABYLON.Gamepads = Gamepads;
  32611. var StickValues = (function () {
  32612. function StickValues(x, y) {
  32613. this.x = x;
  32614. this.y = y;
  32615. }
  32616. return StickValues;
  32617. })();
  32618. BABYLON.StickValues = StickValues;
  32619. var Gamepad = (function () {
  32620. function Gamepad(id, index, browserGamepad) {
  32621. this.id = id;
  32622. this.index = index;
  32623. this.browserGamepad = browserGamepad;
  32624. if (this.browserGamepad.axes.length >= 2) {
  32625. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32626. }
  32627. if (this.browserGamepad.axes.length >= 4) {
  32628. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32629. }
  32630. }
  32631. Gamepad.prototype.onleftstickchanged = function (callback) {
  32632. this._onleftstickchanged = callback;
  32633. };
  32634. Gamepad.prototype.onrightstickchanged = function (callback) {
  32635. this._onrightstickchanged = callback;
  32636. };
  32637. Object.defineProperty(Gamepad.prototype, "leftStick", {
  32638. get: function () {
  32639. return this._leftStick;
  32640. },
  32641. set: function (newValues) {
  32642. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  32643. this._onleftstickchanged(newValues);
  32644. }
  32645. this._leftStick = newValues;
  32646. },
  32647. enumerable: true,
  32648. configurable: true
  32649. });
  32650. Object.defineProperty(Gamepad.prototype, "rightStick", {
  32651. get: function () {
  32652. return this._rightStick;
  32653. },
  32654. set: function (newValues) {
  32655. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  32656. this._onrightstickchanged(newValues);
  32657. }
  32658. this._rightStick = newValues;
  32659. },
  32660. enumerable: true,
  32661. configurable: true
  32662. });
  32663. Gamepad.prototype.update = function () {
  32664. if (this._leftStick) {
  32665. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32666. }
  32667. if (this._rightStick) {
  32668. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32669. }
  32670. };
  32671. return Gamepad;
  32672. })();
  32673. BABYLON.Gamepad = Gamepad;
  32674. var GenericPad = (function (_super) {
  32675. __extends(GenericPad, _super);
  32676. function GenericPad(id, index, gamepad) {
  32677. _super.call(this, id, index, gamepad);
  32678. this.id = id;
  32679. this.index = index;
  32680. this.gamepad = gamepad;
  32681. this._buttons = new Array(gamepad.buttons.length);
  32682. }
  32683. GenericPad.prototype.onbuttondown = function (callback) {
  32684. this._onbuttondown = callback;
  32685. };
  32686. GenericPad.prototype.onbuttonup = function (callback) {
  32687. this._onbuttonup = callback;
  32688. };
  32689. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  32690. if (newValue !== currentValue) {
  32691. if (this._onbuttondown && newValue === 1) {
  32692. this._onbuttondown(buttonIndex);
  32693. }
  32694. if (this._onbuttonup && newValue === 0) {
  32695. this._onbuttonup(buttonIndex);
  32696. }
  32697. }
  32698. return newValue;
  32699. };
  32700. GenericPad.prototype.update = function () {
  32701. _super.prototype.update.call(this);
  32702. for (var index = 0; index < this._buttons.length; index++) {
  32703. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  32704. }
  32705. };
  32706. return GenericPad;
  32707. })(Gamepad);
  32708. BABYLON.GenericPad = GenericPad;
  32709. (function (Xbox360Button) {
  32710. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  32711. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  32712. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  32713. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  32714. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  32715. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  32716. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  32717. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  32718. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  32719. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  32720. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  32721. var Xbox360Button = BABYLON.Xbox360Button;
  32722. (function (Xbox360Dpad) {
  32723. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  32724. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  32725. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  32726. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  32727. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  32728. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  32729. var Xbox360Pad = (function (_super) {
  32730. __extends(Xbox360Pad, _super);
  32731. function Xbox360Pad() {
  32732. _super.apply(this, arguments);
  32733. this._leftTrigger = 0;
  32734. this._rightTrigger = 0;
  32735. this._buttonA = 0;
  32736. this._buttonB = 0;
  32737. this._buttonX = 0;
  32738. this._buttonY = 0;
  32739. this._buttonBack = 0;
  32740. this._buttonStart = 0;
  32741. this._buttonLB = 0;
  32742. this._buttonRB = 0;
  32743. this._buttonLeftStick = 0;
  32744. this._buttonRightStick = 0;
  32745. this._dPadUp = 0;
  32746. this._dPadDown = 0;
  32747. this._dPadLeft = 0;
  32748. this._dPadRight = 0;
  32749. }
  32750. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  32751. this._onlefttriggerchanged = callback;
  32752. };
  32753. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  32754. this._onrighttriggerchanged = callback;
  32755. };
  32756. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  32757. get: function () {
  32758. return this._leftTrigger;
  32759. },
  32760. set: function (newValue) {
  32761. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  32762. this._onlefttriggerchanged(newValue);
  32763. }
  32764. this._leftTrigger = newValue;
  32765. },
  32766. enumerable: true,
  32767. configurable: true
  32768. });
  32769. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  32770. get: function () {
  32771. return this._rightTrigger;
  32772. },
  32773. set: function (newValue) {
  32774. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  32775. this._onrighttriggerchanged(newValue);
  32776. }
  32777. this._rightTrigger = newValue;
  32778. },
  32779. enumerable: true,
  32780. configurable: true
  32781. });
  32782. Xbox360Pad.prototype.onbuttondown = function (callback) {
  32783. this._onbuttondown = callback;
  32784. };
  32785. Xbox360Pad.prototype.onbuttonup = function (callback) {
  32786. this._onbuttonup = callback;
  32787. };
  32788. Xbox360Pad.prototype.ondpaddown = function (callback) {
  32789. this._ondpaddown = callback;
  32790. };
  32791. Xbox360Pad.prototype.ondpadup = function (callback) {
  32792. this._ondpadup = callback;
  32793. };
  32794. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  32795. if (newValue !== currentValue) {
  32796. if (this._onbuttondown && newValue === 1) {
  32797. this._onbuttondown(buttonType);
  32798. }
  32799. if (this._onbuttonup && newValue === 0) {
  32800. this._onbuttonup(buttonType);
  32801. }
  32802. }
  32803. return newValue;
  32804. };
  32805. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  32806. if (newValue !== currentValue) {
  32807. if (this._ondpaddown && newValue === 1) {
  32808. this._ondpaddown(buttonType);
  32809. }
  32810. if (this._ondpadup && newValue === 0) {
  32811. this._ondpadup(buttonType);
  32812. }
  32813. }
  32814. return newValue;
  32815. };
  32816. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  32817. get: function () {
  32818. return this._buttonA;
  32819. },
  32820. set: function (value) {
  32821. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  32822. },
  32823. enumerable: true,
  32824. configurable: true
  32825. });
  32826. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  32827. get: function () {
  32828. return this._buttonB;
  32829. },
  32830. set: function (value) {
  32831. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  32832. },
  32833. enumerable: true,
  32834. configurable: true
  32835. });
  32836. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  32837. get: function () {
  32838. return this._buttonX;
  32839. },
  32840. set: function (value) {
  32841. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  32842. },
  32843. enumerable: true,
  32844. configurable: true
  32845. });
  32846. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  32847. get: function () {
  32848. return this._buttonY;
  32849. },
  32850. set: function (value) {
  32851. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  32852. },
  32853. enumerable: true,
  32854. configurable: true
  32855. });
  32856. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  32857. get: function () {
  32858. return this._buttonStart;
  32859. },
  32860. set: function (value) {
  32861. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  32862. },
  32863. enumerable: true,
  32864. configurable: true
  32865. });
  32866. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  32867. get: function () {
  32868. return this._buttonBack;
  32869. },
  32870. set: function (value) {
  32871. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  32872. },
  32873. enumerable: true,
  32874. configurable: true
  32875. });
  32876. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  32877. get: function () {
  32878. return this._buttonLB;
  32879. },
  32880. set: function (value) {
  32881. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  32882. },
  32883. enumerable: true,
  32884. configurable: true
  32885. });
  32886. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  32887. get: function () {
  32888. return this._buttonRB;
  32889. },
  32890. set: function (value) {
  32891. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  32892. },
  32893. enumerable: true,
  32894. configurable: true
  32895. });
  32896. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  32897. get: function () {
  32898. return this._buttonLeftStick;
  32899. },
  32900. set: function (value) {
  32901. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  32902. },
  32903. enumerable: true,
  32904. configurable: true
  32905. });
  32906. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  32907. get: function () {
  32908. return this._buttonRightStick;
  32909. },
  32910. set: function (value) {
  32911. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  32912. },
  32913. enumerable: true,
  32914. configurable: true
  32915. });
  32916. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  32917. get: function () {
  32918. return this._dPadUp;
  32919. },
  32920. set: function (value) {
  32921. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  32922. },
  32923. enumerable: true,
  32924. configurable: true
  32925. });
  32926. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  32927. get: function () {
  32928. return this._dPadDown;
  32929. },
  32930. set: function (value) {
  32931. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  32932. },
  32933. enumerable: true,
  32934. configurable: true
  32935. });
  32936. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  32937. get: function () {
  32938. return this._dPadLeft;
  32939. },
  32940. set: function (value) {
  32941. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  32942. },
  32943. enumerable: true,
  32944. configurable: true
  32945. });
  32946. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  32947. get: function () {
  32948. return this._dPadRight;
  32949. },
  32950. set: function (value) {
  32951. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  32952. },
  32953. enumerable: true,
  32954. configurable: true
  32955. });
  32956. Xbox360Pad.prototype.update = function () {
  32957. _super.prototype.update.call(this);
  32958. this.buttonA = this.browserGamepad.buttons[0].value;
  32959. this.buttonB = this.browserGamepad.buttons[1].value;
  32960. this.buttonX = this.browserGamepad.buttons[2].value;
  32961. this.buttonY = this.browserGamepad.buttons[3].value;
  32962. this.buttonLB = this.browserGamepad.buttons[4].value;
  32963. this.buttonRB = this.browserGamepad.buttons[5].value;
  32964. this.leftTrigger = this.browserGamepad.buttons[6].value;
  32965. this.rightTrigger = this.browserGamepad.buttons[7].value;
  32966. this.buttonBack = this.browserGamepad.buttons[8].value;
  32967. this.buttonStart = this.browserGamepad.buttons[9].value;
  32968. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  32969. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  32970. this.dPadUp = this.browserGamepad.buttons[12].value;
  32971. this.dPadDown = this.browserGamepad.buttons[13].value;
  32972. this.dPadLeft = this.browserGamepad.buttons[14].value;
  32973. this.dPadRight = this.browserGamepad.buttons[15].value;
  32974. };
  32975. return Xbox360Pad;
  32976. })(Gamepad);
  32977. BABYLON.Xbox360Pad = Xbox360Pad;
  32978. })(BABYLON || (BABYLON = {}));
  32979. var BABYLON;
  32980. (function (BABYLON) {
  32981. // We're mainly based on the logic defined into the FreeCamera code
  32982. var GamepadCamera = (function (_super) {
  32983. __extends(GamepadCamera, _super);
  32984. function GamepadCamera(name, position, scene) {
  32985. var _this = this;
  32986. _super.call(this, name, position, scene);
  32987. this.angularSensibility = 200;
  32988. this.moveSensibility = 75;
  32989. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  32990. }
  32991. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  32992. // Only the first gamepad can control the camera
  32993. if (gamepad.index === 0) {
  32994. this._gamepad = gamepad;
  32995. }
  32996. };
  32997. GamepadCamera.prototype._checkInputs = function () {
  32998. if (this._gamepad) {
  32999. var LSValues = this._gamepad.leftStick;
  33000. var normalizedLX = LSValues.x / this.moveSensibility;
  33001. var normalizedLY = LSValues.y / this.moveSensibility;
  33002. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33003. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33004. var RSValues = this._gamepad.rightStick;
  33005. var normalizedRX = RSValues.x / this.angularSensibility;
  33006. var normalizedRY = RSValues.y / this.angularSensibility;
  33007. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33008. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33009. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33010. var speed = this._computeLocalCameraSpeed() * 50.0;
  33011. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33012. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33013. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33014. }
  33015. _super.prototype._checkInputs.call(this);
  33016. };
  33017. GamepadCamera.prototype.dispose = function () {
  33018. this._gamepads.dispose();
  33019. _super.prototype.dispose.call(this);
  33020. };
  33021. return GamepadCamera;
  33022. })(BABYLON.FreeCamera);
  33023. BABYLON.GamepadCamera = GamepadCamera;
  33024. })(BABYLON || (BABYLON = {}));
  33025. var BABYLON;
  33026. (function (BABYLON) {
  33027. var Analyser = (function () {
  33028. function Analyser(scene) {
  33029. this.SMOOTHING = 0.75;
  33030. this.FFT_SIZE = 512;
  33031. this.BARGRAPHAMPLITUDE = 256;
  33032. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33033. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33034. this._scene = scene;
  33035. this._audioEngine = BABYLON.Engine.audioEngine;
  33036. if (this._audioEngine.canUseWebAudio) {
  33037. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33038. this._webAudioAnalyser.minDecibels = -140;
  33039. this._webAudioAnalyser.maxDecibels = 0;
  33040. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33041. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33042. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33043. }
  33044. }
  33045. Analyser.prototype.getFrequencyBinCount = function () {
  33046. if (this._audioEngine.canUseWebAudio) {
  33047. return this._webAudioAnalyser.frequencyBinCount;
  33048. }
  33049. else {
  33050. return 0;
  33051. }
  33052. };
  33053. Analyser.prototype.getByteFrequencyData = function () {
  33054. if (this._audioEngine.canUseWebAudio) {
  33055. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33056. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33057. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33058. }
  33059. return this._byteFreqs;
  33060. };
  33061. Analyser.prototype.getByteTimeDomainData = function () {
  33062. if (this._audioEngine.canUseWebAudio) {
  33063. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33064. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33065. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33066. }
  33067. return this._byteTime;
  33068. };
  33069. Analyser.prototype.getFloatFrequencyData = function () {
  33070. if (this._audioEngine.canUseWebAudio) {
  33071. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33072. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33073. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33074. }
  33075. return this._floatFreqs;
  33076. };
  33077. Analyser.prototype.drawDebugCanvas = function () {
  33078. var _this = this;
  33079. if (this._audioEngine.canUseWebAudio) {
  33080. if (!this._debugCanvas) {
  33081. this._debugCanvas = document.createElement("canvas");
  33082. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33083. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33084. this._debugCanvas.style.position = "absolute";
  33085. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33086. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33087. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33088. document.body.appendChild(this._debugCanvas);
  33089. this._registerFunc = function () {
  33090. _this.drawDebugCanvas();
  33091. };
  33092. this._scene.registerBeforeRender(this._registerFunc);
  33093. }
  33094. if (this._registerFunc) {
  33095. var workingArray = this.getByteFrequencyData();
  33096. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33097. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33098. // Draw the frequency domain chart.
  33099. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33100. var value = workingArray[i];
  33101. var percent = value / this.BARGRAPHAMPLITUDE;
  33102. var height = this.DEBUGCANVASSIZE.height * percent;
  33103. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33104. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33105. var hue = i / this.getFrequencyBinCount() * 360;
  33106. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33107. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33108. }
  33109. }
  33110. }
  33111. };
  33112. Analyser.prototype.stopDebugCanvas = function () {
  33113. if (this._debugCanvas) {
  33114. this._scene.unregisterBeforeRender(this._registerFunc);
  33115. this._registerFunc = null;
  33116. document.body.removeChild(this._debugCanvas);
  33117. this._debugCanvas = null;
  33118. this._debugCanvasContext = null;
  33119. }
  33120. };
  33121. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33122. if (this._audioEngine.canUseWebAudio) {
  33123. inputAudioNode.connect(this._webAudioAnalyser);
  33124. this._webAudioAnalyser.connect(outputAudioNode);
  33125. }
  33126. };
  33127. Analyser.prototype.dispose = function () {
  33128. if (this._audioEngine.canUseWebAudio) {
  33129. this._webAudioAnalyser.disconnect();
  33130. }
  33131. };
  33132. return Analyser;
  33133. })();
  33134. BABYLON.Analyser = Analyser;
  33135. })(BABYLON || (BABYLON = {}));
  33136. var BABYLON;
  33137. (function (BABYLON) {
  33138. var DepthRenderer = (function () {
  33139. function DepthRenderer(scene, type) {
  33140. var _this = this;
  33141. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  33142. this._viewMatrix = BABYLON.Matrix.Zero();
  33143. this._projectionMatrix = BABYLON.Matrix.Zero();
  33144. this._transformMatrix = BABYLON.Matrix.Zero();
  33145. this._worldViewProjection = BABYLON.Matrix.Zero();
  33146. this._scene = scene;
  33147. var engine = scene.getEngine();
  33148. // Render target
  33149. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  33150. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33151. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33152. this._depthMap.refreshRate = 1;
  33153. this._depthMap.renderParticles = false;
  33154. this._depthMap.renderList = null;
  33155. // set default depth value to 1.0 (far away)
  33156. this._depthMap.onClear = function (engine) {
  33157. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  33158. };
  33159. // Custom render function
  33160. var renderSubMesh = function (subMesh) {
  33161. var mesh = subMesh.getRenderingMesh();
  33162. var scene = _this._scene;
  33163. var engine = scene.getEngine();
  33164. // Culling
  33165. engine.setState(subMesh.getMaterial().backFaceCulling);
  33166. // Managing instances
  33167. var batch = mesh._getInstancesRenderList(subMesh._id);
  33168. if (batch.mustReturn) {
  33169. return;
  33170. }
  33171. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33172. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33173. engine.enableEffect(_this._effect);
  33174. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  33175. var material = subMesh.getMaterial();
  33176. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33177. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  33178. // Alpha test
  33179. if (material && material.needAlphaTesting()) {
  33180. var alphaTexture = material.getAlphaTestTexture();
  33181. _this._effect.setTexture("diffuseSampler", alphaTexture);
  33182. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33183. }
  33184. // Bones
  33185. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33186. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33187. }
  33188. // Draw
  33189. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  33190. }
  33191. };
  33192. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  33193. var index;
  33194. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33195. renderSubMesh(opaqueSubMeshes.data[index]);
  33196. }
  33197. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33198. renderSubMesh(alphaTestSubMeshes.data[index]);
  33199. }
  33200. };
  33201. }
  33202. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  33203. var defines = [];
  33204. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33205. var mesh = subMesh.getMesh();
  33206. var scene = mesh.getScene();
  33207. var material = subMesh.getMaterial();
  33208. // Alpha test
  33209. if (material && material.needAlphaTesting()) {
  33210. defines.push("#define ALPHATEST");
  33211. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33212. attribs.push(BABYLON.VertexBuffer.UVKind);
  33213. defines.push("#define UV1");
  33214. }
  33215. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33216. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33217. defines.push("#define UV2");
  33218. }
  33219. }
  33220. // Bones
  33221. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33222. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33223. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33224. defines.push("#define BONES");
  33225. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33226. }
  33227. // Instances
  33228. if (useInstances) {
  33229. defines.push("#define INSTANCES");
  33230. attribs.push("world0");
  33231. attribs.push("world1");
  33232. attribs.push("world2");
  33233. attribs.push("world3");
  33234. }
  33235. // Get correct effect
  33236. var join = defines.join("\n");
  33237. if (this._cachedDefines !== join) {
  33238. this._cachedDefines = join;
  33239. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  33240. }
  33241. return this._effect.isReady();
  33242. };
  33243. DepthRenderer.prototype.getDepthMap = function () {
  33244. return this._depthMap;
  33245. };
  33246. // Methods
  33247. DepthRenderer.prototype.dispose = function () {
  33248. this._depthMap.dispose();
  33249. };
  33250. return DepthRenderer;
  33251. })();
  33252. BABYLON.DepthRenderer = DepthRenderer;
  33253. })(BABYLON || (BABYLON = {}));
  33254. var BABYLON;
  33255. (function (BABYLON) {
  33256. var SSAORenderingPipeline = (function (_super) {
  33257. __extends(SSAORenderingPipeline, _super);
  33258. /**
  33259. * @constructor
  33260. * @param {string} name - The rendering pipeline name
  33261. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33262. * @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 }
  33263. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33264. */
  33265. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  33266. var _this = this;
  33267. _super.call(this, scene.getEngine(), name);
  33268. // Members
  33269. /**
  33270. * The PassPostProcess id in the pipeline that contains the original scene color
  33271. * @type {string}
  33272. */
  33273. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  33274. /**
  33275. * The SSAO PostProcess id in the pipeline
  33276. * @type {string}
  33277. */
  33278. this.SSAORenderEffect = "SSAORenderEffect";
  33279. /**
  33280. * The horizontal blur PostProcess id in the pipeline
  33281. * @type {string}
  33282. */
  33283. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  33284. /**
  33285. * The vertical blur PostProcess id in the pipeline
  33286. * @type {string}
  33287. */
  33288. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  33289. /**
  33290. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  33291. * @type {string}
  33292. */
  33293. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  33294. /**
  33295. * The output strength of the SSAO post-process. Default value is 1.0.
  33296. * @type {number}
  33297. */
  33298. this.totalStrength = 1.0;
  33299. /**
  33300. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  33301. * @type {number}
  33302. */
  33303. this.radius = 0.0002;
  33304. /**
  33305. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  33306. * Must not be equal to fallOff and superior to fallOff.
  33307. * Default value is 0.0075
  33308. * @type {number}
  33309. */
  33310. this.area = 0.0075;
  33311. /**
  33312. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  33313. * Must not be equal to area and inferior to area.
  33314. * Default value is 0.0002
  33315. * @type {number}
  33316. */
  33317. this.fallOff = 0.0002;
  33318. this._firstUpdate = true;
  33319. this._scene = scene;
  33320. // Set up assets
  33321. this._createRandomTexture();
  33322. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  33323. var ssaoRatio = ratio.ssaoRatio || ratio;
  33324. var combineRatio = ratio.combineRatio || ratio;
  33325. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33326. this._createSSAOPostProcess(ssaoRatio);
  33327. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33328. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33329. this._createSSAOCombinePostProcess(combineRatio);
  33330. // Set up pipeline
  33331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  33332. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  33333. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  33334. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  33335. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  33336. // Finish
  33337. scene.postProcessRenderPipelineManager.addPipeline(this);
  33338. if (cameras)
  33339. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33340. }
  33341. // Public Methods
  33342. /**
  33343. * Returns the horizontal blur PostProcess
  33344. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  33345. */
  33346. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  33347. return this._blurHPostProcess;
  33348. };
  33349. /**
  33350. * Returns the vertical blur PostProcess
  33351. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  33352. */
  33353. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  33354. return this._blurVPostProcess;
  33355. };
  33356. /**
  33357. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  33358. */
  33359. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  33360. if (disableDepthRender === void 0) { disableDepthRender = false; }
  33361. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33362. this._originalColorPostProcess = undefined;
  33363. this._ssaoPostProcess = undefined;
  33364. this._blurHPostProcess = undefined;
  33365. this._blurVPostProcess = undefined;
  33366. this._ssaoCombinePostProcess = undefined;
  33367. this._randomTexture.dispose();
  33368. if (disableDepthRender)
  33369. this._scene.disableDepthRenderer();
  33370. };
  33371. // Private Methods
  33372. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  33373. var _this = this;
  33374. var sampleSphere = [
  33375. 0.5381, 0.1856, -0.4319,
  33376. 0.1379, 0.2486, 0.4430,
  33377. 0.3371, 0.5679, -0.0057,
  33378. -0.6999, -0.0451, -0.0019,
  33379. 0.0689, -0.1598, -0.8547,
  33380. 0.0560, 0.0069, -0.1843,
  33381. -0.0146, 0.1402, 0.0762,
  33382. 0.0100, -0.1924, -0.0344,
  33383. -0.3577, -0.5301, -0.4358,
  33384. -0.3169, 0.1063, 0.0158,
  33385. 0.0103, -0.5869, 0.0046,
  33386. -0.0897, -0.4940, 0.3287,
  33387. 0.7119, -0.0154, -0.0918,
  33388. -0.0533, 0.0596, -0.5411,
  33389. 0.0352, -0.0631, 0.5460,
  33390. -0.4776, 0.2847, -0.0271
  33391. ];
  33392. var samplesFactor = 1.0 / 16.0;
  33393. 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);
  33394. this._ssaoPostProcess.onApply = function (effect) {
  33395. if (_this._firstUpdate) {
  33396. effect.setArray3("sampleSphere", sampleSphere);
  33397. effect.setFloat("samplesFactor", samplesFactor);
  33398. effect.setFloat("randTextureTiles", 4.0 / ratio);
  33399. _this._firstUpdate = false;
  33400. }
  33401. effect.setFloat("totalStrength", _this.totalStrength);
  33402. effect.setFloat("radius", _this.radius);
  33403. effect.setFloat("area", _this.area);
  33404. effect.setFloat("fallOff", _this.fallOff);
  33405. effect.setTexture("textureSampler", _this._depthTexture);
  33406. effect.setTexture("randomSampler", _this._randomTexture);
  33407. };
  33408. };
  33409. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  33410. var _this = this;
  33411. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33412. this._ssaoCombinePostProcess.onApply = function (effect) {
  33413. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  33414. };
  33415. };
  33416. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  33417. var size = 512;
  33418. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33419. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33420. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33421. var context = this._randomTexture.getContext();
  33422. var rand = function (min, max) {
  33423. return Math.random() * (max - min) + min;
  33424. };
  33425. for (var x = 0; x < size; x++) {
  33426. for (var y = 0; y < size; y++) {
  33427. var randVector = BABYLON.Vector3.Zero();
  33428. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  33429. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  33430. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  33431. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  33432. context.fillRect(x, y, 1, 1);
  33433. }
  33434. }
  33435. this._randomTexture.update(false);
  33436. };
  33437. return SSAORenderingPipeline;
  33438. })(BABYLON.PostProcessRenderPipeline);
  33439. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  33440. })(BABYLON || (BABYLON = {}));
  33441. var BABYLON;
  33442. (function (BABYLON) {
  33443. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  33444. var VolumetricLightScatteringPostProcess = (function (_super) {
  33445. __extends(VolumetricLightScatteringPostProcess, _super);
  33446. /**
  33447. * @constructor
  33448. * @param {string} name - The post-process name
  33449. * @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)
  33450. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  33451. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  33452. * @param {number} samples - The post-process quality, default 100
  33453. * @param {number} samplingMode - The post-process filtering mode
  33454. * @param {BABYLON.Engine} engine - The babylon engine
  33455. * @param {boolean} reusable - If the post-process is reusable
  33456. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  33457. */
  33458. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  33459. var _this = this;
  33460. if (samples === void 0) { samples = 100; }
  33461. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33462. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  33463. this._screenCoordinates = BABYLON.Vector2.Zero();
  33464. /**
  33465. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  33466. * @type {boolean}
  33467. */
  33468. this.useCustomMeshPosition = false;
  33469. /**
  33470. * If the post-process should inverse the light scattering direction
  33471. * @type {boolean}
  33472. */
  33473. this.invert = true;
  33474. /**
  33475. * Set to true to use the diffuseColor instead of the diffuseTexture
  33476. * @type {boolean}
  33477. */
  33478. this.useDiffuseColor = false;
  33479. /**
  33480. * Array containing the excluded meshes not rendered in the internal pass
  33481. */
  33482. this.excludedMeshes = new Array();
  33483. /**
  33484. * Controls the overall intensity of the post-process
  33485. * @type {number}
  33486. */
  33487. this.exposure = 0.3;
  33488. /**
  33489. * Dissipates each sample's contribution in range [0, 1]
  33490. * @type {number}
  33491. */
  33492. this.decay = 0.96815;
  33493. /**
  33494. * Controls the overall intensity of each sample
  33495. * @type {number}
  33496. */
  33497. this.weight = 0.58767;
  33498. /**
  33499. * Controls the density of each sample
  33500. * @type {number}
  33501. */
  33502. this.density = 0.926;
  33503. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  33504. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  33505. // Configure mesh
  33506. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  33507. // Configure
  33508. this._createPass(scene, ratio.passRatio || ratio);
  33509. this.onApply = function (effect) {
  33510. _this._updateMeshScreenCoordinates(scene);
  33511. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  33512. effect.setFloat("exposure", _this.exposure);
  33513. effect.setFloat("decay", _this.decay);
  33514. effect.setFloat("weight", _this.weight);
  33515. effect.setFloat("density", _this.density);
  33516. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  33517. };
  33518. }
  33519. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  33520. var mesh = subMesh.getMesh();
  33521. var defines = [];
  33522. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33523. var material = subMesh.getMaterial();
  33524. var needUV = false;
  33525. // Render this.mesh as default
  33526. if (mesh === this.mesh) {
  33527. if (this.useDiffuseColor) {
  33528. defines.push("#define DIFFUSE_COLOR_RENDER");
  33529. }
  33530. else if (material) {
  33531. if (material.diffuseTexture !== undefined) {
  33532. defines.push("#define BASIC_RENDER");
  33533. }
  33534. else {
  33535. defines.push("#define DIFFUSE_COLOR_RENDER");
  33536. }
  33537. }
  33538. defines.push("#define NEED_UV");
  33539. needUV = true;
  33540. }
  33541. // Alpha test
  33542. if (material) {
  33543. if (material.needAlphaTesting()) {
  33544. defines.push("#define ALPHATEST");
  33545. }
  33546. if (material.opacityTexture !== undefined) {
  33547. defines.push("#define OPACITY");
  33548. if (material.opacityTexture.getAlphaFromRGB) {
  33549. defines.push("#define OPACITYRGB");
  33550. }
  33551. if (!needUV) {
  33552. defines.push("#define NEED_UV");
  33553. }
  33554. }
  33555. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33556. attribs.push(BABYLON.VertexBuffer.UVKind);
  33557. defines.push("#define UV1");
  33558. }
  33559. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33560. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33561. defines.push("#define UV2");
  33562. }
  33563. }
  33564. // Bones
  33565. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33566. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33567. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33568. defines.push("#define BONES");
  33569. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33570. }
  33571. // Instances
  33572. if (useInstances) {
  33573. defines.push("#define INSTANCES");
  33574. attribs.push("world0");
  33575. attribs.push("world1");
  33576. attribs.push("world2");
  33577. attribs.push("world3");
  33578. }
  33579. // Get correct effect
  33580. var join = defines.join("\n");
  33581. if (this._cachedDefines !== join) {
  33582. this._cachedDefines = join;
  33583. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  33584. }
  33585. return this._volumetricLightScatteringPass.isReady();
  33586. };
  33587. /**
  33588. * Sets the new light position for light scattering effect
  33589. * @param {BABYLON.Vector3} The new custom light position
  33590. */
  33591. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  33592. this._customMeshPosition = position;
  33593. };
  33594. /**
  33595. * Returns the light position for light scattering effect
  33596. * @return {BABYLON.Vector3} The custom light position
  33597. */
  33598. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  33599. return this._customMeshPosition;
  33600. };
  33601. /**
  33602. * Disposes the internal assets and detaches the post-process from the camera
  33603. */
  33604. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  33605. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  33606. if (rttIndex !== -1) {
  33607. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  33608. }
  33609. this._volumetricLightScatteringRTT.dispose();
  33610. _super.prototype.dispose.call(this, camera);
  33611. };
  33612. /**
  33613. * Returns the render target texture used by the post-process
  33614. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  33615. */
  33616. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  33617. return this._volumetricLightScatteringRTT;
  33618. };
  33619. // Private methods
  33620. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  33621. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  33622. return true;
  33623. }
  33624. return false;
  33625. };
  33626. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  33627. var _this = this;
  33628. var engine = scene.getEngine();
  33629. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  33630. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33631. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33632. this._volumetricLightScatteringRTT.renderList = null;
  33633. this._volumetricLightScatteringRTT.renderParticles = false;
  33634. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  33635. // Custom render function for submeshes
  33636. var renderSubMesh = function (subMesh) {
  33637. var mesh = subMesh.getRenderingMesh();
  33638. if (_this._meshExcluded(mesh)) {
  33639. return;
  33640. }
  33641. var scene = mesh.getScene();
  33642. var engine = scene.getEngine();
  33643. // Culling
  33644. engine.setState(subMesh.getMaterial().backFaceCulling);
  33645. // Managing instances
  33646. var batch = mesh._getInstancesRenderList(subMesh._id);
  33647. if (batch.mustReturn) {
  33648. return;
  33649. }
  33650. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33651. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33652. engine.enableEffect(_this._volumetricLightScatteringPass);
  33653. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  33654. var material = subMesh.getMaterial();
  33655. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  33656. // Alpha test
  33657. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  33658. var alphaTexture = material.getAlphaTestTexture();
  33659. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  33660. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  33661. }
  33662. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  33663. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  33664. if (alphaTexture) {
  33665. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33666. }
  33667. }
  33668. if (material.opacityTexture !== undefined) {
  33669. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  33670. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  33671. }
  33672. }
  33673. // Bones
  33674. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33675. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33676. }
  33677. // Draw
  33678. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  33679. }
  33680. };
  33681. // Render target texture callbacks
  33682. var savedSceneClearColor;
  33683. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  33684. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  33685. savedSceneClearColor = scene.clearColor;
  33686. scene.clearColor = sceneClearColor;
  33687. };
  33688. this._volumetricLightScatteringRTT.onAfterRender = function () {
  33689. scene.clearColor = savedSceneClearColor;
  33690. };
  33691. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33692. var engine = scene.getEngine();
  33693. var index;
  33694. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33695. renderSubMesh(opaqueSubMeshes.data[index]);
  33696. }
  33697. engine.setAlphaTesting(true);
  33698. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33699. renderSubMesh(alphaTestSubMeshes.data[index]);
  33700. }
  33701. engine.setAlphaTesting(false);
  33702. if (transparentSubMeshes.length) {
  33703. // Sort sub meshes
  33704. for (index = 0; index < transparentSubMeshes.length; index++) {
  33705. var submesh = transparentSubMeshes.data[index];
  33706. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  33707. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  33708. }
  33709. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  33710. sortedArray.sort(function (a, b) {
  33711. // Alpha index first
  33712. if (a._alphaIndex > b._alphaIndex) {
  33713. return 1;
  33714. }
  33715. if (a._alphaIndex < b._alphaIndex) {
  33716. return -1;
  33717. }
  33718. // Then distance to camera
  33719. if (a._distanceToCamera < b._distanceToCamera) {
  33720. return 1;
  33721. }
  33722. if (a._distanceToCamera > b._distanceToCamera) {
  33723. return -1;
  33724. }
  33725. return 0;
  33726. });
  33727. // Render sub meshes
  33728. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33729. for (index = 0; index < sortedArray.length; index++) {
  33730. renderSubMesh(sortedArray[index]);
  33731. }
  33732. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33733. }
  33734. };
  33735. };
  33736. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  33737. var transform = scene.getTransformMatrix();
  33738. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  33739. this._screenCoordinates.x = pos.x / this._viewPort.width;
  33740. this._screenCoordinates.y = pos.y / this._viewPort.height;
  33741. if (this.invert)
  33742. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  33743. };
  33744. // Static methods
  33745. /**
  33746. * Creates a default mesh for the Volumeric Light Scattering post-process
  33747. * @param {string} The mesh name
  33748. * @param {BABYLON.Scene} The scene where to create the mesh
  33749. * @return {BABYLON.Mesh} the default mesh
  33750. */
  33751. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  33752. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  33753. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  33754. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  33755. return mesh;
  33756. };
  33757. return VolumetricLightScatteringPostProcess;
  33758. })(BABYLON.PostProcess);
  33759. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  33760. })(BABYLON || (BABYLON = {}));
  33761. var BABYLON;
  33762. (function (BABYLON) {
  33763. var LensRenderingPipeline = (function (_super) {
  33764. __extends(LensRenderingPipeline, _super);
  33765. /**
  33766. * @constructor
  33767. *
  33768. * Effect parameters are as follow:
  33769. * {
  33770. * chromatic_aberration: number; // from 0 to x (1 for realism)
  33771. * edge_blur: number; // from 0 to x (1 for realism)
  33772. * distortion: number; // from 0 to x (1 for realism)
  33773. * grain_amount: number; // from 0 to 1
  33774. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  33775. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  33776. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  33777. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  33778. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  33779. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  33780. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  33781. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  33782. * }
  33783. * Note: if an effect parameter is unset, effect is disabled
  33784. *
  33785. * @param {string} name - The rendering pipeline name
  33786. * @param {object} parameters - An object containing all parameters (see above)
  33787. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33788. * @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)
  33789. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33790. */
  33791. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  33792. var _this = this;
  33793. if (ratio === void 0) { ratio = 1.0; }
  33794. _super.call(this, scene.getEngine(), name);
  33795. // Lens effects can be of the following:
  33796. // - chromatic aberration (slight shift of RGB colors)
  33797. // - blur on the edge of the lens
  33798. // - lens distortion
  33799. // - depth-of-field blur & highlights enhancing
  33800. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  33801. // - grain effect (noise or custom texture)
  33802. // Two additional texture samplers are needed:
  33803. // - depth map (for depth-of-field)
  33804. // - grain texture
  33805. /**
  33806. * The chromatic aberration PostProcess id in the pipeline
  33807. * @type {string}
  33808. */
  33809. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  33810. /**
  33811. * The highlights enhancing PostProcess id in the pipeline
  33812. * @type {string}
  33813. */
  33814. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  33815. /**
  33816. * The depth-of-field PostProcess id in the pipeline
  33817. * @type {string}
  33818. */
  33819. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  33820. this._scene = scene;
  33821. // Fetch texture samplers
  33822. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  33823. if (parameters.grain_texture) {
  33824. this._grainTexture = parameters.grain_texture;
  33825. }
  33826. else {
  33827. this._createGrainTexture();
  33828. }
  33829. // save parameters
  33830. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  33831. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  33832. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  33833. this._distortion = parameters.distortion ? parameters.distortion : 0;
  33834. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  33835. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  33836. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  33837. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  33838. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  33839. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  33840. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  33841. // Create effects
  33842. this._createChromaticAberrationPostProcess(ratio);
  33843. this._createHighlightsPostProcess(ratio);
  33844. this._createDepthOfFieldPostProcess(ratio / 4);
  33845. // Set up pipeline
  33846. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  33847. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  33848. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  33849. if (this._highlightsGain == -1) {
  33850. this._disableEffect(this.HighlightsEnhancingEffect, null);
  33851. }
  33852. // Finish
  33853. scene.postProcessRenderPipelineManager.addPipeline(this);
  33854. if (cameras) {
  33855. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33856. }
  33857. }
  33858. // public methods (self explanatory)
  33859. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  33860. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  33861. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  33862. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  33863. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  33864. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  33865. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  33866. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  33867. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  33868. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  33869. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  33870. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  33871. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  33872. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  33873. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  33874. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  33875. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  33876. this._highlightsGain = amount;
  33877. };
  33878. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  33879. if (this._highlightsGain == -1) {
  33880. this._highlightsGain = 1.0;
  33881. }
  33882. this._highlightsThreshold = amount;
  33883. };
  33884. LensRenderingPipeline.prototype.disableHighlights = function () {
  33885. this._highlightsGain = -1;
  33886. };
  33887. /**
  33888. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  33889. */
  33890. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  33891. if (disableDepthRender === void 0) { disableDepthRender = false; }
  33892. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33893. this._chromaticAberrationPostProcess = undefined;
  33894. this._highlightsPostProcess = undefined;
  33895. this._depthOfFieldPostProcess = undefined;
  33896. this._grainTexture.dispose();
  33897. if (disableDepthRender)
  33898. this._scene.disableDepthRenderer();
  33899. };
  33900. // colors shifting and distortion
  33901. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  33902. var _this = this;
  33903. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  33904. [], // samplers
  33905. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33906. this._chromaticAberrationPostProcess.onApply = function (effect) {
  33907. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  33908. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33909. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33910. };
  33911. };
  33912. // highlights enhancing
  33913. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  33914. var _this = this;
  33915. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  33916. [], // samplers
  33917. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33918. this._highlightsPostProcess.onApply = function (effect) {
  33919. effect.setFloat('gain', _this._highlightsGain);
  33920. effect.setFloat('threshold', _this._highlightsThreshold);
  33921. effect.setBool('pentagon', _this._dofPentagon);
  33922. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  33923. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33924. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33925. };
  33926. };
  33927. // colors shifting and distortion
  33928. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  33929. var _this = this;
  33930. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  33931. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  33932. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  33933. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33934. this._depthOfFieldPostProcess.onApply = function (effect) {
  33935. effect.setTexture("depthSampler", _this._depthTexture);
  33936. effect.setTexture("grainSampler", _this._grainTexture);
  33937. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  33938. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  33939. effect.setFloat('grain_amount', _this._grainAmount);
  33940. effect.setBool('blur_noise', _this._blurNoise);
  33941. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33942. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33943. effect.setFloat('distortion', _this._distortion);
  33944. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  33945. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  33946. effect.setFloat('aperture', _this._dofAperture);
  33947. effect.setFloat('darken', _this._dofDarken);
  33948. effect.setFloat('edge_blur', _this._edgeBlur);
  33949. effect.setBool('highlights', (_this._highlightsGain != -1));
  33950. effect.setFloat('near', _this._scene.activeCamera.minZ);
  33951. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  33952. };
  33953. };
  33954. // creates a black and white random noise texture, 512x512
  33955. LensRenderingPipeline.prototype._createGrainTexture = function () {
  33956. var size = 512;
  33957. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33958. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33959. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33960. var context = this._grainTexture.getContext();
  33961. var rand = function (min, max) {
  33962. return Math.random() * (max - min) + min;
  33963. };
  33964. var value;
  33965. for (var x = 0; x < size; x++) {
  33966. for (var y = 0; y < size; y++) {
  33967. value = Math.floor(rand(0.42, 0.58) * 255);
  33968. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  33969. context.fillRect(x, y, 1, 1);
  33970. }
  33971. }
  33972. this._grainTexture.update(false);
  33973. };
  33974. return LensRenderingPipeline;
  33975. })(BABYLON.PostProcessRenderPipeline);
  33976. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  33977. })(BABYLON || (BABYLON = {}));
  33978. //
  33979. // This post-process allows the modification of rendered colors by using
  33980. // a 'look-up table' (LUT). This effect is also called Color Grading.
  33981. //
  33982. // The object needs to be provided an url to a texture containing the color
  33983. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  33984. // Use an image editing software to tweak the LUT to match your needs.
  33985. //
  33986. // For an example of a color LUT, see here:
  33987. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  33988. // For explanations on color grading, see here:
  33989. // http://udn.epicgames.com/Three/ColorGrading.html
  33990. //
  33991. var BABYLON;
  33992. (function (BABYLON) {
  33993. var ColorCorrectionPostProcess = (function (_super) {
  33994. __extends(ColorCorrectionPostProcess, _super);
  33995. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  33996. var _this = this;
  33997. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  33998. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  33999. this._colorTableTexture.anisotropicFilteringLevel = 1;
  34000. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34001. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34002. this.onApply = function (effect) {
  34003. effect.setTexture("colorTable", _this._colorTableTexture);
  34004. };
  34005. }
  34006. return ColorCorrectionPostProcess;
  34007. })(BABYLON.PostProcess);
  34008. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  34009. })(BABYLON || (BABYLON = {}));
  34010. var BABYLON;
  34011. (function (BABYLON) {
  34012. var AnaglyphFreeCamera = (function (_super) {
  34013. __extends(AnaglyphFreeCamera, _super);
  34014. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  34015. _super.call(this, name, position, scene);
  34016. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34017. }
  34018. return AnaglyphFreeCamera;
  34019. })(BABYLON.FreeCamera);
  34020. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  34021. var AnaglyphArcRotateCamera = (function (_super) {
  34022. __extends(AnaglyphArcRotateCamera, _super);
  34023. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  34024. _super.call(this, name, alpha, beta, radius, target, scene);
  34025. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34026. }
  34027. return AnaglyphArcRotateCamera;
  34028. })(BABYLON.ArcRotateCamera);
  34029. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  34030. var AnaglyphGamepadCamera = (function (_super) {
  34031. __extends(AnaglyphGamepadCamera, _super);
  34032. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  34033. _super.call(this, name, position, scene);
  34034. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34035. }
  34036. return AnaglyphGamepadCamera;
  34037. })(BABYLON.GamepadCamera);
  34038. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  34039. var StereoscopicFreeCamera = (function (_super) {
  34040. __extends(StereoscopicFreeCamera, _super);
  34041. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34042. _super.call(this, name, position, scene);
  34043. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34044. }
  34045. return StereoscopicFreeCamera;
  34046. })(BABYLON.FreeCamera);
  34047. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  34048. var StereoscopicArcRotateCamera = (function (_super) {
  34049. __extends(StereoscopicArcRotateCamera, _super);
  34050. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  34051. _super.call(this, name, alpha, beta, radius, target, scene);
  34052. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34053. }
  34054. return StereoscopicArcRotateCamera;
  34055. })(BABYLON.ArcRotateCamera);
  34056. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  34057. var StereoscopicGamepadCamera = (function (_super) {
  34058. __extends(StereoscopicGamepadCamera, _super);
  34059. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34060. _super.call(this, name, position, scene);
  34061. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34062. }
  34063. return StereoscopicGamepadCamera;
  34064. })(BABYLON.GamepadCamera);
  34065. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  34066. })(BABYLON || (BABYLON = {}));
  34067. var BABYLON;
  34068. (function (BABYLON) {
  34069. var HDRRenderingPipeline = (function (_super) {
  34070. __extends(HDRRenderingPipeline, _super);
  34071. /**
  34072. * @constructor
  34073. * @param {string} name - The rendering pipeline name
  34074. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34075. * @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)
  34076. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  34077. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34078. */
  34079. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  34080. var _this = this;
  34081. if (originalPostProcess === void 0) { originalPostProcess = null; }
  34082. _super.call(this, scene.getEngine(), name);
  34083. /**
  34084. * Public members
  34085. */
  34086. // Gaussian Blur
  34087. /**
  34088. * Gaussian blur coefficient
  34089. * @type {number}
  34090. */
  34091. this.gaussCoeff = 0.3;
  34092. /**
  34093. * Gaussian blur mean
  34094. * @type {number}
  34095. */
  34096. this.gaussMean = 1.0;
  34097. /**
  34098. * Gaussian blur standard deviation
  34099. * @type {number}
  34100. */
  34101. this.gaussStandDev = 0.8;
  34102. // HDR
  34103. /**
  34104. * Exposure, controls the overall intensity of the pipeline
  34105. * @type {number}
  34106. */
  34107. this.exposure = 1.0;
  34108. /**
  34109. * Minimum luminance that the post-process can output. Luminance is >= 0
  34110. * @type {number}
  34111. */
  34112. this.minimumLuminance = 1.0;
  34113. /**
  34114. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  34115. * @type {number}
  34116. */
  34117. this.maximumLuminance = 1e20;
  34118. /**
  34119. * Increase rate for luminance: eye adaptation speed to dark
  34120. * @type {number}
  34121. */
  34122. this.luminanceIncreaserate = 0.5;
  34123. /**
  34124. * Decrease rate for luminance: eye adaptation speed to bright
  34125. * @type {number}
  34126. */
  34127. this.luminanceDecreaseRate = 0.5;
  34128. // Bright pass
  34129. /**
  34130. * Minimum luminance needed to compute HDR
  34131. * @type {number}
  34132. */
  34133. this.brightThreshold = 0.8;
  34134. this._needUpdate = true;
  34135. this._scene = scene;
  34136. // Bright pass
  34137. this._createBrightPassPostProcess(scene, ratio);
  34138. // Down sample X4
  34139. this._createDownSampleX4PostProcess(scene, ratio);
  34140. // Create gaussian blur post-processes
  34141. this._createGaussianBlurPostProcess(scene, ratio);
  34142. // Texture adder
  34143. this._createTextureAdderPostProcess(scene, ratio);
  34144. // Luminance generator
  34145. this._createLuminanceGeneratorPostProcess(scene);
  34146. // HDR
  34147. this._createHDRPostProcess(scene, ratio);
  34148. // Pass postprocess
  34149. if (originalPostProcess === null) {
  34150. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34151. }
  34152. else {
  34153. this._originalPostProcess = originalPostProcess;
  34154. }
  34155. // Configure pipeline
  34156. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  34157. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  34158. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  34159. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  34160. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  34161. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  34162. var addDownSamplerPostProcess = function (id) {
  34163. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  34164. };
  34165. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  34166. addDownSamplerPostProcess(i);
  34167. }
  34168. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  34169. // Finish
  34170. scene.postProcessRenderPipelineManager.addPipeline(this);
  34171. if (cameras !== null) {
  34172. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34173. }
  34174. this.update();
  34175. }
  34176. /**
  34177. * Tells the pipeline to update its post-processes
  34178. */
  34179. HDRRenderingPipeline.prototype.update = function () {
  34180. this._needUpdate = true;
  34181. };
  34182. /**
  34183. * Returns the current calculated luminance
  34184. */
  34185. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  34186. return this._hdrCurrentLuminance;
  34187. };
  34188. /**
  34189. * Returns the currently drawn luminance
  34190. */
  34191. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  34192. return this._hdrOutputLuminance;
  34193. };
  34194. /**
  34195. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  34196. */
  34197. HDRRenderingPipeline.prototype.dispose = function () {
  34198. this._originalPostProcess = undefined;
  34199. this._brightPassPostProcess = undefined;
  34200. this._downSampleX4PostProcess = undefined;
  34201. this._guassianBlurHPostProcess = undefined;
  34202. this._guassianBlurVPostProcess = undefined;
  34203. this._textureAdderPostProcess = undefined;
  34204. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  34205. this._downSamplePostProcesses[i] = undefined;
  34206. }
  34207. this._hdrPostProcess = undefined;
  34208. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34209. };
  34210. /**
  34211. * Creates the HDR post-process and computes the luminance adaptation
  34212. */
  34213. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  34214. var _this = this;
  34215. var hdrLastLuminance = 0.0;
  34216. this._hdrOutputLuminance = -1.0;
  34217. this._hdrCurrentLuminance = 1.0;
  34218. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  34219. this._hdrPostProcess.onApply = function (effect) {
  34220. if (_this._hdrOutputLuminance < 0.0) {
  34221. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  34222. }
  34223. else {
  34224. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  34225. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  34226. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  34227. }
  34228. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  34229. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  34230. }
  34231. else {
  34232. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  34233. }
  34234. }
  34235. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  34236. hdrLastLuminance += scene.getEngine().getDeltaTime();
  34237. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  34238. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  34239. effect.setFloat("exposure", _this.exposure);
  34240. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  34241. _this._needUpdate = false;
  34242. };
  34243. };
  34244. /**
  34245. * Texture Adder post-process
  34246. */
  34247. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  34248. var _this = this;
  34249. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  34250. this._textureAdderPostProcess.onApply = function (effect) {
  34251. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  34252. };
  34253. };
  34254. /**
  34255. * Down sample X4 post-process
  34256. */
  34257. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  34258. var _this = this;
  34259. var downSampleX4Offsets = new Array(32);
  34260. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  34261. this._downSampleX4PostProcess.onApply = function (effect) {
  34262. if (_this._needUpdate) {
  34263. var id = 0;
  34264. for (var i = -2; i < 2; i++) {
  34265. for (var j = -2; j < 2; j++) {
  34266. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  34267. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  34268. id += 2;
  34269. }
  34270. }
  34271. }
  34272. effect.setArray2("dsOffsets", downSampleX4Offsets);
  34273. };
  34274. };
  34275. /**
  34276. * Bright pass post-process
  34277. */
  34278. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  34279. var _this = this;
  34280. var brightOffsets = new Array(8);
  34281. var brightPassCallback = function (effect) {
  34282. if (_this._needUpdate) {
  34283. var sU = (1.0 / _this._brightPassPostProcess.width);
  34284. var sV = (1.0 / _this._brightPassPostProcess.height);
  34285. brightOffsets[0] = -0.5 * sU;
  34286. brightOffsets[1] = 0.5 * sV;
  34287. brightOffsets[2] = 0.5 * sU;
  34288. brightOffsets[3] = 0.5 * sV;
  34289. brightOffsets[4] = -0.5 * sU;
  34290. brightOffsets[5] = -0.5 * sV;
  34291. brightOffsets[6] = 0.5 * sU;
  34292. brightOffsets[7] = -0.5 * sV;
  34293. }
  34294. effect.setArray2("dsOffsets", brightOffsets);
  34295. effect.setFloat("brightThreshold", _this.brightThreshold);
  34296. };
  34297. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  34298. this._brightPassPostProcess.onApply = brightPassCallback;
  34299. };
  34300. /**
  34301. * Luminance generator. Creates the luminance post-process and down sample post-processes
  34302. */
  34303. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  34304. var _this = this;
  34305. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  34306. var luminanceOffsets = new Array(8);
  34307. var downSampleOffsets = new Array(18);
  34308. var halfDestPixelSize;
  34309. this._downSamplePostProcesses = new Array(lumSteps);
  34310. // Utils for luminance
  34311. var luminanceUpdateSourceOffsets = function (width, height) {
  34312. var sU = (1.0 / width);
  34313. var sV = (1.0 / height);
  34314. luminanceOffsets[0] = -0.5 * sU;
  34315. luminanceOffsets[1] = 0.5 * sV;
  34316. luminanceOffsets[2] = 0.5 * sU;
  34317. luminanceOffsets[3] = 0.5 * sV;
  34318. luminanceOffsets[4] = -0.5 * sU;
  34319. luminanceOffsets[5] = -0.5 * sV;
  34320. luminanceOffsets[6] = 0.5 * sU;
  34321. luminanceOffsets[7] = -0.5 * sV;
  34322. };
  34323. var luminanceUpdateDestOffsets = function (width, height) {
  34324. var id = 0;
  34325. for (var x = -1; x < 2; x++) {
  34326. for (var y = -1; y < 2; y++) {
  34327. downSampleOffsets[id] = (x) / width;
  34328. downSampleOffsets[id + 1] = (y) / height;
  34329. id += 2;
  34330. }
  34331. }
  34332. };
  34333. // Luminance callback
  34334. var luminanceCallback = function (effect) {
  34335. if (_this._needUpdate) {
  34336. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  34337. }
  34338. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  34339. effect.setArray2("lumOffsets", luminanceOffsets);
  34340. };
  34341. // Down sample callbacks
  34342. var downSampleCallback = function (indice) {
  34343. var i = indice;
  34344. return function (effect) {
  34345. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  34346. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  34347. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  34348. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  34349. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  34350. effect.setArray2("dsOffsets", downSampleOffsets);
  34351. };
  34352. };
  34353. var downSampleAfterRenderCallback = function (effect) {
  34354. // Unpack result
  34355. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  34356. 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);
  34357. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  34358. };
  34359. // Create luminance post-process
  34360. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  34361. 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);
  34362. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  34363. // Create down sample post-processes
  34364. for (var i = lumSteps - 2; i >= 0; i--) {
  34365. var length = Math.pow(3, i);
  34366. ratio = { width: length, height: length };
  34367. var defines = "#define DOWN_SAMPLE\n";
  34368. if (i === 0) {
  34369. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  34370. }
  34371. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  34372. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  34373. if (i === 0) {
  34374. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  34375. }
  34376. }
  34377. };
  34378. /**
  34379. * Gaussian blur post-processes. Horizontal and Vertical
  34380. */
  34381. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  34382. var _this = this;
  34383. var blurOffsetsW = new Array(9);
  34384. var blurOffsetsH = new Array(9);
  34385. var blurWeights = new Array(9);
  34386. var uniforms = ["blurOffsets", "blurWeights"];
  34387. // Utils for gaussian blur
  34388. var calculateBlurOffsets = function (height) {
  34389. var lastOutputDimensions = {
  34390. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  34391. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  34392. };
  34393. for (var i = 0; i < 9; i++) {
  34394. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  34395. if (height) {
  34396. blurOffsetsH[i] = value;
  34397. }
  34398. else {
  34399. blurOffsetsW[i] = value;
  34400. }
  34401. }
  34402. };
  34403. var calculateWeights = function () {
  34404. var x = 0.0;
  34405. for (var i = 0; i < 9; i++) {
  34406. x = (i - 4.0) / 4.0;
  34407. 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));
  34408. }
  34409. };
  34410. // Callback
  34411. var gaussianBlurCallback = function (height) {
  34412. return function (effect) {
  34413. if (_this._needUpdate) {
  34414. calculateWeights();
  34415. calculateBlurOffsets(height);
  34416. }
  34417. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  34418. effect.setArray("blurWeights", blurWeights);
  34419. };
  34420. };
  34421. // Create horizontal gaussian blur post-processes
  34422. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  34423. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  34424. // Create vertical gaussian blur post-process
  34425. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  34426. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  34427. };
  34428. // Luminance generator
  34429. HDRRenderingPipeline.LUM_STEPS = 6;
  34430. return HDRRenderingPipeline;
  34431. })(BABYLON.PostProcessRenderPipeline);
  34432. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  34433. })(BABYLON || (BABYLON = {}));
  34434. var BABYLON;
  34435. (function (BABYLON) {
  34436. var FaceAdjacencies = (function () {
  34437. function FaceAdjacencies() {
  34438. this.edges = new Array();
  34439. this.edgesConnectedCount = 0;
  34440. }
  34441. return FaceAdjacencies;
  34442. })();
  34443. var EdgesRenderer = (function () {
  34444. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  34445. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  34446. if (epsilon === void 0) { epsilon = 0.95; }
  34447. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  34448. this._linesPositions = new Array();
  34449. this._linesNormals = new Array();
  34450. this._linesIndices = new Array();
  34451. this._buffers = new Array();
  34452. this._checkVerticesInsteadOfIndices = false;
  34453. this._source = source;
  34454. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  34455. this._epsilon = epsilon;
  34456. this._prepareRessources();
  34457. this._generateEdgesLines();
  34458. }
  34459. EdgesRenderer.prototype._prepareRessources = function () {
  34460. if (this._lineShader) {
  34461. return;
  34462. }
  34463. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  34464. attributes: ["position", "normal"],
  34465. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  34466. });
  34467. this._lineShader.disableDepthWrite = true;
  34468. this._lineShader.backFaceCulling = false;
  34469. };
  34470. EdgesRenderer.prototype.dispose = function () {
  34471. this._vb0.dispose();
  34472. this._vb1.dispose();
  34473. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  34474. this._lineShader.dispose();
  34475. };
  34476. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  34477. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  34478. return 0;
  34479. }
  34480. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  34481. return 1;
  34482. }
  34483. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  34484. return 2;
  34485. }
  34486. return -1;
  34487. };
  34488. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  34489. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  34490. return 0;
  34491. }
  34492. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  34493. return 1;
  34494. }
  34495. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  34496. return 2;
  34497. }
  34498. return -1;
  34499. };
  34500. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  34501. var needToCreateLine;
  34502. if (edge === undefined) {
  34503. needToCreateLine = true;
  34504. }
  34505. else {
  34506. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  34507. needToCreateLine = dotProduct < this._epsilon;
  34508. }
  34509. if (needToCreateLine) {
  34510. var offset = this._linesPositions.length / 3;
  34511. var normal = p0.subtract(p1);
  34512. normal.normalize();
  34513. // Positions
  34514. this._linesPositions.push(p0.x);
  34515. this._linesPositions.push(p0.y);
  34516. this._linesPositions.push(p0.z);
  34517. this._linesPositions.push(p0.x);
  34518. this._linesPositions.push(p0.y);
  34519. this._linesPositions.push(p0.z);
  34520. this._linesPositions.push(p1.x);
  34521. this._linesPositions.push(p1.y);
  34522. this._linesPositions.push(p1.z);
  34523. this._linesPositions.push(p1.x);
  34524. this._linesPositions.push(p1.y);
  34525. this._linesPositions.push(p1.z);
  34526. // Normals
  34527. this._linesNormals.push(p1.x);
  34528. this._linesNormals.push(p1.y);
  34529. this._linesNormals.push(p1.z);
  34530. this._linesNormals.push(-1);
  34531. this._linesNormals.push(p1.x);
  34532. this._linesNormals.push(p1.y);
  34533. this._linesNormals.push(p1.z);
  34534. this._linesNormals.push(1);
  34535. this._linesNormals.push(p0.x);
  34536. this._linesNormals.push(p0.y);
  34537. this._linesNormals.push(p0.z);
  34538. this._linesNormals.push(-1);
  34539. this._linesNormals.push(p0.x);
  34540. this._linesNormals.push(p0.y);
  34541. this._linesNormals.push(p0.z);
  34542. this._linesNormals.push(1);
  34543. // Indices
  34544. this._linesIndices.push(offset);
  34545. this._linesIndices.push(offset + 1);
  34546. this._linesIndices.push(offset + 2);
  34547. this._linesIndices.push(offset);
  34548. this._linesIndices.push(offset + 2);
  34549. this._linesIndices.push(offset + 3);
  34550. }
  34551. };
  34552. EdgesRenderer.prototype._generateEdgesLines = function () {
  34553. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34554. var indices = this._source.getIndices();
  34555. // First let's find adjacencies
  34556. var adjacencies = new Array();
  34557. var faceNormals = new Array();
  34558. var index;
  34559. var faceAdjacencies;
  34560. // Prepare faces
  34561. for (index = 0; index < indices.length; index += 3) {
  34562. faceAdjacencies = new FaceAdjacencies();
  34563. var p0Index = indices[index];
  34564. var p1Index = indices[index + 1];
  34565. var p2Index = indices[index + 2];
  34566. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  34567. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  34568. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  34569. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  34570. faceNormal.normalize();
  34571. faceNormals.push(faceNormal);
  34572. adjacencies.push(faceAdjacencies);
  34573. }
  34574. // Scan
  34575. for (index = 0; index < adjacencies.length; index++) {
  34576. faceAdjacencies = adjacencies[index];
  34577. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  34578. var otherFaceAdjacencies = adjacencies[otherIndex];
  34579. if (faceAdjacencies.edgesConnectedCount === 3) {
  34580. break;
  34581. }
  34582. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  34583. continue;
  34584. }
  34585. var otherP0 = indices[otherIndex * 3];
  34586. var otherP1 = indices[otherIndex * 3 + 1];
  34587. var otherP2 = indices[otherIndex * 3 + 2];
  34588. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  34589. var otherEdgeIndex;
  34590. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  34591. continue;
  34592. }
  34593. switch (edgeIndex) {
  34594. case 0:
  34595. if (this._checkVerticesInsteadOfIndices) {
  34596. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34597. }
  34598. else {
  34599. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  34600. }
  34601. break;
  34602. case 1:
  34603. if (this._checkVerticesInsteadOfIndices) {
  34604. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34605. }
  34606. else {
  34607. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  34608. }
  34609. break;
  34610. case 2:
  34611. if (this._checkVerticesInsteadOfIndices) {
  34612. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34613. }
  34614. else {
  34615. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  34616. }
  34617. break;
  34618. }
  34619. if (otherEdgeIndex === -1) {
  34620. continue;
  34621. }
  34622. faceAdjacencies.edges[edgeIndex] = otherIndex;
  34623. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  34624. faceAdjacencies.edgesConnectedCount++;
  34625. otherFaceAdjacencies.edgesConnectedCount++;
  34626. if (faceAdjacencies.edgesConnectedCount === 3) {
  34627. break;
  34628. }
  34629. }
  34630. }
  34631. }
  34632. // Create lines
  34633. for (index = 0; index < adjacencies.length; index++) {
  34634. // 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
  34635. var current = adjacencies[index];
  34636. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  34637. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  34638. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  34639. }
  34640. // Merge into a single mesh
  34641. var engine = this._source.getScene().getEngine();
  34642. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  34643. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  34644. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  34645. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  34646. this._ib = engine.createIndexBuffer(this._linesIndices);
  34647. this._indicesCount = this._linesIndices.length;
  34648. };
  34649. EdgesRenderer.prototype.render = function () {
  34650. if (!this._lineShader.isReady()) {
  34651. return;
  34652. }
  34653. var scene = this._source.getScene();
  34654. var engine = scene.getEngine();
  34655. this._lineShader._preBind();
  34656. // VBOs
  34657. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  34658. scene.resetCachedMaterial();
  34659. this._lineShader.setColor4("color", this._source.edgesColor);
  34660. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  34661. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  34662. this._lineShader.bind(this._source.getWorldMatrix());
  34663. // Draw order
  34664. engine.draw(true, 0, this._indicesCount);
  34665. this._lineShader.unbind();
  34666. engine.setDepthWrite(true);
  34667. };
  34668. return EdgesRenderer;
  34669. })();
  34670. BABYLON.EdgesRenderer = EdgesRenderer;
  34671. })(BABYLON || (BABYLON = {}));
  34672. var BABYLON;
  34673. (function (BABYLON) {
  34674. (function (TonemappingOperator) {
  34675. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  34676. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  34677. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  34678. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  34679. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  34680. var TonemappingOperator = BABYLON.TonemappingOperator;
  34681. ;
  34682. var TonemapPostProcess = (function (_super) {
  34683. __extends(TonemapPostProcess, _super);
  34684. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  34685. var _this = this;
  34686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34687. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34688. this._operator = operator;
  34689. this._exposureAdjustment = exposureAdjustment;
  34690. var params = ["_ExposureAdjustment"];
  34691. var defines = "#define ";
  34692. if (operator === TonemappingOperator.Hable)
  34693. defines += "HABLE_TONEMAPPING";
  34694. else if (operator === TonemappingOperator.Reinhard)
  34695. defines += "REINHARD_TONEMAPPING";
  34696. else if (operator === TonemappingOperator.HejiDawson)
  34697. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  34698. else if (operator === TonemappingOperator.Photographic)
  34699. defines += "PHOTOGRAPHIC_TONEMAPPING";
  34700. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  34701. this.onApply = function (effect) {
  34702. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  34703. };
  34704. }
  34705. return TonemapPostProcess;
  34706. })(BABYLON.PostProcess);
  34707. BABYLON.TonemapPostProcess = TonemapPostProcess;
  34708. })(BABYLON || (BABYLON = {}));
  34709. var BABYLON;
  34710. (function (BABYLON) {
  34711. var maxSimultaneousLights = 4;
  34712. var PBRMaterialDefines = (function () {
  34713. function PBRMaterialDefines() {
  34714. this.ALBEDO = false;
  34715. this.CLIPPLANE = false;
  34716. this.ALPHATEST = false;
  34717. this.FOG = false;
  34718. this.NORMAL = false;
  34719. this.UV1 = false;
  34720. this.UV2 = false;
  34721. this.VERTEXCOLOR = false;
  34722. this.VERTEXALPHA = false;
  34723. this.BONES = false;
  34724. this.BONES4 = false;
  34725. this.BonesPerMesh = 0;
  34726. this.INSTANCES = false;
  34727. this.POINTSIZE = false;
  34728. this._keys = Object.keys(this);
  34729. }
  34730. PBRMaterialDefines.prototype.isEqual = function (other) {
  34731. for (var index = 0; index < this._keys.length; index++) {
  34732. var prop = this._keys[index];
  34733. if (this[prop] !== other[prop]) {
  34734. return false;
  34735. }
  34736. }
  34737. return true;
  34738. };
  34739. PBRMaterialDefines.prototype.cloneTo = function (other) {
  34740. for (var index = 0; index < this._keys.length; index++) {
  34741. var prop = this._keys[index];
  34742. other[prop] = this[prop];
  34743. }
  34744. };
  34745. PBRMaterialDefines.prototype.reset = function () {
  34746. for (var index = 0; index < this._keys.length; index++) {
  34747. var prop = this._keys[index];
  34748. if (prop === "BonesPerMesh") {
  34749. this[prop] = 0;
  34750. continue;
  34751. }
  34752. this[prop] = false;
  34753. }
  34754. };
  34755. PBRMaterialDefines.prototype.toString = function () {
  34756. var result = "";
  34757. for (var index = 0; index < this._keys.length; index++) {
  34758. var prop = this._keys[index];
  34759. if (prop === "BonesPerMesh" && this[prop] > 0) {
  34760. result += "#define BonesPerMesh " + this[prop] + "\n";
  34761. continue;
  34762. }
  34763. if (this[prop]) {
  34764. result += "#define " + prop + "\n";
  34765. }
  34766. }
  34767. return result;
  34768. };
  34769. return PBRMaterialDefines;
  34770. })();
  34771. var PBRMaterial = (function (_super) {
  34772. __extends(PBRMaterial, _super);
  34773. function PBRMaterial(name, scene) {
  34774. _super.call(this, name, scene);
  34775. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  34776. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34777. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34778. this._scaledDiffuse = new BABYLON.Color3();
  34779. this._scaledSpecular = new BABYLON.Color3();
  34780. this._defines = new PBRMaterialDefines();
  34781. this._cachedDefines = new PBRMaterialDefines();
  34782. this._cachedDefines.BonesPerMesh = -1;
  34783. }
  34784. PBRMaterial.prototype.needAlphaBlending = function () {
  34785. return this.alpha < 1.0;
  34786. };
  34787. PBRMaterial.prototype.needAlphaTesting = function () {
  34788. return false;
  34789. };
  34790. PBRMaterial.prototype.getAlphaTestTexture = function () {
  34791. return null;
  34792. };
  34793. // Methods
  34794. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  34795. if (this.checkReadyOnlyOnce) {
  34796. if (this._wasPreviouslyReady) {
  34797. return true;
  34798. }
  34799. }
  34800. var scene = this.getScene();
  34801. if (!this.checkReadyOnEveryCall) {
  34802. if (this._renderId === scene.getRenderId()) {
  34803. return true;
  34804. }
  34805. }
  34806. var engine = scene.getEngine();
  34807. var needNormals = false;
  34808. var needUVs = false;
  34809. this._defines.reset();
  34810. // Textures
  34811. if (scene.texturesEnabled) {
  34812. }
  34813. // Effect
  34814. if (scene.clipPlane) {
  34815. this._defines.CLIPPLANE = true;
  34816. }
  34817. if (engine.getAlphaTesting()) {
  34818. this._defines.ALPHATEST = true;
  34819. }
  34820. // Point size
  34821. if (this.pointsCloud || scene.forcePointsCloud) {
  34822. this._defines.POINTSIZE = true;
  34823. }
  34824. // Fog
  34825. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34826. this._defines.FOG = true;
  34827. }
  34828. // Lights
  34829. // Attribs
  34830. if (mesh) {
  34831. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34832. this._defines.NORMAL = true;
  34833. }
  34834. if (needUVs) {
  34835. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34836. this._defines.UV1 = true;
  34837. }
  34838. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34839. this._defines.UV2 = true;
  34840. }
  34841. }
  34842. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34843. this._defines.VERTEXCOLOR = true;
  34844. if (mesh.hasVertexAlpha) {
  34845. this._defines.VERTEXALPHA = true;
  34846. }
  34847. }
  34848. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34849. this._defines.BONES = true;
  34850. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  34851. this._defines.BONES4 = true;
  34852. }
  34853. // Instances
  34854. if (useInstances) {
  34855. this._defines.INSTANCES = true;
  34856. }
  34857. }
  34858. // Get correct effect
  34859. if (!this._defines.isEqual(this._cachedDefines)) {
  34860. this._defines.cloneTo(this._cachedDefines);
  34861. scene.resetCachedMaterial();
  34862. // Fallbacks
  34863. var fallbacks = new BABYLON.EffectFallbacks();
  34864. if (this._defines.FOG) {
  34865. fallbacks.addFallback(1, "FOG");
  34866. }
  34867. if (this._defines.BONES4) {
  34868. fallbacks.addFallback(0, "BONES4");
  34869. }
  34870. //Attributes
  34871. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34872. if (this._defines.NORMAL) {
  34873. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34874. }
  34875. if (this._defines.UV1) {
  34876. attribs.push(BABYLON.VertexBuffer.UVKind);
  34877. }
  34878. if (this._defines.UV2) {
  34879. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34880. }
  34881. if (this._defines.VERTEXCOLOR) {
  34882. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34883. }
  34884. if (this._defines.BONES) {
  34885. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34886. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34887. }
  34888. if (this._defines.INSTANCES) {
  34889. attribs.push("world0");
  34890. attribs.push("world1");
  34891. attribs.push("world2");
  34892. attribs.push("world3");
  34893. }
  34894. // Legacy browser patch
  34895. var join = this._defines.toString();
  34896. this._effect = scene.getEngine().createEffect("pbr", attribs, ["world", "view", "viewProjection", "vEyePosition", "vAlbedoColor",
  34897. "vFogInfos", "vFogColor", "pointSize",
  34898. "mBones",
  34899. "vClipPlane",
  34900. ], [], join, fallbacks, this.onCompiled, this.onError);
  34901. }
  34902. if (!this._effect.isReady()) {
  34903. return false;
  34904. }
  34905. this._renderId = scene.getRenderId();
  34906. this._wasPreviouslyReady = true;
  34907. return true;
  34908. };
  34909. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34910. this._effect.setMatrix("world", world);
  34911. };
  34912. PBRMaterial.prototype.bind = function (world, mesh) {
  34913. var scene = this.getScene();
  34914. // Matrices
  34915. this.bindOnlyWorldMatrix(world);
  34916. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34917. // Bones
  34918. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34919. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34920. }
  34921. if (scene.getCachedMaterial() !== this) {
  34922. // Clip plane
  34923. if (scene.clipPlane) {
  34924. var clipPlane = scene.clipPlane;
  34925. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34926. }
  34927. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  34928. }
  34929. // Point size
  34930. if (this.pointsCloud) {
  34931. this._effect.setFloat("pointSize", this.pointSize);
  34932. }
  34933. // Colors
  34934. this._effect.setColor4("vAlbedoColor", this.albedoColor, this.alpha * mesh.visibility);
  34935. // View
  34936. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34937. this._effect.setMatrix("view", scene.getViewMatrix());
  34938. }
  34939. // Fog
  34940. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34941. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34942. this._effect.setColor3("vFogColor", scene.fogColor);
  34943. }
  34944. _super.prototype.bind.call(this, world, mesh);
  34945. };
  34946. PBRMaterial.prototype.getAnimatables = function () {
  34947. var results = [];
  34948. return results;
  34949. };
  34950. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  34951. _super.prototype.dispose.call(this, forceDisposeEffect);
  34952. };
  34953. PBRMaterial.prototype.clone = function (name) {
  34954. var newPBRMaterial = new PBRMaterial(name, this.getScene());
  34955. // Base material
  34956. this.copyTo(newPBRMaterial);
  34957. // PBRMaterial material
  34958. newPBRMaterial.albedoColor = this.albedoColor.clone();
  34959. return newPBRMaterial;
  34960. };
  34961. return PBRMaterial;
  34962. })(BABYLON.Material);
  34963. BABYLON.PBRMaterial = PBRMaterial;
  34964. })(BABYLON || (BABYLON = {}));
  34965. var BABYLON;
  34966. (function (BABYLON) {
  34967. var ReflectionProbe = (function () {
  34968. //http://localhost:61437/Playground/index%20-%20debug.html#KA93U#7
  34969. function ReflectionProbe(name, size, scene, generateMipMaps) {
  34970. var _this = this;
  34971. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34972. this.name = name;
  34973. this._viewMatrix = BABYLON.Matrix.Identity();
  34974. this._target = BABYLON.Vector3.Zero();
  34975. this._add = BABYLON.Vector3.Zero();
  34976. this.position = BABYLON.Vector3.Zero();
  34977. this._scene = scene;
  34978. this._scene.reflectionProbes.push(this);
  34979. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  34980. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  34981. switch (faceIndex) {
  34982. case 0:
  34983. _this._add.copyFromFloats(1, 0, 0);
  34984. break;
  34985. case 1:
  34986. _this._add.copyFromFloats(-1, 0, 0);
  34987. break;
  34988. case 2:
  34989. _this._add.copyFromFloats(0, -1, 0);
  34990. break;
  34991. case 3:
  34992. _this._add.copyFromFloats(0, 1, 0);
  34993. break;
  34994. case 4:
  34995. _this._add.copyFromFloats(0, 0, 1);
  34996. break;
  34997. case 5:
  34998. _this._add.copyFromFloats(0, 0, -1);
  34999. break;
  35000. }
  35001. if (_this._attachedMesh) {
  35002. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35003. }
  35004. _this.position.addToRef(_this._add, _this._target);
  35005. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35006. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35007. };
  35008. this._renderTargetTexture.onAfterUnbind = function () {
  35009. scene.updateTransformMatrix(true);
  35010. };
  35011. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35012. }
  35013. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35014. get: function () {
  35015. return this._renderTargetTexture.refreshRate;
  35016. },
  35017. set: function (value) {
  35018. this._renderTargetTexture.refreshRate = value;
  35019. },
  35020. enumerable: true,
  35021. configurable: true
  35022. });
  35023. ReflectionProbe.prototype.getScene = function () {
  35024. return this._scene;
  35025. };
  35026. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35027. get: function () {
  35028. return this._renderTargetTexture;
  35029. },
  35030. enumerable: true,
  35031. configurable: true
  35032. });
  35033. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35034. get: function () {
  35035. return this._renderTargetTexture.renderList;
  35036. },
  35037. enumerable: true,
  35038. configurable: true
  35039. });
  35040. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35041. this._attachedMesh = mesh;
  35042. };
  35043. ReflectionProbe.prototype.dispose = function () {
  35044. var index = this._scene.reflectionProbes.indexOf(this);
  35045. if (index !== -1) {
  35046. // Remove from the scene if found
  35047. this._scene.reflectionProbes.splice(index, 1);
  35048. }
  35049. };
  35050. return ReflectionProbe;
  35051. })();
  35052. BABYLON.ReflectionProbe = ReflectionProbe;
  35053. })(BABYLON || (BABYLON = {}));
  35054. var BABYLON;
  35055. (function (BABYLON) {
  35056. var SolidParticle = (function () {
  35057. function SolidParticle(particleIndex, positionIndex, shape, shapeUV, shapeId) {
  35058. this.shapeId = shapeId;
  35059. this.color = new BABYLON.Color4(1, 1, 1, 1);
  35060. this.position = BABYLON.Vector3.Zero();
  35061. this.rotation = BABYLON.Vector3.Zero();
  35062. this.scale = new BABYLON.Vector3(1, 1, 1);
  35063. this.uvs = new BABYLON.Vector4(0, 0, 1, 1);
  35064. this.velocity = BABYLON.Vector3.Zero();
  35065. this.alive = true;
  35066. this.idx = particleIndex;
  35067. this._pos = positionIndex;
  35068. this._shape = shape;
  35069. this._shapeUV = shapeUV;
  35070. }
  35071. return SolidParticle;
  35072. })();
  35073. BABYLON.SolidParticle = SolidParticle;
  35074. })(BABYLON || (BABYLON = {}));
  35075. var BABYLON;
  35076. (function (BABYLON) {
  35077. var SolidParticleSystem = (function () {
  35078. function SolidParticleSystem(name, scene) {
  35079. // public members
  35080. this.particles = new Array();
  35081. this.nbParticles = 0;
  35082. this.billboard = false;
  35083. this.counter = 0;
  35084. this._positions = new Array();
  35085. this._indices = new Array();
  35086. this._normals = new Array();
  35087. this._colors = new Array();
  35088. this._uvs = new Array();
  35089. this._index = 0; // indices index
  35090. this._shapeCounter = 0;
  35091. this._useParticleColor = true;
  35092. this._useParticleTexture = true;
  35093. this._useParticleRotation = true;
  35094. this._useParticleVertex = false;
  35095. this._cam_axisZ = BABYLON.Vector3.Zero();
  35096. this._cam_axisY = BABYLON.Vector3.Zero();
  35097. this._cam_axisX = BABYLON.Vector3.Zero();
  35098. this._axisX = BABYLON.Axis.X;
  35099. this._axisY = BABYLON.Axis.Y;
  35100. this._axisZ = BABYLON.Axis.Z;
  35101. this._fakeCamPos = BABYLON.Vector3.Zero();
  35102. this._rotMatrix = new BABYLON.Matrix();
  35103. this._invertedMatrix = new BABYLON.Matrix();
  35104. this._rotated = BABYLON.Vector3.Zero();
  35105. this._quaternion = new BABYLON.Quaternion();
  35106. this._vertex = BABYLON.Vector3.Zero();
  35107. this._yaw = 0.0;
  35108. this._pitch = 0.0;
  35109. this._roll = 0.0;
  35110. this._halfroll = 0.0;
  35111. this._halfpitch = 0.0;
  35112. this._halfyaw = 0.0;
  35113. this._sinRoll = 0.0;
  35114. this._cosRoll = 0.0;
  35115. this._sinPitch = 0.0;
  35116. this._cosPitch = 0.0;
  35117. this._sinYaw = 0.0;
  35118. this._cosYaw = 0.0;
  35119. this.name = name;
  35120. this._scene = scene;
  35121. this._camera = scene.activeCamera;
  35122. }
  35123. // build the SPS mesh : returns the mesh
  35124. SolidParticleSystem.prototype.buildMesh = function () {
  35125. if (this.nbParticles === 0) {
  35126. var triangle = BABYLON.Mesh.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35127. this.addShape(triangle, 1);
  35128. triangle.dispose();
  35129. }
  35130. BABYLON.VertexData.ComputeNormals(this._positions, this._indices, this._normals);
  35131. var vertexData = new BABYLON.VertexData();
  35132. vertexData.positions = this._positions;
  35133. vertexData.indices = this._indices;
  35134. vertexData.normals = this._normals;
  35135. if (this._uvs) {
  35136. vertexData.uvs = this._uvs;
  35137. }
  35138. if (this._colors) {
  35139. vertexData.colors = this._colors;
  35140. }
  35141. var mesh = new BABYLON.Mesh(name, this._scene);
  35142. vertexData.applyToMesh(mesh, true);
  35143. this.mesh = mesh;
  35144. return mesh;
  35145. };
  35146. // _meshBuilder : inserts the shape model in the global SPS mesh
  35147. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors) {
  35148. var i;
  35149. var u = 0;
  35150. var c = 0;
  35151. for (i = 0; i < shape.length; i++) {
  35152. positions.push(shape[i].x, shape[i].y, shape[i].z);
  35153. if (meshUV) {
  35154. uvs.push(meshUV[u], meshUV[u + 1]);
  35155. u += 2;
  35156. }
  35157. if (meshCol) {
  35158. colors.push(meshCol[c], meshCol[c + 1], meshCol[c + 2], meshCol[c + 3]);
  35159. c += 4;
  35160. }
  35161. else {
  35162. colors.push(1, 1, 1, 1);
  35163. }
  35164. }
  35165. for (i = 0; i < meshInd.length; i++) {
  35166. indices.push(p + meshInd[i]);
  35167. }
  35168. };
  35169. // returns a shape array from positions array
  35170. SolidParticleSystem.prototype._posToShape = function (positions) {
  35171. var shape = [];
  35172. for (var i = 0; i < positions.length; i += 3) {
  35173. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  35174. }
  35175. return shape;
  35176. };
  35177. // returns a shapeUV array from a Vector4 uvs
  35178. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  35179. var shapeUV = [];
  35180. if (uvs) {
  35181. for (var i = 0; i < uvs.length; i++)
  35182. shapeUV.push(uvs[i]);
  35183. }
  35184. return shapeUV;
  35185. };
  35186. // adds a new particle object in the particles array and double links the particle (next/previous)
  35187. SolidParticleSystem.prototype._addParticle = function (p, idxpos, shape, shapeUV, shapeId) {
  35188. this._particle = new BABYLON.SolidParticle(p, idxpos, shape, shapeUV, shapeId);
  35189. this.particles.push(this._particle);
  35190. this._particle.previous = this._previousParticle;
  35191. if (this._previousParticle) {
  35192. this._previousParticle.next = this._particle;
  35193. }
  35194. this._previousParticle = this._particle;
  35195. };
  35196. // add solid particles from a shape model in the particles array
  35197. SolidParticleSystem.prototype.addShape = function (mesh, nb) {
  35198. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35199. var meshInd = mesh.getIndices();
  35200. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35201. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35202. var shape = this._posToShape(meshPos);
  35203. var shapeUV = this._uvsToShapeUV(meshUV);
  35204. // particles
  35205. for (var i = 0; i < nb; i++) {
  35206. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors);
  35207. this._addParticle(this.nbParticles + i, this._positions.length, shape, shapeUV, this._shapeCounter);
  35208. this._index += shape.length;
  35209. }
  35210. this.nbParticles += nb;
  35211. this._shapeCounter++;
  35212. return this._shapeCounter;
  35213. };
  35214. // resets a particle back to its just built status
  35215. SolidParticleSystem.prototype.resetParticle = function (particle) {
  35216. for (var pt = 0; pt < particle._shape.length; pt++) {
  35217. this._positions[particle._pos + pt * 3] = particle._shape[pt].x;
  35218. this._positions[particle._pos + pt * 3 + 1] = particle._shape[pt].y;
  35219. this._positions[particle._pos + pt * 3 + 2] = particle._shape[pt].z;
  35220. }
  35221. };
  35222. // sets all the particles
  35223. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  35224. if (start === void 0) { start = 0; }
  35225. if (end === void 0) { end = this.nbParticles - 1; }
  35226. if (update === void 0) { update = true; }
  35227. // custom beforeUpdate
  35228. this.beforeUpdateParticles(start, end, update);
  35229. this._cam_axisX.x = 1;
  35230. this._cam_axisX.y = 0;
  35231. this._cam_axisX.z = 0;
  35232. this._cam_axisY.x = 0;
  35233. this._cam_axisY.y = 1;
  35234. this._cam_axisY.z = 0;
  35235. this._cam_axisZ.x = 0;
  35236. this._cam_axisZ.y = 0;
  35237. this._cam_axisZ.z = 1;
  35238. // if the particles will always face the camera
  35239. if (this.billboard) {
  35240. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  35241. this._yaw = this.mesh.rotation.y;
  35242. this._pitch = this.mesh.rotation.x;
  35243. this._roll = this.mesh.rotation.z;
  35244. this._quaternionRotationYPR();
  35245. this._quaternionToRotationMatrix();
  35246. this._rotMatrix.invertToRef(this._invertedMatrix);
  35247. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertedMatrix, this._fakeCamPos);
  35248. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  35249. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  35250. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  35251. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  35252. this._cam_axisY.normalize();
  35253. this._cam_axisX.normalize();
  35254. this._cam_axisZ.normalize();
  35255. }
  35256. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  35257. var idx = 0;
  35258. var index = 0;
  35259. var colidx = 0;
  35260. var colorIndex = 0;
  35261. var uvidx = 0;
  35262. var uvIndex = 0;
  35263. // particle loop
  35264. for (var p = start; p <= end; p++) {
  35265. this._particle = this.particles[p];
  35266. // call to custom user function to update the particle properties
  35267. this.updateParticle(this._particle);
  35268. // particle rotation matrix
  35269. if (this.billboard) {
  35270. this._particle.rotation.x = 0.0;
  35271. this._particle.rotation.y = 0.0;
  35272. }
  35273. if (this._useParticleRotation) {
  35274. if (this._particle.quaternion) {
  35275. this._quaternion.x = this._particle.quaternion.x;
  35276. this._quaternion.y = this._particle.quaternion.y;
  35277. this._quaternion.z = this._particle.quaternion.z;
  35278. this._quaternion.w = this._particle.quaternion.w;
  35279. }
  35280. else {
  35281. this._yaw = this._particle.rotation.y;
  35282. this._pitch = this._particle.rotation.x;
  35283. this._roll = this._particle.rotation.z;
  35284. this._quaternionRotationYPR();
  35285. }
  35286. this._quaternionToRotationMatrix();
  35287. }
  35288. for (var pt = 0; pt < this._particle._shape.length; pt++) {
  35289. idx = index + pt * 3;
  35290. colidx = colorIndex + pt * 4;
  35291. uvidx = uvIndex + pt * 2;
  35292. this._vertex.x = this._particle._shape[pt].x;
  35293. this._vertex.y = this._particle._shape[pt].y;
  35294. this._vertex.z = this._particle._shape[pt].z;
  35295. if (this._useParticleVertex) {
  35296. this.updateParticleVertex(this._particle, this._vertex, pt);
  35297. }
  35298. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35299. this._positions[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x * this._particle.scale.x + this._cam_axisY.x * this._rotated.y * this._particle.scale.y + this._cam_axisZ.x * this._rotated.z * this._particle.scale.z;
  35300. this._positions[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x * this._particle.scale.x + this._cam_axisY.y * this._rotated.y * this._particle.scale.y + this._cam_axisZ.y * this._rotated.z * this._particle.scale.z;
  35301. this._positions[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x * this._particle.scale.x + this._cam_axisY.z * this._rotated.y * this._particle.scale.y + this._cam_axisZ.z * this._rotated.z * this._particle.scale.z;
  35302. if (this._useParticleColor) {
  35303. this._colors[colidx] = this._particle.color.r;
  35304. this._colors[colidx + 1] = this._particle.color.g;
  35305. this._colors[colidx + 2] = this._particle.color.b;
  35306. this._colors[colidx + 3] = this._particle.color.a;
  35307. }
  35308. if (this._useParticleTexture) {
  35309. this._uvs[uvidx] = this._particle._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  35310. this._uvs[uvidx + 1] = this._particle._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  35311. }
  35312. }
  35313. index = idx + 3;
  35314. colorIndex = colidx + 4;
  35315. uvIndex = uvidx + 2;
  35316. }
  35317. if (update) {
  35318. if (this._useParticleColor) {
  35319. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors, false, false);
  35320. }
  35321. if (this._useParticleTexture) {
  35322. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs, false, false);
  35323. }
  35324. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions, false, false);
  35325. if (!this.mesh.areNormalsFrozen) {
  35326. BABYLON.VertexData.ComputeNormals(this._positions, this._indices, this._normals);
  35327. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals, false, false);
  35328. }
  35329. }
  35330. this.afterUpdateParticles(start, end, update);
  35331. };
  35332. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  35333. this._halfroll = this._roll * 0.5;
  35334. this._halfpitch = this._pitch * 0.5;
  35335. this._halfyaw = this._yaw * 0.5;
  35336. this._sinRoll = Math.sin(this._halfroll);
  35337. this._cosRoll = Math.cos(this._halfroll);
  35338. this._sinPitch = Math.sin(this._halfpitch);
  35339. this._cosPitch = Math.cos(this._halfpitch);
  35340. this._sinYaw = Math.sin(this._halfyaw);
  35341. this._cosYaw = Math.cos(this._halfyaw);
  35342. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  35343. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  35344. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  35345. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  35346. };
  35347. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  35348. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  35349. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  35350. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  35351. this._rotMatrix.m[3] = 0;
  35352. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  35353. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  35354. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  35355. this._rotMatrix.m[7] = 0;
  35356. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  35357. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  35358. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  35359. this._rotMatrix.m[11] = 0;
  35360. this._rotMatrix.m[12] = 0;
  35361. this._rotMatrix.m[13] = 0;
  35362. this._rotMatrix.m[14] = 0;
  35363. this._rotMatrix.m[15] = 1.0;
  35364. };
  35365. // dispose the SPS
  35366. SolidParticleSystem.prototype.dispose = function () {
  35367. this.mesh.dispose();
  35368. };
  35369. Object.defineProperty(SolidParticleSystem.prototype, "useParticleRotation", {
  35370. // getters
  35371. get: function () {
  35372. return this._useParticleRotation;
  35373. },
  35374. // Optimizer setters
  35375. set: function (val) {
  35376. this._useParticleRotation = val;
  35377. },
  35378. enumerable: true,
  35379. configurable: true
  35380. });
  35381. Object.defineProperty(SolidParticleSystem.prototype, "useParticleColor", {
  35382. get: function () {
  35383. return this._useParticleColor;
  35384. },
  35385. set: function (val) {
  35386. this._useParticleColor = val;
  35387. },
  35388. enumerable: true,
  35389. configurable: true
  35390. });
  35391. Object.defineProperty(SolidParticleSystem.prototype, "useParticleTexture", {
  35392. get: function () {
  35393. return this._useParticleTexture;
  35394. },
  35395. set: function (val) {
  35396. this._useParticleTexture = val;
  35397. },
  35398. enumerable: true,
  35399. configurable: true
  35400. });
  35401. Object.defineProperty(SolidParticleSystem.prototype, "useParticleVertex", {
  35402. get: function () {
  35403. return this._useParticleVertex;
  35404. },
  35405. set: function (val) {
  35406. this._useParticleVertex = val;
  35407. },
  35408. enumerable: true,
  35409. configurable: true
  35410. });
  35411. // =======================================================================
  35412. // Particle behavior logic
  35413. // these following methods may be overwritten by the user to fit his needs
  35414. // init : sets all particles first values and calls updateParticle to set them in space
  35415. // can be overwritten by the user
  35416. SolidParticleSystem.prototype.initParticles = function () {
  35417. };
  35418. // recycles a particle : can by overwritten by the user
  35419. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  35420. return particle;
  35421. };
  35422. // updates a particle : can be overwritten by the user
  35423. // will be called on each particle by setParticles() :
  35424. // ex : just set a particle position or velocity and recycle conditions
  35425. SolidParticleSystem.prototype.updateParticle = function (particle) {
  35426. return particle;
  35427. };
  35428. // updates a vertex of a particle : can be overwritten by the user
  35429. // will be called on each vertex particle by setParticles() :
  35430. // ex : just set a vertex particle position
  35431. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, i) {
  35432. return vertex;
  35433. };
  35434. // will be called before any other treatment by setParticles()
  35435. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  35436. };
  35437. // will be called after all setParticles() treatments
  35438. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  35439. };
  35440. return SolidParticleSystem;
  35441. })();
  35442. BABYLON.SolidParticleSystem = SolidParticleSystem;
  35443. })(BABYLON || (BABYLON = {}));
  35444. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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\nprecision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n\t#ifdef SPECULAR\r\n\t\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\t\tspecularColor = specularMapColor.rgb;\r\n\t\t#ifdef GLOSSINESS\r\n\t\t\tglossiness = glossiness * specularMapColor.a;\r\n\t\t#endif\r\n\t#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\t#ifdef REFLECTIONMAP_3D\r\n\t\t\tfloat bias = 0.;\r\n\r\n\t\t#ifdef ROUGHNESS\r\n\t\t\t\tbias = vReflectionInfos.y;\r\n\t\t#endif\r\n\r\n\t\t#ifdef SPECULARTERM\r\n\t\t\t#ifdef SPECULAR\r\n\t\t\t\t#ifdef GLOSSINESS\r\n\t\t\t\t\t\tbias *= (1.0 - specularMapColor.a);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\r\n\t\t#endif\r\n\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x * shadow;\r\n\t#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\t#ifdef REFLECTIONMAP_PROJECTION\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x * shadow;\r\n#endif\t\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n vec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\tfloat lightmapIllum = clamp(dot(lightmapColor, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n\r\n\tif (lightmapIllum > vLightmapInfos.z)\r\n\t{\r\n\t\tcolor.rgb += lightmapColor;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcolor.rgb *= lightmapColor;\r\n\t}\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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\nprecision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","pbrPixelShader":"precision highp float;\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec4 vAlbedoColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec3 baseColor = vAlbedoColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vAlbedoColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n\t// Composition\r\n vec4 color = vec4(clamp(baseColor, 0.0, 1.0), alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","pbrVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","postprocessVertexShader":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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}"};
  35445. 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=g*(2*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=g*(2*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=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,o){return this.r===t&&this.g===i&&this.b===o},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||7!==o.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16);return i.FromInts(n,r,s)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2])},i.FromInts=function(t,o,n){return new i(t/255,o/255,n/255)},i.Lerp=function(t,o,n){var r=t.r+(o.r-t.r)*n,s=t.g+(o.g-t.g)*n,e=t.b+(o.b-t.b)*n;return new i(r,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var o=function(){function i(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0,r=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||9!==o.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16),e=parseInt(o.substring(7,9),16);return i.FromInts(n,r,s,e)},i.Lerp=function(t,o,n){var r=new i(0,0,0,0);return i.LerpToRef(t,o,n,r),r},i.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromInts=function(t,o,n,r){return new i(t/255,o/255,n/255,r/255)},i}();t.Color4=o;var n=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a);return new i(h,u)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},i}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromFloatArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),l=SIMD.float32x4.load(n.m,8),m=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),l=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(n).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert();var u=new i(o.x/n*2-1,-(o.y/r*2-1),o.z),l=i.TransformCoordinates(u,h),m=u.x*h.m[3]+u.y*h.m[7]+u.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(m,1)&&(l=l.scale(1/m)),l},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(t,o,n){var r=i.Zero();return i.RotationFromAxisToRef(t,o,n,r),r},i.RotationFromAxisToRef=function(o,n,r,s){var e,a,h,u=i.Normalize(o),l=i.Normalize(r),m=f.X,x=f.Y,y=0,c=0,p=0,z=0,M=0,w=0,d=0,I=-1,D=0,S=0;t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?w=1:t.Tools.WithinEpsilon(l.x,0,t.Engine.Epsilon)?z=1:(d=l.z/l.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),a=new i(z,M,w),a.normalize(),h=i.Cross(l,a),h.normalize(),e=i.Cross(u,a),e.normalize(),i.Dot(l,e)<0&&(I=1),S=i.Dot(u,a),S=Math.min(1,Math.max(-1,S)),p=Math.acos(S)*I,i.Dot(a,m)<0&&(p=Math.PI+p,a=a.scaleInPlace(-1),h=h.scaleInPlace(-1),D++);var v,g;z=0,M=0,w=0,I=-1,t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?z=1:(d=a.z/a.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),v=new i(z,M,w),v.normalize(),g=i.Cross(v,a),g.normalize(),e=i.Cross(l,v),e.normalize(),i.Dot(a,e)<0&&(I=1),S=i.Dot(l,v),S=Math.min(1,Math.max(-1,S)),c=Math.acos(S)*I,i.Dot(g,x)<0&&(c=Math.PI+c,g=g.scaleInPlace(-1),v=v.scaleInPlace(-1),D++),I=-1,e=i.Cross(m,a),e.normalize(),i.Dot(e,x)<0&&(I=1),S=i.Dot(a,m),S=Math.min(1,Math.max(-1,S)),y=-Math.acos(S)*I,0>S&&2>D&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)&&t.Tools.WithinEpsilon(this.w,i.w,o)},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,r=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,n,r,s),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,l=o*n,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],l=n[2],m=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return i.normalize(),n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var o=new i;return this.addToRef(t,o),o},i.prototype.addToRef=function(t,i){for(var o=0;16>o;o++)i.m[o]=this.m[o]+t.m[o];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,d=u*p-f*x,I=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,F=e*c-a*y,A=s*p-h*x,P=s*c-a*x,C=s*y-e*x,E=a*f-h*m,L=e*f-h*l,q=e*m-a*l,Z=s*f-h*u,H=s*m-a*u,W=s*l-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*F)*R,t.m[6]=-(i*_-n*A+r*P)*R,t.m[10]=(i*b-o*A+r*C)*R,t.m[14]=-(i*F-o*P+n*C)*R,t.m[3]=-(o*E-n*L+r*q)*R,t.m[7]=(i*E-n*Z+r*H)*R,t.m[11]=-(i*L-o*Z+r*W)*R,t.m[15]=(i*q-o*H+n*W)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],F=t.m[11],A=t.m[12],P=t.m[13],C=t.m[14],E=t.m[15];return i[o]=n*w+r*S+s*R+e*A,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*F+e*E,i[o+4]=a*w+h*S+u*R+l*A,i[o+5]=a*d+h*v+u*_+l*P,i[o+6]=a*I+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*F+l*E,i[o+8]=m*w+f*S+x*R+y*A,i[o+9]=m*d+f*v+x*_+y*P,i[o+10]=m*I+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*F+y*E,i[o+12]=c*w+p*S+z*R+M*A,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*F+M*E,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));\nvar l=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromFloat32ArrayToRefScaled=function(t,i,o,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]*o},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=i.Zero();return i.RotationAxisToRef(t,o,n),n},i.RotationAxisToRef=function(t,i,o){var n=Math.sin(-i),r=Math.cos(-i),s=1-r;t.normalize(),o.m[0]=t.x*t.x*s+r,o.m[1]=t.x*t.y*s-t.z*n,o.m[2]=t.x*t.z*s+t.y*n,o.m[3]=0,o.m[4]=t.y*t.x*s+t.z*n,o.m[5]=t.y*t.y*s+r,o.m[6]=t.y*t.z*s-t.x*n,o.m[7]=0,o.m[8]=t.z*t.x*s-t.y*n,o.m[9]=t.z*t.y*s+t.x*n,o.m[10]=t.z*t.z*s+r,o.m[11]=0,o.m[15]=1},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(l,m,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;h?s.m[0]=a/o:s.m[0]=a,s.m[1]=s.m[2]=s.m[3]=0,h?s.m[5]=a:s.m[5]=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={}));";
  35446. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  35447. module.exports = BABYLON;
  35448. };