babylon.max.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103
  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 ToGammaSpace = 1 / 2.2;
  10. var ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. return Color4;
  270. })();
  271. BABYLON.Color4 = Color4;
  272. var Vector2 = (function () {
  273. function Vector2(x, y) {
  274. this.x = x;
  275. this.y = y;
  276. }
  277. Vector2.prototype.toString = function () {
  278. return "{X: " + this.x + " Y:" + this.y + "}";
  279. };
  280. // Operators
  281. Vector2.prototype.toArray = function (array, index) {
  282. if (index === void 0) { index = 0; }
  283. array[index] = this.x;
  284. array[index + 1] = this.y;
  285. return this;
  286. };
  287. Vector2.prototype.asArray = function () {
  288. var result = [];
  289. this.toArray(result, 0);
  290. return result;
  291. };
  292. Vector2.prototype.copyFrom = function (source) {
  293. this.x = source.x;
  294. this.y = source.y;
  295. return this;
  296. };
  297. Vector2.prototype.copyFromFloats = function (x, y) {
  298. this.x = x;
  299. this.y = y;
  300. return this;
  301. };
  302. Vector2.prototype.add = function (otherVector) {
  303. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  304. };
  305. Vector2.prototype.addVector3 = function (otherVector) {
  306. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  307. };
  308. Vector2.prototype.subtract = function (otherVector) {
  309. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  310. };
  311. Vector2.prototype.subtractInPlace = function (otherVector) {
  312. this.x -= otherVector.x;
  313. this.y -= otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.multiplyInPlace = function (otherVector) {
  317. this.x *= otherVector.x;
  318. this.y *= otherVector.y;
  319. return this;
  320. };
  321. Vector2.prototype.multiply = function (otherVector) {
  322. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  323. };
  324. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  325. result.x = this.x * otherVector.x;
  326. result.y = this.y * otherVector.y;
  327. return this;
  328. };
  329. Vector2.prototype.multiplyByFloats = function (x, y) {
  330. return new Vector2(this.x * x, this.y * y);
  331. };
  332. Vector2.prototype.divide = function (otherVector) {
  333. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  334. };
  335. Vector2.prototype.divideToRef = function (otherVector, result) {
  336. result.x = this.x / otherVector.x;
  337. result.y = this.y / otherVector.y;
  338. return this;
  339. };
  340. Vector2.prototype.negate = function () {
  341. return new Vector2(-this.x, -this.y);
  342. };
  343. Vector2.prototype.scaleInPlace = function (scale) {
  344. this.x *= scale;
  345. this.y *= scale;
  346. return this;
  347. };
  348. Vector2.prototype.scale = function (scale) {
  349. return new Vector2(this.x * scale, this.y * scale);
  350. };
  351. Vector2.prototype.equals = function (otherVector) {
  352. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  353. };
  354. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  355. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  356. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  357. };
  358. // Properties
  359. Vector2.prototype.length = function () {
  360. return Math.sqrt(this.x * this.x + this.y * this.y);
  361. };
  362. Vector2.prototype.lengthSquared = function () {
  363. return (this.x * this.x + this.y * this.y);
  364. };
  365. // Methods
  366. Vector2.prototype.normalize = function () {
  367. var len = this.length();
  368. if (len === 0)
  369. return this;
  370. var num = 1.0 / len;
  371. this.x *= num;
  372. this.y *= num;
  373. return this;
  374. };
  375. Vector2.prototype.clone = function () {
  376. return new Vector2(this.x, this.y);
  377. };
  378. // Statics
  379. Vector2.Zero = function () {
  380. return new Vector2(0, 0);
  381. };
  382. Vector2.FromArray = function (array, offset) {
  383. if (offset === void 0) { offset = 0; }
  384. return new Vector2(array[offset], array[offset + 1]);
  385. };
  386. Vector2.FromArrayToRef = function (array, offset, result) {
  387. result.x = array[offset];
  388. result.y = array[offset + 1];
  389. };
  390. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  391. var squared = amount * amount;
  392. var cubed = amount * squared;
  393. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  394. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  395. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  396. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  397. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  398. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  399. return new Vector2(x, y);
  400. };
  401. Vector2.Clamp = function (value, min, max) {
  402. var x = value.x;
  403. x = (x > max.x) ? max.x : x;
  404. x = (x < min.x) ? min.x : x;
  405. var y = value.y;
  406. y = (y > max.y) ? max.y : y;
  407. y = (y < min.y) ? min.y : y;
  408. return new Vector2(x, y);
  409. };
  410. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  411. var squared = amount * amount;
  412. var cubed = amount * squared;
  413. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  414. var part2 = (-2.0 * cubed) + (3.0 * squared);
  415. var part3 = (cubed - (2.0 * squared)) + amount;
  416. var part4 = cubed - squared;
  417. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  418. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  419. return new Vector2(x, y);
  420. };
  421. Vector2.Lerp = function (start, end, amount) {
  422. var x = start.x + ((end.x - start.x) * amount);
  423. var y = start.y + ((end.y - start.y) * amount);
  424. return new Vector2(x, y);
  425. };
  426. Vector2.Dot = function (left, right) {
  427. return left.x * right.x + left.y * right.y;
  428. };
  429. Vector2.Normalize = function (vector) {
  430. var newVector = vector.clone();
  431. newVector.normalize();
  432. return newVector;
  433. };
  434. Vector2.Minimize = function (left, right) {
  435. var x = (left.x < right.x) ? left.x : right.x;
  436. var y = (left.y < right.y) ? left.y : right.y;
  437. return new Vector2(x, y);
  438. };
  439. Vector2.Maximize = function (left, right) {
  440. var x = (left.x > right.x) ? left.x : right.x;
  441. var y = (left.y > right.y) ? left.y : right.y;
  442. return new Vector2(x, y);
  443. };
  444. Vector2.Transform = function (vector, transformation) {
  445. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  446. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  447. return new Vector2(x, y);
  448. };
  449. Vector2.Distance = function (value1, value2) {
  450. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  451. };
  452. Vector2.DistanceSquared = function (value1, value2) {
  453. var x = value1.x - value2.x;
  454. var y = value1.y - value2.y;
  455. return (x * x) + (y * y);
  456. };
  457. return Vector2;
  458. })();
  459. BABYLON.Vector2 = Vector2;
  460. var Vector3 = (function () {
  461. function Vector3(x, y, z) {
  462. this.x = x;
  463. this.y = y;
  464. this.z = z;
  465. }
  466. Vector3.prototype.toString = function () {
  467. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  468. };
  469. // Operators
  470. Vector3.prototype.asArray = function () {
  471. var result = [];
  472. this.toArray(result, 0);
  473. return result;
  474. };
  475. Vector3.prototype.toArray = function (array, index) {
  476. if (index === void 0) { index = 0; }
  477. array[index] = this.x;
  478. array[index + 1] = this.y;
  479. array[index + 2] = this.z;
  480. return this;
  481. };
  482. Vector3.prototype.toQuaternion = function () {
  483. var result = new Quaternion(0, 0, 0, 1);
  484. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  485. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  486. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  487. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  488. var cosy = Math.cos(this.y * 0.5);
  489. var siny = Math.sin(this.y * 0.5);
  490. result.x = coszMinusx * siny;
  491. result.y = -sinzMinusx * siny;
  492. result.z = sinxPlusz * cosy;
  493. result.w = cosxPlusz * cosy;
  494. return result;
  495. };
  496. Vector3.prototype.addInPlace = function (otherVector) {
  497. this.x += otherVector.x;
  498. this.y += otherVector.y;
  499. this.z += otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.add = function (otherVector) {
  503. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  504. };
  505. Vector3.prototype.addToRef = function (otherVector, result) {
  506. result.x = this.x + otherVector.x;
  507. result.y = this.y + otherVector.y;
  508. result.z = this.z + otherVector.z;
  509. return this;
  510. };
  511. Vector3.prototype.subtractInPlace = function (otherVector) {
  512. this.x -= otherVector.x;
  513. this.y -= otherVector.y;
  514. this.z -= otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.subtract = function (otherVector) {
  518. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  519. };
  520. Vector3.prototype.subtractToRef = function (otherVector, result) {
  521. result.x = this.x - otherVector.x;
  522. result.y = this.y - otherVector.y;
  523. result.z = this.z - otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  527. return new Vector3(this.x - x, this.y - y, this.z - z);
  528. };
  529. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  530. result.x = this.x - x;
  531. result.y = this.y - y;
  532. result.z = this.z - z;
  533. return this;
  534. };
  535. Vector3.prototype.negate = function () {
  536. return new Vector3(-this.x, -this.y, -this.z);
  537. };
  538. Vector3.prototype.scaleInPlace = function (scale) {
  539. this.x *= scale;
  540. this.y *= scale;
  541. this.z *= scale;
  542. return this;
  543. };
  544. Vector3.prototype.scale = function (scale) {
  545. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  546. };
  547. Vector3.prototype.scaleToRef = function (scale, result) {
  548. result.x = this.x * scale;
  549. result.y = this.y * scale;
  550. result.z = this.z * scale;
  551. };
  552. Vector3.prototype.equals = function (otherVector) {
  553. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  554. };
  555. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  556. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  557. 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);
  558. };
  559. Vector3.prototype.equalsToFloats = function (x, y, z) {
  560. return this.x === x && this.y === y && this.z === z;
  561. };
  562. Vector3.prototype.multiplyInPlace = function (otherVector) {
  563. this.x *= otherVector.x;
  564. this.y *= otherVector.y;
  565. this.z *= otherVector.z;
  566. return this;
  567. };
  568. Vector3.prototype.multiply = function (otherVector) {
  569. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  570. };
  571. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  572. result.x = this.x * otherVector.x;
  573. result.y = this.y * otherVector.y;
  574. result.z = this.z * otherVector.z;
  575. return this;
  576. };
  577. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  578. return new Vector3(this.x * x, this.y * y, this.z * z);
  579. };
  580. Vector3.prototype.divide = function (otherVector) {
  581. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  582. };
  583. Vector3.prototype.divideToRef = function (otherVector, result) {
  584. result.x = this.x / otherVector.x;
  585. result.y = this.y / otherVector.y;
  586. result.z = this.z / otherVector.z;
  587. return this;
  588. };
  589. Vector3.prototype.MinimizeInPlace = function (other) {
  590. if (other.x < this.x)
  591. this.x = other.x;
  592. if (other.y < this.y)
  593. this.y = other.y;
  594. if (other.z < this.z)
  595. this.z = other.z;
  596. return this;
  597. };
  598. Vector3.prototype.MaximizeInPlace = function (other) {
  599. if (other.x > this.x)
  600. this.x = other.x;
  601. if (other.y > this.y)
  602. this.y = other.y;
  603. if (other.z > this.z)
  604. this.z = other.z;
  605. return this;
  606. };
  607. // Properties
  608. Vector3.prototype.length = function () {
  609. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  610. };
  611. Vector3.prototype.lengthSquared = function () {
  612. return (this.x * this.x + this.y * this.y + this.z * this.z);
  613. };
  614. // Methods
  615. Vector3.prototype.normalize = function () {
  616. var len = this.length();
  617. if (len === 0 || len === 1.0)
  618. return this;
  619. var num = 1.0 / len;
  620. this.x *= num;
  621. this.y *= num;
  622. this.z *= num;
  623. return this;
  624. };
  625. Vector3.prototype.clone = function () {
  626. return new Vector3(this.x, this.y, this.z);
  627. };
  628. Vector3.prototype.copyFrom = function (source) {
  629. this.x = source.x;
  630. this.y = source.y;
  631. this.z = source.z;
  632. return this;
  633. };
  634. Vector3.prototype.copyFromFloats = function (x, y, z) {
  635. this.x = x;
  636. this.y = y;
  637. this.z = z;
  638. return this;
  639. };
  640. // Statics
  641. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  642. var d0 = Vector3.Dot(vector0, axis) - size;
  643. var d1 = Vector3.Dot(vector1, axis) - size;
  644. var s = d0 / (d0 - d1);
  645. return s;
  646. };
  647. Vector3.FromArray = function (array, offset) {
  648. if (!offset) {
  649. offset = 0;
  650. }
  651. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  652. };
  653. Vector3.FromFloatArray = function (array, offset) {
  654. if (!offset) {
  655. offset = 0;
  656. }
  657. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  658. };
  659. Vector3.FromArrayToRef = function (array, offset, result) {
  660. result.x = array[offset];
  661. result.y = array[offset + 1];
  662. result.z = array[offset + 2];
  663. };
  664. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  665. result.x = array[offset];
  666. result.y = array[offset + 1];
  667. result.z = array[offset + 2];
  668. };
  669. Vector3.FromFloatsToRef = function (x, y, z, result) {
  670. result.x = x;
  671. result.y = y;
  672. result.z = z;
  673. };
  674. Vector3.Zero = function () {
  675. return new Vector3(0, 0, 0);
  676. };
  677. Vector3.Up = function () {
  678. return new Vector3(0, 1.0, 0);
  679. };
  680. Vector3.TransformCoordinates = function (vector, transformation) {
  681. var result = Vector3.Zero();
  682. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  683. return result;
  684. };
  685. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  686. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  687. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  688. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  689. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  690. result.x = x / w;
  691. result.y = y / w;
  692. result.z = z / w;
  693. };
  694. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  695. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  696. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  697. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  698. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  699. result.x = rx / rw;
  700. result.y = ry / rw;
  701. result.z = rz / rw;
  702. };
  703. Vector3.TransformNormal = function (vector, transformation) {
  704. var result = Vector3.Zero();
  705. Vector3.TransformNormalToRef(vector, transformation, result);
  706. return result;
  707. };
  708. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  709. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  710. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  711. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  712. };
  713. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  714. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  715. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  716. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  717. };
  718. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  719. var squared = amount * amount;
  720. var cubed = amount * squared;
  721. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  722. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  723. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  724. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  725. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  726. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  727. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  728. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  729. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  730. return new Vector3(x, y, z);
  731. };
  732. Vector3.Clamp = function (value, min, max) {
  733. var x = value.x;
  734. x = (x > max.x) ? max.x : x;
  735. x = (x < min.x) ? min.x : x;
  736. var y = value.y;
  737. y = (y > max.y) ? max.y : y;
  738. y = (y < min.y) ? min.y : y;
  739. var z = value.z;
  740. z = (z > max.z) ? max.z : z;
  741. z = (z < min.z) ? min.z : z;
  742. return new Vector3(x, y, z);
  743. };
  744. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  745. var squared = amount * amount;
  746. var cubed = amount * squared;
  747. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  748. var part2 = (-2.0 * cubed) + (3.0 * squared);
  749. var part3 = (cubed - (2.0 * squared)) + amount;
  750. var part4 = cubed - squared;
  751. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  752. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  753. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  754. return new Vector3(x, y, z);
  755. };
  756. Vector3.Lerp = function (start, end, amount) {
  757. var x = start.x + ((end.x - start.x) * amount);
  758. var y = start.y + ((end.y - start.y) * amount);
  759. var z = start.z + ((end.z - start.z) * amount);
  760. return new Vector3(x, y, z);
  761. };
  762. Vector3.Dot = function (left, right) {
  763. return (left.x * right.x + left.y * right.y + left.z * right.z);
  764. };
  765. Vector3.Cross = function (left, right) {
  766. var result = Vector3.Zero();
  767. Vector3.CrossToRef(left, right, result);
  768. return result;
  769. };
  770. Vector3.CrossToRef = function (left, right, result) {
  771. result.x = left.y * right.z - left.z * right.y;
  772. result.y = left.z * right.x - left.x * right.z;
  773. result.z = left.x * right.y - left.y * right.x;
  774. };
  775. Vector3.Normalize = function (vector) {
  776. var result = Vector3.Zero();
  777. Vector3.NormalizeToRef(vector, result);
  778. return result;
  779. };
  780. Vector3.NormalizeToRef = function (vector, result) {
  781. result.copyFrom(vector);
  782. result.normalize();
  783. };
  784. Vector3.Project = function (vector, world, transform, viewport) {
  785. var cw = viewport.width;
  786. var ch = viewport.height;
  787. var cx = viewport.x;
  788. var cy = viewport.y;
  789. 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);
  790. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  791. return Vector3.TransformCoordinates(vector, finalMatrix);
  792. };
  793. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  794. var matrix = world.multiply(transform);
  795. matrix.invert();
  796. source.x = source.x / viewportWidth * 2 - 1;
  797. source.y = -(source.y / viewportHeight * 2 - 1);
  798. var vector = Vector3.TransformCoordinates(source, matrix);
  799. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  800. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  801. vector = vector.scale(1.0 / num);
  802. }
  803. return vector;
  804. };
  805. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  806. var matrix = world.multiply(view).multiply(projection);
  807. matrix.invert();
  808. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  809. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  810. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  811. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  812. vector = vector.scale(1.0 / num);
  813. }
  814. return vector;
  815. };
  816. Vector3.Minimize = function (left, right) {
  817. var min = left.clone();
  818. min.MinimizeInPlace(right);
  819. return min;
  820. };
  821. Vector3.Maximize = function (left, right) {
  822. var max = left.clone();
  823. max.MaximizeInPlace(right);
  824. return max;
  825. };
  826. Vector3.Distance = function (value1, value2) {
  827. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  828. };
  829. Vector3.DistanceSquared = function (value1, value2) {
  830. var x = value1.x - value2.x;
  831. var y = value1.y - value2.y;
  832. var z = value1.z - value2.z;
  833. return (x * x) + (y * y) + (z * z);
  834. };
  835. Vector3.Center = function (value1, value2) {
  836. var center = value1.add(value2);
  837. center.scaleInPlace(0.5);
  838. return center;
  839. };
  840. /**
  841. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  842. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  843. * to something in order to rotate it from its local system to the given target system.
  844. */
  845. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  846. var rotation = Vector3.Zero();
  847. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  848. return rotation;
  849. };
  850. /**
  851. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  852. */
  853. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  854. var u = Vector3.Normalize(axis1);
  855. var w = Vector3.Normalize(axis3);
  856. // world axis
  857. var X = Axis.X;
  858. var Y = Axis.Y;
  859. // equation unknowns and vars
  860. var yaw = 0.0;
  861. var pitch = 0.0;
  862. var roll = 0.0;
  863. var x = 0.0;
  864. var y = 0.0;
  865. var z = 0.0;
  866. var t = 0.0;
  867. var sign = -1.0;
  868. var nbRevert = 0;
  869. var cross;
  870. var dot = 0.0;
  871. // step 1 : rotation around w
  872. // Rv3(u) = u1, and u1 belongs to plane xOz
  873. // Rv3(w) = w1 = w invariant
  874. var u1;
  875. var v1;
  876. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  877. z = 1.0;
  878. }
  879. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  880. x = 1.0;
  881. }
  882. else {
  883. t = w.z / w.x;
  884. x = -t * Math.sqrt(1 / (1 + t * t));
  885. z = Math.sqrt(1 / (1 + t * t));
  886. }
  887. u1 = new Vector3(x, y, z);
  888. u1.normalize();
  889. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  890. v1.normalize();
  891. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  892. cross.normalize();
  893. if (Vector3.Dot(w, cross) < 0) {
  894. sign = 1.0;
  895. }
  896. dot = Vector3.Dot(u, u1);
  897. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  898. roll = Math.acos(dot) * sign;
  899. if (Vector3.Dot(u1, X) < 0) {
  900. roll = Math.PI + roll;
  901. u1 = u1.scaleInPlace(-1);
  902. v1 = v1.scaleInPlace(-1);
  903. nbRevert++;
  904. }
  905. // step 2 : rotate around u1
  906. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  907. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  908. var w2;
  909. var v2;
  910. x = 0.0;
  911. y = 0.0;
  912. z = 0.0;
  913. sign = -1;
  914. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  915. x = 1.0;
  916. }
  917. else {
  918. t = u1.z / u1.x;
  919. x = -t * Math.sqrt(1 / (1 + t * t));
  920. z = Math.sqrt(1 / (1 + t * t));
  921. }
  922. w2 = new Vector3(x, y, z);
  923. w2.normalize();
  924. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  925. v2.normalize();
  926. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  927. cross.normalize();
  928. if (Vector3.Dot(u1, cross) < 0) {
  929. sign = 1.0;
  930. }
  931. dot = Vector3.Dot(w, w2);
  932. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  933. pitch = Math.acos(dot) * sign;
  934. if (Vector3.Dot(v2, Y) < 0) {
  935. pitch = Math.PI + pitch;
  936. v2 = v2.scaleInPlace(-1);
  937. w2 = w2.scaleInPlace(-1);
  938. nbRevert++;
  939. }
  940. // step 3 : rotate around v2
  941. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  942. sign = -1;
  943. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(cross, Y) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u1, X);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  951. if (dot < 0 && nbRevert < 2) {
  952. yaw = Math.PI + yaw;
  953. }
  954. ref.x = pitch;
  955. ref.y = yaw;
  956. ref.z = roll;
  957. };
  958. return Vector3;
  959. })();
  960. BABYLON.Vector3 = Vector3;
  961. //Vector4 class created for EulerAngle class conversion to Quaternion
  962. var Vector4 = (function () {
  963. function Vector4(x, y, z, w) {
  964. this.x = x;
  965. this.y = y;
  966. this.z = z;
  967. this.w = w;
  968. }
  969. Vector4.prototype.toString = function () {
  970. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  971. };
  972. // Operators
  973. Vector4.prototype.asArray = function () {
  974. var result = [];
  975. this.toArray(result, 0);
  976. return result;
  977. };
  978. Vector4.prototype.toArray = function (array, index) {
  979. if (index === undefined) {
  980. index = 0;
  981. }
  982. array[index] = this.x;
  983. array[index + 1] = this.y;
  984. array[index + 2] = this.z;
  985. array[index + 3] = this.w;
  986. return this;
  987. };
  988. Vector4.prototype.addInPlace = function (otherVector) {
  989. this.x += otherVector.x;
  990. this.y += otherVector.y;
  991. this.z += otherVector.z;
  992. this.w += otherVector.w;
  993. return this;
  994. };
  995. Vector4.prototype.add = function (otherVector) {
  996. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  997. };
  998. Vector4.prototype.addToRef = function (otherVector, result) {
  999. result.x = this.x + otherVector.x;
  1000. result.y = this.y + otherVector.y;
  1001. result.z = this.z + otherVector.z;
  1002. result.w = this.w + otherVector.w;
  1003. return this;
  1004. };
  1005. Vector4.prototype.subtractInPlace = function (otherVector) {
  1006. this.x -= otherVector.x;
  1007. this.y -= otherVector.y;
  1008. this.z -= otherVector.z;
  1009. this.w -= otherVector.w;
  1010. return this;
  1011. };
  1012. Vector4.prototype.subtract = function (otherVector) {
  1013. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1014. };
  1015. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1016. result.x = this.x - otherVector.x;
  1017. result.y = this.y - otherVector.y;
  1018. result.z = this.z - otherVector.z;
  1019. result.w = this.w - otherVector.w;
  1020. return this;
  1021. };
  1022. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1023. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1024. };
  1025. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1026. result.x = this.x - x;
  1027. result.y = this.y - y;
  1028. result.z = this.z - z;
  1029. result.w = this.w - w;
  1030. return this;
  1031. };
  1032. Vector4.prototype.negate = function () {
  1033. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1034. };
  1035. Vector4.prototype.scaleInPlace = function (scale) {
  1036. this.x *= scale;
  1037. this.y *= scale;
  1038. this.z *= scale;
  1039. this.w *= scale;
  1040. return this;
  1041. };
  1042. Vector4.prototype.scale = function (scale) {
  1043. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1044. };
  1045. Vector4.prototype.scaleToRef = function (scale, result) {
  1046. result.x = this.x * scale;
  1047. result.y = this.y * scale;
  1048. result.z = this.z * scale;
  1049. result.w = this.w * scale;
  1050. };
  1051. Vector4.prototype.equals = function (otherVector) {
  1052. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1053. };
  1054. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1055. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1056. return otherVector
  1057. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1058. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1059. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1060. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1061. };
  1062. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1063. return this.x === x && this.y === y && this.z === z && this.w === w;
  1064. };
  1065. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1066. this.x *= otherVector.x;
  1067. this.y *= otherVector.y;
  1068. this.z *= otherVector.z;
  1069. this.w *= otherVector.w;
  1070. return this;
  1071. };
  1072. Vector4.prototype.multiply = function (otherVector) {
  1073. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1074. };
  1075. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1076. result.x = this.x * otherVector.x;
  1077. result.y = this.y * otherVector.y;
  1078. result.z = this.z * otherVector.z;
  1079. result.w = this.w * otherVector.w;
  1080. return this;
  1081. };
  1082. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1083. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1084. };
  1085. Vector4.prototype.divide = function (otherVector) {
  1086. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1087. };
  1088. Vector4.prototype.divideToRef = function (otherVector, result) {
  1089. result.x = this.x / otherVector.x;
  1090. result.y = this.y / otherVector.y;
  1091. result.z = this.z / otherVector.z;
  1092. result.w = this.w / otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.MinimizeInPlace = function (other) {
  1096. if (other.x < this.x)
  1097. this.x = other.x;
  1098. if (other.y < this.y)
  1099. this.y = other.y;
  1100. if (other.z < this.z)
  1101. this.z = other.z;
  1102. if (other.w < this.w)
  1103. this.w = other.w;
  1104. return this;
  1105. };
  1106. Vector4.prototype.MaximizeInPlace = function (other) {
  1107. if (other.x > this.x)
  1108. this.x = other.x;
  1109. if (other.y > this.y)
  1110. this.y = other.y;
  1111. if (other.z > this.z)
  1112. this.z = other.z;
  1113. if (other.w > this.w)
  1114. this.w = other.w;
  1115. return this;
  1116. };
  1117. // Properties
  1118. Vector4.prototype.length = function () {
  1119. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1120. };
  1121. Vector4.prototype.lengthSquared = function () {
  1122. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1123. };
  1124. // Methods
  1125. Vector4.prototype.normalize = function () {
  1126. var len = this.length();
  1127. if (len === 0)
  1128. return this;
  1129. var num = 1.0 / len;
  1130. this.x *= num;
  1131. this.y *= num;
  1132. this.z *= num;
  1133. this.w *= num;
  1134. return this;
  1135. };
  1136. Vector4.prototype.clone = function () {
  1137. return new Vector4(this.x, this.y, this.z, this.w);
  1138. };
  1139. Vector4.prototype.copyFrom = function (source) {
  1140. this.x = source.x;
  1141. this.y = source.y;
  1142. this.z = source.z;
  1143. this.w = source.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1147. this.x = x;
  1148. this.y = y;
  1149. this.z = z;
  1150. this.w = w;
  1151. return this;
  1152. };
  1153. // Statics
  1154. Vector4.FromArray = function (array, offset) {
  1155. if (!offset) {
  1156. offset = 0;
  1157. }
  1158. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1159. };
  1160. Vector4.FromArrayToRef = function (array, offset, result) {
  1161. result.x = array[offset];
  1162. result.y = array[offset + 1];
  1163. result.z = array[offset + 2];
  1164. result.w = array[offset + 3];
  1165. };
  1166. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1167. result.x = array[offset];
  1168. result.y = array[offset + 1];
  1169. result.z = array[offset + 2];
  1170. result.w = array[offset + 3];
  1171. };
  1172. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1173. result.x = x;
  1174. result.y = y;
  1175. result.z = z;
  1176. result.w = w;
  1177. };
  1178. Vector4.Zero = function () {
  1179. return new Vector4(0, 0, 0, 0);
  1180. };
  1181. Vector4.Normalize = function (vector) {
  1182. var result = Vector4.Zero();
  1183. Vector4.NormalizeToRef(vector, result);
  1184. return result;
  1185. };
  1186. Vector4.NormalizeToRef = function (vector, result) {
  1187. result.copyFrom(vector);
  1188. result.normalize();
  1189. };
  1190. Vector4.Minimize = function (left, right) {
  1191. var min = left.clone();
  1192. min.MinimizeInPlace(right);
  1193. return min;
  1194. };
  1195. Vector4.Maximize = function (left, right) {
  1196. var max = left.clone();
  1197. max.MaximizeInPlace(right);
  1198. return max;
  1199. };
  1200. Vector4.Distance = function (value1, value2) {
  1201. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1202. };
  1203. Vector4.DistanceSquared = function (value1, value2) {
  1204. var x = value1.x - value2.x;
  1205. var y = value1.y - value2.y;
  1206. var z = value1.z - value2.z;
  1207. var w = value1.w - value2.w;
  1208. return (x * x) + (y * y) + (z * z) + (w * w);
  1209. };
  1210. Vector4.Center = function (value1, value2) {
  1211. var center = value1.add(value2);
  1212. center.scaleInPlace(0.5);
  1213. return center;
  1214. };
  1215. return Vector4;
  1216. })();
  1217. BABYLON.Vector4 = Vector4;
  1218. var Quaternion = (function () {
  1219. function Quaternion(x, y, z, w) {
  1220. if (x === void 0) { x = 0; }
  1221. if (y === void 0) { y = 0; }
  1222. if (z === void 0) { z = 0; }
  1223. if (w === void 0) { w = 1; }
  1224. this.x = x;
  1225. this.y = y;
  1226. this.z = z;
  1227. this.w = w;
  1228. }
  1229. Quaternion.prototype.toString = function () {
  1230. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1231. };
  1232. Quaternion.prototype.asArray = function () {
  1233. return [this.x, this.y, this.z, this.w];
  1234. };
  1235. Quaternion.prototype.equals = function (otherQuaternion) {
  1236. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1237. };
  1238. Quaternion.prototype.clone = function () {
  1239. return new Quaternion(this.x, this.y, this.z, this.w);
  1240. };
  1241. Quaternion.prototype.copyFrom = function (other) {
  1242. this.x = other.x;
  1243. this.y = other.y;
  1244. this.z = other.z;
  1245. this.w = other.w;
  1246. return this;
  1247. };
  1248. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1249. this.x = x;
  1250. this.y = y;
  1251. this.z = z;
  1252. this.w = w;
  1253. return this;
  1254. };
  1255. Quaternion.prototype.add = function (other) {
  1256. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1257. };
  1258. Quaternion.prototype.subtract = function (other) {
  1259. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1260. };
  1261. Quaternion.prototype.scale = function (value) {
  1262. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1263. };
  1264. Quaternion.prototype.multiply = function (q1) {
  1265. var result = new Quaternion(0, 0, 0, 1.0);
  1266. this.multiplyToRef(q1, result);
  1267. return result;
  1268. };
  1269. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1270. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1271. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1272. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1273. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1274. result.copyFromFloats(x, y, z, w);
  1275. return this;
  1276. };
  1277. Quaternion.prototype.multiplyInPlace = function (q1) {
  1278. this.multiplyToRef(q1, this);
  1279. return this;
  1280. };
  1281. Quaternion.prototype.length = function () {
  1282. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1283. };
  1284. Quaternion.prototype.normalize = function () {
  1285. var length = 1.0 / this.length();
  1286. this.x *= length;
  1287. this.y *= length;
  1288. this.z *= length;
  1289. this.w *= length;
  1290. return this;
  1291. };
  1292. Quaternion.prototype.toEulerAngles = function () {
  1293. var result = Vector3.Zero();
  1294. this.toEulerAnglesToRef(result);
  1295. return result;
  1296. };
  1297. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1298. //result is an EulerAngles in the in the z-x-z convention
  1299. var qx = this.x;
  1300. var qy = this.y;
  1301. var qz = this.z;
  1302. var qw = this.w;
  1303. var qxy = qx * qy;
  1304. var qxz = qx * qz;
  1305. var qwy = qw * qy;
  1306. var qwz = qw * qz;
  1307. var qwx = qw * qx;
  1308. var qyz = qy * qz;
  1309. var sqx = qx * qx;
  1310. var sqy = qy * qy;
  1311. var determinant = sqx + sqy;
  1312. if (determinant !== 0.000 && determinant !== 1.000) {
  1313. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1314. result.y = Math.acos(1 - 2 * determinant);
  1315. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1316. }
  1317. else {
  1318. if (determinant === 0.0) {
  1319. result.x = 0.0;
  1320. result.y = 0.0;
  1321. 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)
  1322. }
  1323. else {
  1324. 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)
  1325. result.y = Math.PI;
  1326. result.z = 0.0;
  1327. }
  1328. }
  1329. return this;
  1330. };
  1331. Quaternion.prototype.toRotationMatrix = function (result) {
  1332. var xx = this.x * this.x;
  1333. var yy = this.y * this.y;
  1334. var zz = this.z * this.z;
  1335. var xy = this.x * this.y;
  1336. var zw = this.z * this.w;
  1337. var zx = this.z * this.x;
  1338. var yw = this.y * this.w;
  1339. var yz = this.y * this.z;
  1340. var xw = this.x * this.w;
  1341. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1342. result.m[1] = 2.0 * (xy + zw);
  1343. result.m[2] = 2.0 * (zx - yw);
  1344. result.m[3] = 0;
  1345. result.m[4] = 2.0 * (xy - zw);
  1346. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1347. result.m[6] = 2.0 * (yz + xw);
  1348. result.m[7] = 0;
  1349. result.m[8] = 2.0 * (zx + yw);
  1350. result.m[9] = 2.0 * (yz - xw);
  1351. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1352. result.m[11] = 0;
  1353. result.m[12] = 0;
  1354. result.m[13] = 0;
  1355. result.m[14] = 0;
  1356. result.m[15] = 1.0;
  1357. return this;
  1358. };
  1359. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1360. Quaternion.FromRotationMatrixToRef(matrix, this);
  1361. return this;
  1362. };
  1363. // Statics
  1364. Quaternion.FromRotationMatrix = function (matrix) {
  1365. var result = new Quaternion();
  1366. Quaternion.FromRotationMatrixToRef(matrix, result);
  1367. return result;
  1368. };
  1369. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1370. var data = matrix.m;
  1371. var m11 = data[0], m12 = data[4], m13 = data[8];
  1372. var m21 = data[1], m22 = data[5], m23 = data[9];
  1373. var m31 = data[2], m32 = data[6], m33 = data[10];
  1374. var trace = m11 + m22 + m33;
  1375. var s;
  1376. if (trace > 0) {
  1377. s = 0.5 / Math.sqrt(trace + 1.0);
  1378. result.w = 0.25 / s;
  1379. result.x = (m32 - m23) * s;
  1380. result.y = (m13 - m31) * s;
  1381. result.z = (m21 - m12) * s;
  1382. }
  1383. else if (m11 > m22 && m11 > m33) {
  1384. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1385. result.w = (m32 - m23) / s;
  1386. result.x = 0.25 * s;
  1387. result.y = (m12 + m21) / s;
  1388. result.z = (m13 + m31) / s;
  1389. }
  1390. else if (m22 > m33) {
  1391. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1392. result.w = (m13 - m31) / s;
  1393. result.x = (m12 + m21) / s;
  1394. result.y = 0.25 * s;
  1395. result.z = (m23 + m32) / s;
  1396. }
  1397. else {
  1398. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1399. result.w = (m21 - m12) / s;
  1400. result.x = (m13 + m31) / s;
  1401. result.y = (m23 + m32) / s;
  1402. result.z = 0.25 * s;
  1403. }
  1404. };
  1405. Quaternion.Inverse = function (q) {
  1406. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1407. };
  1408. Quaternion.Identity = function () {
  1409. return new Quaternion(0, 0, 0, 1);
  1410. };
  1411. Quaternion.RotationAxis = function (axis, angle) {
  1412. var result = new Quaternion();
  1413. var sin = Math.sin(angle / 2);
  1414. axis.normalize();
  1415. result.w = Math.cos(angle / 2);
  1416. result.x = axis.x * sin;
  1417. result.y = axis.y * sin;
  1418. result.z = axis.z * sin;
  1419. return result;
  1420. };
  1421. Quaternion.FromArray = function (array, offset) {
  1422. if (!offset) {
  1423. offset = 0;
  1424. }
  1425. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1426. };
  1427. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1428. var result = new Quaternion();
  1429. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1430. return result;
  1431. };
  1432. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1433. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1434. var halfRoll = roll * 0.5;
  1435. var halfPitch = pitch * 0.5;
  1436. var halfYaw = yaw * 0.5;
  1437. var sinRoll = Math.sin(halfRoll);
  1438. var cosRoll = Math.cos(halfRoll);
  1439. var sinPitch = Math.sin(halfPitch);
  1440. var cosPitch = Math.cos(halfPitch);
  1441. var sinYaw = Math.sin(halfYaw);
  1442. var cosYaw = Math.cos(halfYaw);
  1443. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1444. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1445. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1446. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1447. };
  1448. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1449. var result = new Quaternion();
  1450. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1451. return result;
  1452. };
  1453. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1454. // Produces a quaternion from Euler angles in the z-x-z orientation
  1455. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1456. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1457. var halfBeta = beta * 0.5;
  1458. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1459. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1460. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1461. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1462. };
  1463. Quaternion.Slerp = function (left, right, amount) {
  1464. var num2;
  1465. var num3;
  1466. var num = amount;
  1467. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1468. var flag = false;
  1469. if (num4 < 0) {
  1470. flag = true;
  1471. num4 = -num4;
  1472. }
  1473. if (num4 > 0.999999) {
  1474. num3 = 1 - num;
  1475. num2 = flag ? -num : num;
  1476. }
  1477. else {
  1478. var num5 = Math.acos(num4);
  1479. var num6 = (1.0 / Math.sin(num5));
  1480. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1481. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1482. }
  1483. 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));
  1484. };
  1485. return Quaternion;
  1486. })();
  1487. BABYLON.Quaternion = Quaternion;
  1488. var Matrix = (function () {
  1489. function Matrix() {
  1490. this.m = new Float32Array(16);
  1491. }
  1492. // Properties
  1493. Matrix.prototype.isIdentity = function () {
  1494. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1495. return false;
  1496. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1497. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1498. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1499. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1500. return false;
  1501. return true;
  1502. };
  1503. Matrix.prototype.determinant = function () {
  1504. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1505. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1506. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1507. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1508. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1509. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1510. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1511. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1512. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1513. };
  1514. // Methods
  1515. Matrix.prototype.toArray = function () {
  1516. return this.m;
  1517. };
  1518. Matrix.prototype.asArray = function () {
  1519. return this.toArray();
  1520. };
  1521. Matrix.prototype.invert = function () {
  1522. this.invertToRef(this);
  1523. return this;
  1524. };
  1525. Matrix.prototype.reset = function () {
  1526. for (var index = 0; index < 16; index++) {
  1527. this.m[index] = 0;
  1528. }
  1529. return this;
  1530. };
  1531. Matrix.prototype.add = function (other) {
  1532. var result = new Matrix();
  1533. this.addToRef(other, result);
  1534. return result;
  1535. };
  1536. Matrix.prototype.addToRef = function (other, result) {
  1537. for (var index = 0; index < 16; index++) {
  1538. result.m[index] = this.m[index] + other.m[index];
  1539. }
  1540. return this;
  1541. };
  1542. Matrix.prototype.addToSelf = function (other) {
  1543. for (var index = 0; index < 16; index++) {
  1544. this.m[index] += other.m[index];
  1545. }
  1546. return this;
  1547. };
  1548. Matrix.prototype.invertToRef = function (other) {
  1549. var l1 = this.m[0];
  1550. var l2 = this.m[1];
  1551. var l3 = this.m[2];
  1552. var l4 = this.m[3];
  1553. var l5 = this.m[4];
  1554. var l6 = this.m[5];
  1555. var l7 = this.m[6];
  1556. var l8 = this.m[7];
  1557. var l9 = this.m[8];
  1558. var l10 = this.m[9];
  1559. var l11 = this.m[10];
  1560. var l12 = this.m[11];
  1561. var l13 = this.m[12];
  1562. var l14 = this.m[13];
  1563. var l15 = this.m[14];
  1564. var l16 = this.m[15];
  1565. var l17 = (l11 * l16) - (l12 * l15);
  1566. var l18 = (l10 * l16) - (l12 * l14);
  1567. var l19 = (l10 * l15) - (l11 * l14);
  1568. var l20 = (l9 * l16) - (l12 * l13);
  1569. var l21 = (l9 * l15) - (l11 * l13);
  1570. var l22 = (l9 * l14) - (l10 * l13);
  1571. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1572. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1573. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1574. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1575. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1576. var l28 = (l7 * l16) - (l8 * l15);
  1577. var l29 = (l6 * l16) - (l8 * l14);
  1578. var l30 = (l6 * l15) - (l7 * l14);
  1579. var l31 = (l5 * l16) - (l8 * l13);
  1580. var l32 = (l5 * l15) - (l7 * l13);
  1581. var l33 = (l5 * l14) - (l6 * l13);
  1582. var l34 = (l7 * l12) - (l8 * l11);
  1583. var l35 = (l6 * l12) - (l8 * l10);
  1584. var l36 = (l6 * l11) - (l7 * l10);
  1585. var l37 = (l5 * l12) - (l8 * l9);
  1586. var l38 = (l5 * l11) - (l7 * l9);
  1587. var l39 = (l5 * l10) - (l6 * l9);
  1588. other.m[0] = l23 * l27;
  1589. other.m[4] = l24 * l27;
  1590. other.m[8] = l25 * l27;
  1591. other.m[12] = l26 * l27;
  1592. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1593. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1594. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1595. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1596. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1597. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1598. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1599. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1600. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1601. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1602. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1603. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1604. return this;
  1605. };
  1606. Matrix.prototype.setTranslation = function (vector3) {
  1607. this.m[12] = vector3.x;
  1608. this.m[13] = vector3.y;
  1609. this.m[14] = vector3.z;
  1610. return this;
  1611. };
  1612. Matrix.prototype.multiply = function (other) {
  1613. var result = new Matrix();
  1614. this.multiplyToRef(other, result);
  1615. return result;
  1616. };
  1617. Matrix.prototype.copyFrom = function (other) {
  1618. for (var index = 0; index < 16; index++) {
  1619. this.m[index] = other.m[index];
  1620. }
  1621. return this;
  1622. };
  1623. Matrix.prototype.copyToArray = function (array, offset) {
  1624. if (offset === void 0) { offset = 0; }
  1625. for (var index = 0; index < 16; index++) {
  1626. array[offset + index] = this.m[index];
  1627. }
  1628. return this;
  1629. };
  1630. Matrix.prototype.multiplyToRef = function (other, result) {
  1631. this.multiplyToArray(other, result.m, 0);
  1632. return this;
  1633. };
  1634. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1635. var tm0 = this.m[0];
  1636. var tm1 = this.m[1];
  1637. var tm2 = this.m[2];
  1638. var tm3 = this.m[3];
  1639. var tm4 = this.m[4];
  1640. var tm5 = this.m[5];
  1641. var tm6 = this.m[6];
  1642. var tm7 = this.m[7];
  1643. var tm8 = this.m[8];
  1644. var tm9 = this.m[9];
  1645. var tm10 = this.m[10];
  1646. var tm11 = this.m[11];
  1647. var tm12 = this.m[12];
  1648. var tm13 = this.m[13];
  1649. var tm14 = this.m[14];
  1650. var tm15 = this.m[15];
  1651. var om0 = other.m[0];
  1652. var om1 = other.m[1];
  1653. var om2 = other.m[2];
  1654. var om3 = other.m[3];
  1655. var om4 = other.m[4];
  1656. var om5 = other.m[5];
  1657. var om6 = other.m[6];
  1658. var om7 = other.m[7];
  1659. var om8 = other.m[8];
  1660. var om9 = other.m[9];
  1661. var om10 = other.m[10];
  1662. var om11 = other.m[11];
  1663. var om12 = other.m[12];
  1664. var om13 = other.m[13];
  1665. var om14 = other.m[14];
  1666. var om15 = other.m[15];
  1667. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1668. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1669. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1670. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1671. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1672. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1673. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1674. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1675. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1676. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1677. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1678. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1679. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1680. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1681. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1682. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1683. return this;
  1684. };
  1685. Matrix.prototype.equals = function (value) {
  1686. return value &&
  1687. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1688. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1689. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1690. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1691. };
  1692. Matrix.prototype.clone = function () {
  1693. 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]);
  1694. };
  1695. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1696. translation.x = this.m[12];
  1697. translation.y = this.m[13];
  1698. translation.z = this.m[14];
  1699. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1700. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1701. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1702. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1703. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1704. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1705. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1706. rotation.x = 0;
  1707. rotation.y = 0;
  1708. rotation.z = 0;
  1709. rotation.w = 1;
  1710. return false;
  1711. }
  1712. 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);
  1713. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1714. return true;
  1715. };
  1716. // Statics
  1717. Matrix.FromArray = function (array, offset) {
  1718. var result = new Matrix();
  1719. if (!offset) {
  1720. offset = 0;
  1721. }
  1722. Matrix.FromArrayToRef(array, offset, result);
  1723. return result;
  1724. };
  1725. Matrix.FromArrayToRef = function (array, offset, result) {
  1726. for (var index = 0; index < 16; index++) {
  1727. result.m[index] = array[index + offset];
  1728. }
  1729. };
  1730. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1731. for (var index = 0; index < 16; index++) {
  1732. result.m[index] = array[index + offset] * scale;
  1733. }
  1734. };
  1735. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1736. result.m[0] = initialM11;
  1737. result.m[1] = initialM12;
  1738. result.m[2] = initialM13;
  1739. result.m[3] = initialM14;
  1740. result.m[4] = initialM21;
  1741. result.m[5] = initialM22;
  1742. result.m[6] = initialM23;
  1743. result.m[7] = initialM24;
  1744. result.m[8] = initialM31;
  1745. result.m[9] = initialM32;
  1746. result.m[10] = initialM33;
  1747. result.m[11] = initialM34;
  1748. result.m[12] = initialM41;
  1749. result.m[13] = initialM42;
  1750. result.m[14] = initialM43;
  1751. result.m[15] = initialM44;
  1752. };
  1753. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1754. var result = new Matrix();
  1755. result.m[0] = initialM11;
  1756. result.m[1] = initialM12;
  1757. result.m[2] = initialM13;
  1758. result.m[3] = initialM14;
  1759. result.m[4] = initialM21;
  1760. result.m[5] = initialM22;
  1761. result.m[6] = initialM23;
  1762. result.m[7] = initialM24;
  1763. result.m[8] = initialM31;
  1764. result.m[9] = initialM32;
  1765. result.m[10] = initialM33;
  1766. result.m[11] = initialM34;
  1767. result.m[12] = initialM41;
  1768. result.m[13] = initialM42;
  1769. result.m[14] = initialM43;
  1770. result.m[15] = initialM44;
  1771. return result;
  1772. };
  1773. Matrix.Compose = function (scale, rotation, translation) {
  1774. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1775. var rotationMatrix = Matrix.Identity();
  1776. rotation.toRotationMatrix(rotationMatrix);
  1777. result = result.multiply(rotationMatrix);
  1778. result.setTranslation(translation);
  1779. return result;
  1780. };
  1781. Matrix.Identity = function () {
  1782. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1783. };
  1784. Matrix.IdentityToRef = function (result) {
  1785. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1786. };
  1787. Matrix.Zero = function () {
  1788. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1789. };
  1790. Matrix.RotationX = function (angle) {
  1791. var result = new Matrix();
  1792. Matrix.RotationXToRef(angle, result);
  1793. return result;
  1794. };
  1795. Matrix.Invert = function (source) {
  1796. var result = new Matrix();
  1797. source.invertToRef(result);
  1798. return result;
  1799. };
  1800. Matrix.RotationXToRef = function (angle, result) {
  1801. var s = Math.sin(angle);
  1802. var c = Math.cos(angle);
  1803. result.m[0] = 1.0;
  1804. result.m[15] = 1.0;
  1805. result.m[5] = c;
  1806. result.m[10] = c;
  1807. result.m[9] = -s;
  1808. result.m[6] = s;
  1809. result.m[1] = 0;
  1810. result.m[2] = 0;
  1811. result.m[3] = 0;
  1812. result.m[4] = 0;
  1813. result.m[7] = 0;
  1814. result.m[8] = 0;
  1815. result.m[11] = 0;
  1816. result.m[12] = 0;
  1817. result.m[13] = 0;
  1818. result.m[14] = 0;
  1819. };
  1820. Matrix.RotationY = function (angle) {
  1821. var result = new Matrix();
  1822. Matrix.RotationYToRef(angle, result);
  1823. return result;
  1824. };
  1825. Matrix.RotationYToRef = function (angle, result) {
  1826. var s = Math.sin(angle);
  1827. var c = Math.cos(angle);
  1828. result.m[5] = 1.0;
  1829. result.m[15] = 1.0;
  1830. result.m[0] = c;
  1831. result.m[2] = -s;
  1832. result.m[8] = s;
  1833. result.m[10] = c;
  1834. result.m[1] = 0;
  1835. result.m[3] = 0;
  1836. result.m[4] = 0;
  1837. result.m[6] = 0;
  1838. result.m[7] = 0;
  1839. result.m[9] = 0;
  1840. result.m[11] = 0;
  1841. result.m[12] = 0;
  1842. result.m[13] = 0;
  1843. result.m[14] = 0;
  1844. };
  1845. Matrix.RotationZ = function (angle) {
  1846. var result = new Matrix();
  1847. Matrix.RotationZToRef(angle, result);
  1848. return result;
  1849. };
  1850. Matrix.RotationZToRef = function (angle, result) {
  1851. var s = Math.sin(angle);
  1852. var c = Math.cos(angle);
  1853. result.m[10] = 1.0;
  1854. result.m[15] = 1.0;
  1855. result.m[0] = c;
  1856. result.m[1] = s;
  1857. result.m[4] = -s;
  1858. result.m[5] = c;
  1859. result.m[2] = 0;
  1860. result.m[3] = 0;
  1861. result.m[6] = 0;
  1862. result.m[7] = 0;
  1863. result.m[8] = 0;
  1864. result.m[9] = 0;
  1865. result.m[11] = 0;
  1866. result.m[12] = 0;
  1867. result.m[13] = 0;
  1868. result.m[14] = 0;
  1869. };
  1870. Matrix.RotationAxis = function (axis, angle) {
  1871. var result = Matrix.Zero();
  1872. Matrix.RotationAxisToRef(axis, angle, result);
  1873. return result;
  1874. };
  1875. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1876. var s = Math.sin(-angle);
  1877. var c = Math.cos(-angle);
  1878. var c1 = 1 - c;
  1879. axis.normalize();
  1880. result.m[0] = (axis.x * axis.x) * c1 + c;
  1881. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1882. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1883. result.m[3] = 0.0;
  1884. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1885. result.m[5] = (axis.y * axis.y) * c1 + c;
  1886. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1887. result.m[7] = 0.0;
  1888. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1889. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1890. result.m[10] = (axis.z * axis.z) * c1 + c;
  1891. result.m[11] = 0.0;
  1892. result.m[15] = 1.0;
  1893. };
  1894. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1895. var result = new Matrix();
  1896. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1897. return result;
  1898. };
  1899. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1900. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1901. this._tempQuaternion.toRotationMatrix(result);
  1902. };
  1903. Matrix.Scaling = function (x, y, z) {
  1904. var result = Matrix.Zero();
  1905. Matrix.ScalingToRef(x, y, z, result);
  1906. return result;
  1907. };
  1908. Matrix.ScalingToRef = function (x, y, z, result) {
  1909. result.m[0] = x;
  1910. result.m[1] = 0;
  1911. result.m[2] = 0;
  1912. result.m[3] = 0;
  1913. result.m[4] = 0;
  1914. result.m[5] = y;
  1915. result.m[6] = 0;
  1916. result.m[7] = 0;
  1917. result.m[8] = 0;
  1918. result.m[9] = 0;
  1919. result.m[10] = z;
  1920. result.m[11] = 0;
  1921. result.m[12] = 0;
  1922. result.m[13] = 0;
  1923. result.m[14] = 0;
  1924. result.m[15] = 1.0;
  1925. };
  1926. Matrix.Translation = function (x, y, z) {
  1927. var result = Matrix.Identity();
  1928. Matrix.TranslationToRef(x, y, z, result);
  1929. return result;
  1930. };
  1931. Matrix.TranslationToRef = function (x, y, z, result) {
  1932. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1933. };
  1934. Matrix.LookAtLH = function (eye, target, up) {
  1935. var result = Matrix.Zero();
  1936. Matrix.LookAtLHToRef(eye, target, up, result);
  1937. return result;
  1938. };
  1939. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1940. // Z axis
  1941. target.subtractToRef(eye, this._zAxis);
  1942. this._zAxis.normalize();
  1943. // X axis
  1944. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1945. if (this._xAxis.lengthSquared() === 0) {
  1946. this._xAxis.x = 1.0;
  1947. }
  1948. else {
  1949. this._xAxis.normalize();
  1950. }
  1951. // Y axis
  1952. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1953. this._yAxis.normalize();
  1954. // Eye angles
  1955. var ex = -Vector3.Dot(this._xAxis, eye);
  1956. var ey = -Vector3.Dot(this._yAxis, eye);
  1957. var ez = -Vector3.Dot(this._zAxis, eye);
  1958. 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);
  1959. };
  1960. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1961. var matrix = Matrix.Zero();
  1962. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1963. return matrix;
  1964. };
  1965. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1966. var hw = 2.0 / width;
  1967. var hh = 2.0 / height;
  1968. var id = 1.0 / (zfar - znear);
  1969. var nid = znear / (znear - zfar);
  1970. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1971. };
  1972. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1973. var matrix = Matrix.Zero();
  1974. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1975. return matrix;
  1976. };
  1977. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1978. result.m[0] = 2.0 / (right - left);
  1979. result.m[1] = result.m[2] = result.m[3] = 0;
  1980. result.m[5] = 2.0 / (top - bottom);
  1981. result.m[4] = result.m[6] = result.m[7] = 0;
  1982. result.m[10] = -1.0 / (znear - zfar);
  1983. result.m[8] = result.m[9] = result.m[11] = 0;
  1984. result.m[12] = (left + right) / (left - right);
  1985. result.m[13] = (top + bottom) / (bottom - top);
  1986. result.m[14] = znear / (znear - zfar);
  1987. result.m[15] = 1.0;
  1988. };
  1989. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. matrix.m[0] = (2.0 * znear) / width;
  1992. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1993. matrix.m[5] = (2.0 * znear) / height;
  1994. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1995. matrix.m[10] = -zfar / (znear - zfar);
  1996. matrix.m[8] = matrix.m[9] = 0.0;
  1997. matrix.m[11] = 1.0;
  1998. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1999. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2000. return matrix;
  2001. };
  2002. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2003. var matrix = Matrix.Zero();
  2004. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2005. return matrix;
  2006. };
  2007. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2008. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2009. var tan = 1.0 / (Math.tan(fov * 0.5));
  2010. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2011. if (v_fixed) {
  2012. result.m[0] = tan / aspect;
  2013. }
  2014. else {
  2015. result.m[0] = tan;
  2016. }
  2017. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2018. if (v_fixed) {
  2019. result.m[5] = tan;
  2020. }
  2021. else {
  2022. result.m[5] = tan * aspect;
  2023. }
  2024. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2025. result.m[8] = result.m[9] = 0.0;
  2026. result.m[10] = -zfar / (znear - zfar);
  2027. result.m[11] = 1.0;
  2028. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2029. result.m[14] = (znear * zfar) / (znear - zfar);
  2030. };
  2031. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2032. var cw = viewport.width;
  2033. var ch = viewport.height;
  2034. var cx = viewport.x;
  2035. var cy = viewport.y;
  2036. 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);
  2037. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2038. };
  2039. Matrix.GetAsMatrix2x2 = function (matrix) {
  2040. return new Float32Array([
  2041. matrix.m[0], matrix.m[1],
  2042. matrix.m[4], matrix.m[5]
  2043. ]);
  2044. };
  2045. Matrix.GetAsMatrix3x3 = function (matrix) {
  2046. return new Float32Array([
  2047. matrix.m[0], matrix.m[1], matrix.m[2],
  2048. matrix.m[4], matrix.m[5], matrix.m[6],
  2049. matrix.m[8], matrix.m[9], matrix.m[10]
  2050. ]);
  2051. };
  2052. Matrix.Transpose = function (matrix) {
  2053. var result = new Matrix();
  2054. result.m[0] = matrix.m[0];
  2055. result.m[1] = matrix.m[4];
  2056. result.m[2] = matrix.m[8];
  2057. result.m[3] = matrix.m[12];
  2058. result.m[4] = matrix.m[1];
  2059. result.m[5] = matrix.m[5];
  2060. result.m[6] = matrix.m[9];
  2061. result.m[7] = matrix.m[13];
  2062. result.m[8] = matrix.m[2];
  2063. result.m[9] = matrix.m[6];
  2064. result.m[10] = matrix.m[10];
  2065. result.m[11] = matrix.m[14];
  2066. result.m[12] = matrix.m[3];
  2067. result.m[13] = matrix.m[7];
  2068. result.m[14] = matrix.m[11];
  2069. result.m[15] = matrix.m[15];
  2070. return result;
  2071. };
  2072. Matrix.Reflection = function (plane) {
  2073. var matrix = new Matrix();
  2074. Matrix.ReflectionToRef(plane, matrix);
  2075. return matrix;
  2076. };
  2077. Matrix.ReflectionToRef = function (plane, result) {
  2078. plane.normalize();
  2079. var x = plane.normal.x;
  2080. var y = plane.normal.y;
  2081. var z = plane.normal.z;
  2082. var temp = -2 * x;
  2083. var temp2 = -2 * y;
  2084. var temp3 = -2 * z;
  2085. result.m[0] = (temp * x) + 1;
  2086. result.m[1] = temp2 * x;
  2087. result.m[2] = temp3 * x;
  2088. result.m[3] = 0.0;
  2089. result.m[4] = temp * y;
  2090. result.m[5] = (temp2 * y) + 1;
  2091. result.m[6] = temp3 * y;
  2092. result.m[7] = 0.0;
  2093. result.m[8] = temp * z;
  2094. result.m[9] = temp2 * z;
  2095. result.m[10] = (temp3 * z) + 1;
  2096. result.m[11] = 0.0;
  2097. result.m[12] = temp * plane.d;
  2098. result.m[13] = temp2 * plane.d;
  2099. result.m[14] = temp3 * plane.d;
  2100. result.m[15] = 1.0;
  2101. };
  2102. Matrix._tempQuaternion = new Quaternion();
  2103. Matrix._xAxis = Vector3.Zero();
  2104. Matrix._yAxis = Vector3.Zero();
  2105. Matrix._zAxis = Vector3.Zero();
  2106. return Matrix;
  2107. })();
  2108. BABYLON.Matrix = Matrix;
  2109. var Plane = (function () {
  2110. function Plane(a, b, c, d) {
  2111. this.normal = new Vector3(a, b, c);
  2112. this.d = d;
  2113. }
  2114. Plane.prototype.asArray = function () {
  2115. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2116. };
  2117. // Methods
  2118. Plane.prototype.clone = function () {
  2119. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2120. };
  2121. Plane.prototype.normalize = function () {
  2122. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2123. var magnitude = 0;
  2124. if (norm !== 0) {
  2125. magnitude = 1.0 / norm;
  2126. }
  2127. this.normal.x *= magnitude;
  2128. this.normal.y *= magnitude;
  2129. this.normal.z *= magnitude;
  2130. this.d *= magnitude;
  2131. return this;
  2132. };
  2133. Plane.prototype.transform = function (transformation) {
  2134. var transposedMatrix = Matrix.Transpose(transformation);
  2135. var x = this.normal.x;
  2136. var y = this.normal.y;
  2137. var z = this.normal.z;
  2138. var d = this.d;
  2139. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2140. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2141. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2142. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2143. return new Plane(normalX, normalY, normalZ, finalD);
  2144. };
  2145. Plane.prototype.dotCoordinate = function (point) {
  2146. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2147. };
  2148. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2149. var x1 = point2.x - point1.x;
  2150. var y1 = point2.y - point1.y;
  2151. var z1 = point2.z - point1.z;
  2152. var x2 = point3.x - point1.x;
  2153. var y2 = point3.y - point1.y;
  2154. var z2 = point3.z - point1.z;
  2155. var yz = (y1 * z2) - (z1 * y2);
  2156. var xz = (z1 * x2) - (x1 * z2);
  2157. var xy = (x1 * y2) - (y1 * x2);
  2158. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2159. var invPyth;
  2160. if (pyth !== 0) {
  2161. invPyth = 1.0 / pyth;
  2162. }
  2163. else {
  2164. invPyth = 0;
  2165. }
  2166. this.normal.x = yz * invPyth;
  2167. this.normal.y = xz * invPyth;
  2168. this.normal.z = xy * invPyth;
  2169. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2170. return this;
  2171. };
  2172. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2173. var dot = Vector3.Dot(this.normal, direction);
  2174. return (dot <= epsilon);
  2175. };
  2176. Plane.prototype.signedDistanceTo = function (point) {
  2177. return Vector3.Dot(point, this.normal) + this.d;
  2178. };
  2179. // Statics
  2180. Plane.FromArray = function (array) {
  2181. return new Plane(array[0], array[1], array[2], array[3]);
  2182. };
  2183. Plane.FromPoints = function (point1, point2, point3) {
  2184. var result = new Plane(0, 0, 0, 0);
  2185. result.copyFromPoints(point1, point2, point3);
  2186. return result;
  2187. };
  2188. Plane.FromPositionAndNormal = function (origin, normal) {
  2189. var result = new Plane(0, 0, 0, 0);
  2190. normal.normalize();
  2191. result.normal = normal;
  2192. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2193. return result;
  2194. };
  2195. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2196. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2197. return Vector3.Dot(point, normal) + d;
  2198. };
  2199. return Plane;
  2200. })();
  2201. BABYLON.Plane = Plane;
  2202. var Viewport = (function () {
  2203. function Viewport(x, y, width, height) {
  2204. this.x = x;
  2205. this.y = y;
  2206. this.width = width;
  2207. this.height = height;
  2208. }
  2209. Viewport.prototype.toGlobal = function (engine) {
  2210. var width = engine.getRenderWidth();
  2211. var height = engine.getRenderHeight();
  2212. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2213. };
  2214. return Viewport;
  2215. })();
  2216. BABYLON.Viewport = Viewport;
  2217. var Frustum = (function () {
  2218. function Frustum() {
  2219. }
  2220. Frustum.GetPlanes = function (transform) {
  2221. var frustumPlanes = [];
  2222. for (var index = 0; index < 6; index++) {
  2223. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2224. }
  2225. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2226. return frustumPlanes;
  2227. };
  2228. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2229. // Near
  2230. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2231. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2232. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2233. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2234. frustumPlanes[0].normalize();
  2235. // Far
  2236. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2237. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2238. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2239. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2240. frustumPlanes[1].normalize();
  2241. // Left
  2242. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2243. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2244. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2245. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2246. frustumPlanes[2].normalize();
  2247. // Right
  2248. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2249. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2250. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2251. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2252. frustumPlanes[3].normalize();
  2253. // Top
  2254. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2255. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2256. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2257. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2258. frustumPlanes[4].normalize();
  2259. // Bottom
  2260. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2261. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2262. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2263. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2264. frustumPlanes[5].normalize();
  2265. };
  2266. return Frustum;
  2267. })();
  2268. BABYLON.Frustum = Frustum;
  2269. var Ray = (function () {
  2270. function Ray(origin, direction, length) {
  2271. if (length === void 0) { length = Number.MAX_VALUE; }
  2272. this.origin = origin;
  2273. this.direction = direction;
  2274. this.length = length;
  2275. }
  2276. // Methods
  2277. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2278. var d = 0.0;
  2279. var maxValue = Number.MAX_VALUE;
  2280. var inv;
  2281. var min;
  2282. var max;
  2283. var temp;
  2284. if (Math.abs(this.direction.x) < 0.0000001) {
  2285. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2286. return false;
  2287. }
  2288. }
  2289. else {
  2290. inv = 1.0 / this.direction.x;
  2291. min = (minimum.x - this.origin.x) * inv;
  2292. max = (maximum.x - this.origin.x) * inv;
  2293. if (max === -Infinity) {
  2294. max = Infinity;
  2295. }
  2296. if (min > max) {
  2297. temp = min;
  2298. min = max;
  2299. max = temp;
  2300. }
  2301. d = Math.max(min, d);
  2302. maxValue = Math.min(max, maxValue);
  2303. if (d > maxValue) {
  2304. return false;
  2305. }
  2306. }
  2307. if (Math.abs(this.direction.y) < 0.0000001) {
  2308. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2309. return false;
  2310. }
  2311. }
  2312. else {
  2313. inv = 1.0 / this.direction.y;
  2314. min = (minimum.y - this.origin.y) * inv;
  2315. max = (maximum.y - this.origin.y) * inv;
  2316. if (max === -Infinity) {
  2317. max = Infinity;
  2318. }
  2319. if (min > max) {
  2320. temp = min;
  2321. min = max;
  2322. max = temp;
  2323. }
  2324. d = Math.max(min, d);
  2325. maxValue = Math.min(max, maxValue);
  2326. if (d > maxValue) {
  2327. return false;
  2328. }
  2329. }
  2330. if (Math.abs(this.direction.z) < 0.0000001) {
  2331. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2332. return false;
  2333. }
  2334. }
  2335. else {
  2336. inv = 1.0 / this.direction.z;
  2337. min = (minimum.z - this.origin.z) * inv;
  2338. max = (maximum.z - this.origin.z) * inv;
  2339. if (max === -Infinity) {
  2340. max = Infinity;
  2341. }
  2342. if (min > max) {
  2343. temp = min;
  2344. min = max;
  2345. max = temp;
  2346. }
  2347. d = Math.max(min, d);
  2348. maxValue = Math.min(max, maxValue);
  2349. if (d > maxValue) {
  2350. return false;
  2351. }
  2352. }
  2353. return true;
  2354. };
  2355. Ray.prototype.intersectsBox = function (box) {
  2356. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2357. };
  2358. Ray.prototype.intersectsSphere = function (sphere) {
  2359. var x = sphere.center.x - this.origin.x;
  2360. var y = sphere.center.y - this.origin.y;
  2361. var z = sphere.center.z - this.origin.z;
  2362. var pyth = (x * x) + (y * y) + (z * z);
  2363. var rr = sphere.radius * sphere.radius;
  2364. if (pyth <= rr) {
  2365. return true;
  2366. }
  2367. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2368. if (dot < 0.0) {
  2369. return false;
  2370. }
  2371. var temp = pyth - (dot * dot);
  2372. return temp <= rr;
  2373. };
  2374. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2375. if (!this._edge1) {
  2376. this._edge1 = Vector3.Zero();
  2377. this._edge2 = Vector3.Zero();
  2378. this._pvec = Vector3.Zero();
  2379. this._tvec = Vector3.Zero();
  2380. this._qvec = Vector3.Zero();
  2381. }
  2382. vertex1.subtractToRef(vertex0, this._edge1);
  2383. vertex2.subtractToRef(vertex0, this._edge2);
  2384. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2385. var det = Vector3.Dot(this._edge1, this._pvec);
  2386. if (det === 0) {
  2387. return null;
  2388. }
  2389. var invdet = 1 / det;
  2390. this.origin.subtractToRef(vertex0, this._tvec);
  2391. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2392. if (bu < 0 || bu > 1.0) {
  2393. return null;
  2394. }
  2395. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2396. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2397. if (bv < 0 || bu + bv > 1.0) {
  2398. return null;
  2399. }
  2400. //check if the distance is longer than the predefined length.
  2401. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2402. if (distance > this.length) {
  2403. return null;
  2404. }
  2405. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2406. };
  2407. // Statics
  2408. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2409. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2410. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2411. var direction = end.subtract(start);
  2412. direction.normalize();
  2413. return new Ray(start, direction);
  2414. };
  2415. /**
  2416. * 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
  2417. * transformed to the given world matrix.
  2418. * @param origin The origin point
  2419. * @param end The end point
  2420. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2421. */
  2422. Ray.CreateNewFromTo = function (origin, end, world) {
  2423. if (world === void 0) { world = Matrix.Identity(); }
  2424. var direction = end.subtract(origin);
  2425. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2426. direction.normalize();
  2427. return Ray.Transform(new Ray(origin, direction, length), world);
  2428. };
  2429. Ray.Transform = function (ray, matrix) {
  2430. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2431. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2432. return new Ray(newOrigin, newDirection, ray.length);
  2433. };
  2434. return Ray;
  2435. })();
  2436. BABYLON.Ray = Ray;
  2437. (function (Space) {
  2438. Space[Space["LOCAL"] = 0] = "LOCAL";
  2439. Space[Space["WORLD"] = 1] = "WORLD";
  2440. })(BABYLON.Space || (BABYLON.Space = {}));
  2441. var Space = BABYLON.Space;
  2442. var Axis = (function () {
  2443. function Axis() {
  2444. }
  2445. Axis.X = new Vector3(1, 0, 0);
  2446. Axis.Y = new Vector3(0, 1, 0);
  2447. Axis.Z = new Vector3(0, 0, 1);
  2448. return Axis;
  2449. })();
  2450. BABYLON.Axis = Axis;
  2451. ;
  2452. var BezierCurve = (function () {
  2453. function BezierCurve() {
  2454. }
  2455. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2456. // Extract X (which is equal to time here)
  2457. var f0 = 1 - 3 * x2 + 3 * x1;
  2458. var f1 = 3 * x2 - 6 * x1;
  2459. var f2 = 3 * x1;
  2460. var refinedT = t;
  2461. for (var i = 0; i < 5; i++) {
  2462. var refinedT2 = refinedT * refinedT;
  2463. var refinedT3 = refinedT2 * refinedT;
  2464. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2465. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2466. refinedT -= (x - t) * slope;
  2467. refinedT = Math.min(1, Math.max(0, refinedT));
  2468. }
  2469. // Resolve cubic bezier for the given x
  2470. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2471. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2472. Math.pow(refinedT, 3);
  2473. };
  2474. return BezierCurve;
  2475. })();
  2476. BABYLON.BezierCurve = BezierCurve;
  2477. (function (Orientation) {
  2478. Orientation[Orientation["CW"] = 0] = "CW";
  2479. Orientation[Orientation["CCW"] = 1] = "CCW";
  2480. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2481. var Orientation = BABYLON.Orientation;
  2482. var Angle = (function () {
  2483. function Angle(radians) {
  2484. var _this = this;
  2485. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2486. this.radians = function () { return _this._radians; };
  2487. this._radians = radians;
  2488. if (this._radians < 0)
  2489. this._radians += (2 * Math.PI);
  2490. }
  2491. Angle.BetweenTwoPoints = function (a, b) {
  2492. var delta = b.subtract(a);
  2493. var theta = Math.atan2(delta.y, delta.x);
  2494. return new Angle(theta);
  2495. };
  2496. Angle.FromRadians = function (radians) {
  2497. return new Angle(radians);
  2498. };
  2499. Angle.FromDegrees = function (degrees) {
  2500. return new Angle(degrees * Math.PI / 180);
  2501. };
  2502. return Angle;
  2503. })();
  2504. BABYLON.Angle = Angle;
  2505. var Arc2 = (function () {
  2506. function Arc2(startPoint, midPoint, endPoint) {
  2507. this.startPoint = startPoint;
  2508. this.midPoint = midPoint;
  2509. this.endPoint = endPoint;
  2510. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2511. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2512. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2513. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2514. 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);
  2515. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2516. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2517. var a1 = this.startAngle.degrees();
  2518. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2519. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2520. // angles correction
  2521. if (a2 - a1 > +180.0)
  2522. a2 -= 360.0;
  2523. if (a2 - a1 < -180.0)
  2524. a2 += 360.0;
  2525. if (a3 - a2 > +180.0)
  2526. a3 -= 360.0;
  2527. if (a3 - a2 < -180.0)
  2528. a3 += 360.0;
  2529. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2530. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2531. }
  2532. return Arc2;
  2533. })();
  2534. BABYLON.Arc2 = Arc2;
  2535. var PathCursor = (function () {
  2536. function PathCursor(path) {
  2537. this.path = path;
  2538. this._onchange = new Array();
  2539. this.value = 0;
  2540. this.animations = new Array();
  2541. }
  2542. PathCursor.prototype.getPoint = function () {
  2543. var point = this.path.getPointAtLengthPosition(this.value);
  2544. return new Vector3(point.x, 0, point.y);
  2545. };
  2546. PathCursor.prototype.moveAhead = function (step) {
  2547. if (step === void 0) { step = 0.002; }
  2548. this.move(step);
  2549. return this;
  2550. };
  2551. PathCursor.prototype.moveBack = function (step) {
  2552. if (step === void 0) { step = 0.002; }
  2553. this.move(-step);
  2554. return this;
  2555. };
  2556. PathCursor.prototype.move = function (step) {
  2557. if (Math.abs(step) > 1) {
  2558. throw "step size should be less than 1.";
  2559. }
  2560. this.value += step;
  2561. this.ensureLimits();
  2562. this.raiseOnChange();
  2563. return this;
  2564. };
  2565. PathCursor.prototype.ensureLimits = function () {
  2566. while (this.value > 1) {
  2567. this.value -= 1;
  2568. }
  2569. while (this.value < 0) {
  2570. this.value += 1;
  2571. }
  2572. return this;
  2573. };
  2574. // used by animation engine
  2575. PathCursor.prototype.markAsDirty = function (propertyName) {
  2576. this.ensureLimits();
  2577. this.raiseOnChange();
  2578. return this;
  2579. };
  2580. PathCursor.prototype.raiseOnChange = function () {
  2581. var _this = this;
  2582. this._onchange.forEach(function (f) { return f(_this); });
  2583. return this;
  2584. };
  2585. PathCursor.prototype.onchange = function (f) {
  2586. this._onchange.push(f);
  2587. return this;
  2588. };
  2589. return PathCursor;
  2590. })();
  2591. BABYLON.PathCursor = PathCursor;
  2592. var Path2 = (function () {
  2593. function Path2(x, y) {
  2594. this._points = new Array();
  2595. this._length = 0;
  2596. this.closed = false;
  2597. this._points.push(new Vector2(x, y));
  2598. }
  2599. Path2.prototype.addLineTo = function (x, y) {
  2600. if (closed) {
  2601. BABYLON.Tools.Error("cannot add lines to closed paths");
  2602. return this;
  2603. }
  2604. var newPoint = new Vector2(x, y);
  2605. var previousPoint = this._points[this._points.length - 1];
  2606. this._points.push(newPoint);
  2607. this._length += newPoint.subtract(previousPoint).length();
  2608. return this;
  2609. };
  2610. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2611. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2612. if (closed) {
  2613. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2614. return this;
  2615. }
  2616. var startPoint = this._points[this._points.length - 1];
  2617. var midPoint = new Vector2(midX, midY);
  2618. var endPoint = new Vector2(endX, endY);
  2619. var arc = new Arc2(startPoint, midPoint, endPoint);
  2620. var increment = arc.angle.radians() / numberOfSegments;
  2621. if (arc.orientation === Orientation.CW)
  2622. increment *= -1;
  2623. var currentAngle = arc.startAngle.radians() + increment;
  2624. for (var i = 0; i < numberOfSegments; i++) {
  2625. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2626. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2627. this.addLineTo(x, y);
  2628. currentAngle += increment;
  2629. }
  2630. return this;
  2631. };
  2632. Path2.prototype.close = function () {
  2633. this.closed = true;
  2634. return this;
  2635. };
  2636. Path2.prototype.length = function () {
  2637. var result = this._length;
  2638. if (!this.closed) {
  2639. var lastPoint = this._points[this._points.length - 1];
  2640. var firstPoint = this._points[0];
  2641. result += (firstPoint.subtract(lastPoint).length());
  2642. }
  2643. return result;
  2644. };
  2645. Path2.prototype.getPoints = function () {
  2646. return this._points;
  2647. };
  2648. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2649. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2650. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2651. return Vector2.Zero();
  2652. }
  2653. var lengthPosition = normalizedLengthPosition * this.length();
  2654. var previousOffset = 0;
  2655. for (var i = 0; i < this._points.length; i++) {
  2656. var j = (i + 1) % this._points.length;
  2657. var a = this._points[i];
  2658. var b = this._points[j];
  2659. var bToA = b.subtract(a);
  2660. var nextOffset = (bToA.length() + previousOffset);
  2661. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2662. var dir = bToA.normalize();
  2663. var localOffset = lengthPosition - previousOffset;
  2664. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2665. }
  2666. previousOffset = nextOffset;
  2667. }
  2668. BABYLON.Tools.Error("internal error");
  2669. return Vector2.Zero();
  2670. };
  2671. Path2.StartingAt = function (x, y) {
  2672. return new Path2(x, y);
  2673. };
  2674. return Path2;
  2675. })();
  2676. BABYLON.Path2 = Path2;
  2677. var Path3D = (function () {
  2678. /**
  2679. * new Path3D(path, normal, raw)
  2680. * path : an array of Vector3, the curve axis of the Path3D
  2681. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2682. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2683. */
  2684. function Path3D(path, firstNormal, raw) {
  2685. this.path = path;
  2686. this._curve = new Array();
  2687. this._distances = new Array();
  2688. this._tangents = new Array();
  2689. this._normals = new Array();
  2690. this._binormals = new Array();
  2691. for (var p = 0; p < path.length; p++) {
  2692. this._curve[p] = path[p].clone(); // hard copy
  2693. }
  2694. this._raw = raw || false;
  2695. this._compute(firstNormal);
  2696. }
  2697. Path3D.prototype.getCurve = function () {
  2698. return this._curve;
  2699. };
  2700. Path3D.prototype.getTangents = function () {
  2701. return this._tangents;
  2702. };
  2703. Path3D.prototype.getNormals = function () {
  2704. return this._normals;
  2705. };
  2706. Path3D.prototype.getBinormals = function () {
  2707. return this._binormals;
  2708. };
  2709. Path3D.prototype.getDistances = function () {
  2710. return this._distances;
  2711. };
  2712. Path3D.prototype.update = function (path, firstNormal) {
  2713. for (var p = 0; p < path.length; p++) {
  2714. this._curve[p].x = path[p].x;
  2715. this._curve[p].y = path[p].y;
  2716. this._curve[p].z = path[p].z;
  2717. }
  2718. this._compute(firstNormal);
  2719. return this;
  2720. };
  2721. // private function compute() : computes tangents, normals and binormals
  2722. Path3D.prototype._compute = function (firstNormal) {
  2723. var l = this._curve.length;
  2724. // first and last tangents
  2725. this._tangents[0] = this._getFirstNonNullVector(0);
  2726. if (!this._raw) {
  2727. this._tangents[0].normalize();
  2728. }
  2729. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2730. if (!this._raw) {
  2731. this._tangents[l - 1].normalize();
  2732. }
  2733. // normals and binormals at first point : arbitrary vector with _normalVector()
  2734. var tg0 = this._tangents[0];
  2735. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2736. this._normals[0] = pp0;
  2737. if (!this._raw) {
  2738. this._normals[0].normalize();
  2739. }
  2740. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2741. if (!this._raw) {
  2742. this._binormals[0].normalize();
  2743. }
  2744. this._distances[0] = 0;
  2745. // normals and binormals : next points
  2746. var prev; // previous vector (segment)
  2747. var cur; // current vector (segment)
  2748. var curTang; // current tangent
  2749. // previous normal
  2750. var prevBinor; // previous binormal
  2751. for (var i = 1; i < l; i++) {
  2752. // tangents
  2753. prev = this._getLastNonNullVector(i);
  2754. if (i < l - 1) {
  2755. cur = this._getFirstNonNullVector(i);
  2756. this._tangents[i] = prev.add(cur);
  2757. this._tangents[i].normalize();
  2758. }
  2759. this._distances[i] = this._distances[i - 1] + prev.length();
  2760. // normals and binormals
  2761. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2762. curTang = this._tangents[i];
  2763. prevBinor = this._binormals[i - 1];
  2764. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2765. if (!this._raw) {
  2766. this._normals[i].normalize();
  2767. }
  2768. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2769. if (!this._raw) {
  2770. this._binormals[i].normalize();
  2771. }
  2772. }
  2773. };
  2774. // private function getFirstNonNullVector(index)
  2775. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2776. Path3D.prototype._getFirstNonNullVector = function (index) {
  2777. var i = 1;
  2778. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2779. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2780. i++;
  2781. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2782. }
  2783. return nNVector;
  2784. };
  2785. // private function getLastNonNullVector(index)
  2786. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2787. Path3D.prototype._getLastNonNullVector = function (index) {
  2788. var i = 1;
  2789. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2790. while (nLVector.length() === 0 && index > i + 1) {
  2791. i++;
  2792. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2793. }
  2794. return nLVector;
  2795. };
  2796. // private function normalVector(v0, vt, va) :
  2797. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2798. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2799. Path3D.prototype._normalVector = function (v0, vt, va) {
  2800. var normal0;
  2801. if (va === undefined || va === null) {
  2802. var point;
  2803. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2804. point = new Vector3(0, -1, 0);
  2805. }
  2806. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2807. point = new Vector3(1, 0, 0);
  2808. }
  2809. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2810. point = new Vector3(0, 0, 1);
  2811. }
  2812. normal0 = Vector3.Cross(vt, point);
  2813. }
  2814. else {
  2815. normal0 = Vector3.Cross(vt, va);
  2816. Vector3.CrossToRef(normal0, vt, normal0);
  2817. }
  2818. normal0.normalize();
  2819. return normal0;
  2820. };
  2821. return Path3D;
  2822. })();
  2823. BABYLON.Path3D = Path3D;
  2824. var Curve3 = (function () {
  2825. function Curve3(points) {
  2826. this._length = 0;
  2827. this._points = points;
  2828. this._length = this._computeLength(points);
  2829. }
  2830. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2831. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2832. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2833. var bez = new Array();
  2834. var equation = function (t, val0, val1, val2) {
  2835. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2836. return res;
  2837. };
  2838. for (var i = 0; i <= nbPoints; i++) {
  2839. 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)));
  2840. }
  2841. return new Curve3(bez);
  2842. };
  2843. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2844. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2845. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2846. var bez = new Array();
  2847. var equation = function (t, val0, val1, val2, val3) {
  2848. 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;
  2849. return res;
  2850. };
  2851. for (var i = 0; i <= nbPoints; i++) {
  2852. 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)));
  2853. }
  2854. return new Curve3(bez);
  2855. };
  2856. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2857. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2858. var hermite = new Array();
  2859. var step = 1 / nbPoints;
  2860. for (var i = 0; i <= nbPoints; i++) {
  2861. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2862. }
  2863. return new Curve3(hermite);
  2864. };
  2865. Curve3.prototype.getPoints = function () {
  2866. return this._points;
  2867. };
  2868. Curve3.prototype.length = function () {
  2869. return this._length;
  2870. };
  2871. Curve3.prototype.continue = function (curve) {
  2872. var lastPoint = this._points[this._points.length - 1];
  2873. var continuedPoints = this._points.slice();
  2874. var curvePoints = curve.getPoints();
  2875. for (var i = 1; i < curvePoints.length; i++) {
  2876. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2877. }
  2878. var continuedCurve = new Curve3(continuedPoints);
  2879. return continuedCurve;
  2880. };
  2881. Curve3.prototype._computeLength = function (path) {
  2882. var l = 0;
  2883. for (var i = 1; i < path.length; i++) {
  2884. l += (path[i].subtract(path[i - 1])).length();
  2885. }
  2886. return l;
  2887. };
  2888. return Curve3;
  2889. })();
  2890. BABYLON.Curve3 = Curve3;
  2891. // Vertex formats
  2892. var PositionNormalVertex = (function () {
  2893. function PositionNormalVertex(position, normal) {
  2894. if (position === void 0) { position = Vector3.Zero(); }
  2895. if (normal === void 0) { normal = Vector3.Up(); }
  2896. this.position = position;
  2897. this.normal = normal;
  2898. }
  2899. PositionNormalVertex.prototype.clone = function () {
  2900. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2901. };
  2902. return PositionNormalVertex;
  2903. })();
  2904. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2905. var PositionNormalTextureVertex = (function () {
  2906. function PositionNormalTextureVertex(position, normal, uv) {
  2907. if (position === void 0) { position = Vector3.Zero(); }
  2908. if (normal === void 0) { normal = Vector3.Up(); }
  2909. if (uv === void 0) { uv = Vector2.Zero(); }
  2910. this.position = position;
  2911. this.normal = normal;
  2912. this.uv = uv;
  2913. }
  2914. PositionNormalTextureVertex.prototype.clone = function () {
  2915. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2916. };
  2917. return PositionNormalTextureVertex;
  2918. })();
  2919. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2920. })(BABYLON || (BABYLON = {}));
  2921. var BABYLON;
  2922. (function (BABYLON) {
  2923. var Database = (function () {
  2924. function Database(urlToScene, callbackManifestChecked) {
  2925. // Handling various flavors of prefixed version of IndexedDB
  2926. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2927. this.callbackManifestChecked = callbackManifestChecked;
  2928. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2929. this.db = null;
  2930. this.enableSceneOffline = false;
  2931. this.enableTexturesOffline = false;
  2932. this.manifestVersionFound = 0;
  2933. this.mustUpdateRessources = false;
  2934. this.hasReachedQuota = false;
  2935. if (!Database.IDBStorageEnabled) {
  2936. this.callbackManifestChecked(true);
  2937. }
  2938. else {
  2939. this.checkManifestFile();
  2940. }
  2941. }
  2942. Database.prototype.checkManifestFile = function () {
  2943. var _this = this;
  2944. function noManifestFile() {
  2945. that.enableSceneOffline = false;
  2946. that.enableTexturesOffline = false;
  2947. that.callbackManifestChecked(false);
  2948. }
  2949. var that = this;
  2950. var manifestURL = this.currentSceneUrl + ".manifest";
  2951. var xhr = new XMLHttpRequest();
  2952. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2953. xhr.open("GET", manifestURLTimeStamped, true);
  2954. xhr.addEventListener("load", function () {
  2955. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2956. try {
  2957. var manifestFile = JSON.parse(xhr.response);
  2958. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2959. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2960. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2961. _this.manifestVersionFound = manifestFile.version;
  2962. }
  2963. if (_this.callbackManifestChecked) {
  2964. _this.callbackManifestChecked(true);
  2965. }
  2966. }
  2967. catch (ex) {
  2968. noManifestFile();
  2969. }
  2970. }
  2971. else {
  2972. noManifestFile();
  2973. }
  2974. }, false);
  2975. xhr.addEventListener("error", function (event) {
  2976. noManifestFile();
  2977. }, false);
  2978. try {
  2979. xhr.send();
  2980. }
  2981. catch (ex) {
  2982. BABYLON.Tools.Error("Error on XHR send request.");
  2983. that.callbackManifestChecked(false);
  2984. }
  2985. };
  2986. Database.prototype.openAsync = function (successCallback, errorCallback) {
  2987. var _this = this;
  2988. function handleError() {
  2989. that.isSupported = false;
  2990. if (errorCallback)
  2991. errorCallback();
  2992. }
  2993. var that = this;
  2994. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  2995. // Your browser doesn't support IndexedDB
  2996. this.isSupported = false;
  2997. if (errorCallback)
  2998. errorCallback();
  2999. }
  3000. else {
  3001. // If the DB hasn't been opened or created yet
  3002. if (!this.db) {
  3003. this.hasReachedQuota = false;
  3004. this.isSupported = true;
  3005. var request = this.idbFactory.open("babylonjs", 1);
  3006. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3007. request.onerror = function (event) {
  3008. handleError();
  3009. };
  3010. // executes when a version change transaction cannot complete due to other active transactions
  3011. request.onblocked = function (event) {
  3012. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3013. handleError();
  3014. };
  3015. // DB has been opened successfully
  3016. request.onsuccess = function (event) {
  3017. _this.db = request.result;
  3018. successCallback();
  3019. };
  3020. // Initialization of the DB. Creating Scenes & Textures stores
  3021. request.onupgradeneeded = function (event) {
  3022. _this.db = (event.target).result;
  3023. try {
  3024. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3025. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3026. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3027. }
  3028. catch (ex) {
  3029. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3030. handleError();
  3031. }
  3032. };
  3033. }
  3034. else {
  3035. if (successCallback)
  3036. successCallback();
  3037. }
  3038. }
  3039. };
  3040. Database.prototype.loadImageFromDB = function (url, image) {
  3041. var _this = this;
  3042. var completeURL = Database.ReturnFullUrlLocation(url);
  3043. var saveAndLoadImage = function () {
  3044. if (!_this.hasReachedQuota && _this.db !== null) {
  3045. // the texture is not yet in the DB, let's try to save it
  3046. _this._saveImageIntoDBAsync(completeURL, image);
  3047. }
  3048. else {
  3049. image.src = url;
  3050. }
  3051. };
  3052. if (!this.mustUpdateRessources) {
  3053. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3054. }
  3055. else {
  3056. saveAndLoadImage();
  3057. }
  3058. };
  3059. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3060. if (this.isSupported && this.db !== null) {
  3061. var texture;
  3062. var transaction = this.db.transaction(["textures"]);
  3063. transaction.onabort = function (event) {
  3064. image.src = url;
  3065. };
  3066. transaction.oncomplete = function (event) {
  3067. var blobTextureURL;
  3068. if (texture) {
  3069. var URL = window.URL || window.webkitURL;
  3070. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3071. image.onerror = function () {
  3072. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3073. image.src = url;
  3074. };
  3075. image.src = blobTextureURL;
  3076. }
  3077. else {
  3078. notInDBCallback();
  3079. }
  3080. };
  3081. var getRequest = transaction.objectStore("textures").get(url);
  3082. getRequest.onsuccess = function (event) {
  3083. texture = (event.target).result;
  3084. };
  3085. getRequest.onerror = function (event) {
  3086. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3087. image.src = url;
  3088. };
  3089. }
  3090. else {
  3091. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3092. image.src = url;
  3093. }
  3094. };
  3095. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3096. var _this = this;
  3097. if (this.isSupported) {
  3098. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3099. var generateBlobUrl = function () {
  3100. var blobTextureURL;
  3101. if (blob) {
  3102. var URL = window.URL || window.webkitURL;
  3103. try {
  3104. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3105. }
  3106. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3107. catch (ex) {
  3108. blobTextureURL = URL.createObjectURL(blob);
  3109. }
  3110. }
  3111. image.src = blobTextureURL;
  3112. };
  3113. if (Database.IsUASupportingBlobStorage) {
  3114. var xhr = new XMLHttpRequest(), blob;
  3115. xhr.open("GET", url, true);
  3116. xhr.responseType = "blob";
  3117. xhr.addEventListener("load", function () {
  3118. if (xhr.status === 200) {
  3119. // Blob as response (XHR2)
  3120. blob = xhr.response;
  3121. var transaction = _this.db.transaction(["textures"], "readwrite");
  3122. // the transaction could abort because of a QuotaExceededError error
  3123. transaction.onabort = function (event) {
  3124. try {
  3125. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3126. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3127. this.hasReachedQuota = true;
  3128. }
  3129. }
  3130. catch (ex) { }
  3131. generateBlobUrl();
  3132. };
  3133. transaction.oncomplete = function (event) {
  3134. generateBlobUrl();
  3135. };
  3136. var newTexture = { textureUrl: url, data: blob };
  3137. try {
  3138. // Put the blob into the dabase
  3139. var addRequest = transaction.objectStore("textures").put(newTexture);
  3140. addRequest.onsuccess = function (event) {
  3141. };
  3142. addRequest.onerror = function (event) {
  3143. generateBlobUrl();
  3144. };
  3145. }
  3146. catch (ex) {
  3147. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3148. if (ex.code === 25) {
  3149. Database.IsUASupportingBlobStorage = false;
  3150. }
  3151. image.src = url;
  3152. }
  3153. }
  3154. else {
  3155. image.src = url;
  3156. }
  3157. }, false);
  3158. xhr.addEventListener("error", function (event) {
  3159. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3160. image.src = url;
  3161. }, false);
  3162. xhr.send();
  3163. }
  3164. else {
  3165. image.src = url;
  3166. }
  3167. }
  3168. else {
  3169. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3170. image.src = url;
  3171. }
  3172. };
  3173. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3174. var _this = this;
  3175. var updateVersion = function (event) {
  3176. // the version is not yet in the DB or we need to update it
  3177. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3178. };
  3179. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3180. };
  3181. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3182. var _this = this;
  3183. if (this.isSupported) {
  3184. var version;
  3185. try {
  3186. var transaction = this.db.transaction(["versions"]);
  3187. transaction.oncomplete = function (event) {
  3188. if (version) {
  3189. // If the version in the JSON file is > than the version in DB
  3190. if (_this.manifestVersionFound > version.data) {
  3191. _this.mustUpdateRessources = true;
  3192. updateInDBCallback();
  3193. }
  3194. else {
  3195. callback(version.data);
  3196. }
  3197. }
  3198. else {
  3199. _this.mustUpdateRessources = true;
  3200. updateInDBCallback();
  3201. }
  3202. };
  3203. transaction.onabort = function (event) {
  3204. callback(-1);
  3205. };
  3206. var getRequest = transaction.objectStore("versions").get(url);
  3207. getRequest.onsuccess = function (event) {
  3208. version = (event.target).result;
  3209. };
  3210. getRequest.onerror = function (event) {
  3211. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3212. callback(-1);
  3213. };
  3214. }
  3215. catch (ex) {
  3216. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3217. callback(-1);
  3218. }
  3219. }
  3220. else {
  3221. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3222. callback(-1);
  3223. }
  3224. };
  3225. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3226. var _this = this;
  3227. if (this.isSupported && !this.hasReachedQuota) {
  3228. try {
  3229. // Open a transaction to the database
  3230. var transaction = this.db.transaction(["versions"], "readwrite");
  3231. // the transaction could abort because of a QuotaExceededError error
  3232. transaction.onabort = function (event) {
  3233. try {
  3234. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3235. _this.hasReachedQuota = true;
  3236. }
  3237. }
  3238. catch (ex) { }
  3239. callback(-1);
  3240. };
  3241. transaction.oncomplete = function (event) {
  3242. callback(_this.manifestVersionFound);
  3243. };
  3244. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3245. // Put the scene into the database
  3246. var addRequest = transaction.objectStore("versions").put(newVersion);
  3247. addRequest.onsuccess = function (event) {
  3248. };
  3249. addRequest.onerror = function (event) {
  3250. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3251. };
  3252. }
  3253. catch (ex) {
  3254. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3255. callback(-1);
  3256. }
  3257. }
  3258. else {
  3259. callback(-1);
  3260. }
  3261. };
  3262. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3263. var _this = this;
  3264. var completeUrl = Database.ReturnFullUrlLocation(url);
  3265. var saveAndLoadFile = function (event) {
  3266. // the scene is not yet in the DB, let's try to save it
  3267. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3268. };
  3269. this._checkVersionFromDB(completeUrl, function (version) {
  3270. if (version !== -1) {
  3271. if (!_this.mustUpdateRessources) {
  3272. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3273. }
  3274. else {
  3275. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3276. }
  3277. }
  3278. else {
  3279. errorCallback();
  3280. }
  3281. });
  3282. };
  3283. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3284. if (this.isSupported) {
  3285. var targetStore;
  3286. if (url.indexOf(".babylon") !== -1) {
  3287. targetStore = "scenes";
  3288. }
  3289. else {
  3290. targetStore = "textures";
  3291. }
  3292. var file;
  3293. var transaction = this.db.transaction([targetStore]);
  3294. transaction.oncomplete = function (event) {
  3295. if (file) {
  3296. callback(file.data);
  3297. }
  3298. else {
  3299. notInDBCallback();
  3300. }
  3301. };
  3302. transaction.onabort = function (event) {
  3303. notInDBCallback();
  3304. };
  3305. var getRequest = transaction.objectStore(targetStore).get(url);
  3306. getRequest.onsuccess = function (event) {
  3307. file = (event.target).result;
  3308. };
  3309. getRequest.onerror = function (event) {
  3310. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3311. notInDBCallback();
  3312. };
  3313. }
  3314. else {
  3315. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3316. callback();
  3317. }
  3318. };
  3319. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3320. var _this = this;
  3321. if (this.isSupported) {
  3322. var targetStore;
  3323. if (url.indexOf(".babylon") !== -1) {
  3324. targetStore = "scenes";
  3325. }
  3326. else {
  3327. targetStore = "textures";
  3328. }
  3329. // Create XHR
  3330. var xhr = new XMLHttpRequest(), fileData;
  3331. xhr.open("GET", url, true);
  3332. if (useArrayBuffer) {
  3333. xhr.responseType = "arraybuffer";
  3334. }
  3335. xhr.onprogress = progressCallback;
  3336. xhr.addEventListener("load", function () {
  3337. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3338. // Blob as response (XHR2)
  3339. //fileData = xhr.responseText;
  3340. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3341. if (!_this.hasReachedQuota) {
  3342. // Open a transaction to the database
  3343. var transaction = _this.db.transaction([targetStore], "readwrite");
  3344. // the transaction could abort because of a QuotaExceededError error
  3345. transaction.onabort = function (event) {
  3346. try {
  3347. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3348. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3349. this.hasReachedQuota = true;
  3350. }
  3351. }
  3352. catch (ex) { }
  3353. callback(fileData);
  3354. };
  3355. transaction.oncomplete = function (event) {
  3356. callback(fileData);
  3357. };
  3358. var newFile;
  3359. if (targetStore === "scenes") {
  3360. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3361. }
  3362. else {
  3363. newFile = { textureUrl: url, data: fileData };
  3364. }
  3365. try {
  3366. // Put the scene into the database
  3367. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3368. addRequest.onsuccess = function (event) {
  3369. };
  3370. addRequest.onerror = function (event) {
  3371. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3372. };
  3373. }
  3374. catch (ex) {
  3375. callback(fileData);
  3376. }
  3377. }
  3378. else {
  3379. callback(fileData);
  3380. }
  3381. }
  3382. else {
  3383. callback();
  3384. }
  3385. }, false);
  3386. xhr.addEventListener("error", function (event) {
  3387. BABYLON.Tools.Error("error on XHR request.");
  3388. callback();
  3389. }, false);
  3390. xhr.send();
  3391. }
  3392. else {
  3393. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3394. callback();
  3395. }
  3396. };
  3397. Database.IsUASupportingBlobStorage = true;
  3398. Database.IDBStorageEnabled = true;
  3399. Database.parseURL = function (url) {
  3400. var a = document.createElement('a');
  3401. a.href = url;
  3402. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3403. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3404. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3405. return absLocation;
  3406. };
  3407. Database.ReturnFullUrlLocation = function (url) {
  3408. if (url.indexOf("http:/") === -1) {
  3409. return (Database.parseURL(window.location.href) + url);
  3410. }
  3411. else {
  3412. return url;
  3413. }
  3414. };
  3415. return Database;
  3416. })();
  3417. BABYLON.Database = Database;
  3418. })(BABYLON || (BABYLON = {}));
  3419. var BABYLON;
  3420. (function (BABYLON) {
  3421. var Internals;
  3422. (function (Internals) {
  3423. /*
  3424. * Based on jsTGALoader - Javascript loader for TGA file
  3425. * By Vincent Thibault
  3426. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3427. */
  3428. var TGATools = (function () {
  3429. function TGATools() {
  3430. }
  3431. TGATools.GetTGAHeader = function (data) {
  3432. var offset = 0;
  3433. var header = {
  3434. id_length: data[offset++],
  3435. colormap_type: data[offset++],
  3436. image_type: data[offset++],
  3437. colormap_index: data[offset++] | data[offset++] << 8,
  3438. colormap_length: data[offset++] | data[offset++] << 8,
  3439. colormap_size: data[offset++],
  3440. origin: [
  3441. data[offset++] | data[offset++] << 8,
  3442. data[offset++] | data[offset++] << 8
  3443. ],
  3444. width: data[offset++] | data[offset++] << 8,
  3445. height: data[offset++] | data[offset++] << 8,
  3446. pixel_size: data[offset++],
  3447. flags: data[offset++]
  3448. };
  3449. return header;
  3450. };
  3451. TGATools.UploadContent = function (gl, data) {
  3452. // Not enough data to contain header ?
  3453. if (data.length < 19) {
  3454. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3455. return;
  3456. }
  3457. // Read Header
  3458. var offset = 18;
  3459. var header = TGATools.GetTGAHeader(data);
  3460. // Assume it's a valid Targa file.
  3461. if (header.id_length + offset > data.length) {
  3462. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3463. return;
  3464. }
  3465. // Skip not needed data
  3466. offset += header.id_length;
  3467. var use_rle = false;
  3468. var use_pal = false;
  3469. var use_rgb = false;
  3470. var use_grey = false;
  3471. // Get some informations.
  3472. switch (header.image_type) {
  3473. case TGATools._TYPE_RLE_INDEXED:
  3474. use_rle = true;
  3475. case TGATools._TYPE_INDEXED:
  3476. use_pal = true;
  3477. break;
  3478. case TGATools._TYPE_RLE_RGB:
  3479. use_rle = true;
  3480. case TGATools._TYPE_RGB:
  3481. use_rgb = true;
  3482. break;
  3483. case TGATools._TYPE_RLE_GREY:
  3484. use_rle = true;
  3485. case TGATools._TYPE_GREY:
  3486. use_grey = true;
  3487. break;
  3488. }
  3489. var pixel_data;
  3490. var numAlphaBits = header.flags & 0xf;
  3491. var pixel_size = header.pixel_size >> 3;
  3492. var pixel_total = header.width * header.height * pixel_size;
  3493. // Read palettes
  3494. var palettes;
  3495. if (use_pal) {
  3496. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3497. }
  3498. // Read LRE
  3499. if (use_rle) {
  3500. pixel_data = new Uint8Array(pixel_total);
  3501. var c, count, i;
  3502. var localOffset = 0;
  3503. var pixels = new Uint8Array(pixel_size);
  3504. while (offset < pixel_total && localOffset < pixel_total) {
  3505. c = data[offset++];
  3506. count = (c & 0x7f) + 1;
  3507. // RLE pixels
  3508. if (c & 0x80) {
  3509. // Bind pixel tmp array
  3510. for (i = 0; i < pixel_size; ++i) {
  3511. pixels[i] = data[offset++];
  3512. }
  3513. // Copy pixel array
  3514. for (i = 0; i < count; ++i) {
  3515. pixel_data.set(pixels, localOffset + i * pixel_size);
  3516. }
  3517. localOffset += pixel_size * count;
  3518. }
  3519. else {
  3520. count *= pixel_size;
  3521. for (i = 0; i < count; ++i) {
  3522. pixel_data[localOffset + i] = data[offset++];
  3523. }
  3524. localOffset += count;
  3525. }
  3526. }
  3527. }
  3528. else {
  3529. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3530. }
  3531. // Load to texture
  3532. var x_start, y_start, x_step, y_step, y_end, x_end;
  3533. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3534. default:
  3535. case TGATools._ORIGIN_UL:
  3536. x_start = 0;
  3537. x_step = 1;
  3538. x_end = header.width;
  3539. y_start = 0;
  3540. y_step = 1;
  3541. y_end = header.height;
  3542. break;
  3543. case TGATools._ORIGIN_BL:
  3544. x_start = 0;
  3545. x_step = 1;
  3546. x_end = header.width;
  3547. y_start = header.height - 1;
  3548. y_step = -1;
  3549. y_end = -1;
  3550. break;
  3551. case TGATools._ORIGIN_UR:
  3552. x_start = header.width - 1;
  3553. x_step = -1;
  3554. x_end = -1;
  3555. y_start = 0;
  3556. y_step = 1;
  3557. y_end = header.height;
  3558. break;
  3559. case TGATools._ORIGIN_BR:
  3560. x_start = header.width - 1;
  3561. x_step = -1;
  3562. x_end = -1;
  3563. y_start = header.height - 1;
  3564. y_step = -1;
  3565. y_end = -1;
  3566. break;
  3567. }
  3568. // Load the specify method
  3569. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3570. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3571. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3572. };
  3573. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3574. var image = pixel_data, colormap = palettes;
  3575. var width = header.width, height = header.height;
  3576. var color, i = 0, x, y;
  3577. var imageData = new Uint8Array(width * height * 4);
  3578. for (y = y_start; y !== y_end; y += y_step) {
  3579. for (x = x_start; x !== x_end; x += x_step, i++) {
  3580. color = image[i];
  3581. imageData[(x + width * y) * 4 + 3] = 255;
  3582. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3583. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3584. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3585. }
  3586. }
  3587. return imageData;
  3588. };
  3589. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3590. var image = pixel_data;
  3591. var width = header.width, height = header.height;
  3592. var color, i = 0, x, y;
  3593. var imageData = new Uint8Array(width * height * 4);
  3594. for (y = y_start; y !== y_end; y += y_step) {
  3595. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3596. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3597. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3598. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3599. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3600. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3601. }
  3602. }
  3603. return imageData;
  3604. };
  3605. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3606. var image = pixel_data;
  3607. var width = header.width, height = header.height;
  3608. var i = 0, x, y;
  3609. var imageData = new Uint8Array(width * height * 4);
  3610. for (y = y_start; y !== y_end; y += y_step) {
  3611. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3612. imageData[(x + width * y) * 4 + 3] = 255;
  3613. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3614. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3615. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3616. }
  3617. }
  3618. return imageData;
  3619. };
  3620. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3621. var image = pixel_data;
  3622. var width = header.width, height = header.height;
  3623. var i = 0, x, y;
  3624. var imageData = new Uint8Array(width * height * 4);
  3625. for (y = y_start; y !== y_end; y += y_step) {
  3626. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3627. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3628. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3629. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3630. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3631. }
  3632. }
  3633. return imageData;
  3634. };
  3635. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3636. var image = pixel_data;
  3637. var width = header.width, height = header.height;
  3638. var color, i = 0, x, y;
  3639. var imageData = new Uint8Array(width * height * 4);
  3640. for (y = y_start; y !== y_end; y += y_step) {
  3641. for (x = x_start; x !== x_end; x += x_step, i++) {
  3642. color = image[i];
  3643. imageData[(x + width * y) * 4 + 0] = color;
  3644. imageData[(x + width * y) * 4 + 1] = color;
  3645. imageData[(x + width * y) * 4 + 2] = color;
  3646. imageData[(x + width * y) * 4 + 3] = 255;
  3647. }
  3648. }
  3649. return imageData;
  3650. };
  3651. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3652. var image = pixel_data;
  3653. var width = header.width, height = header.height;
  3654. var i = 0, x, y;
  3655. var imageData = new Uint8Array(width * height * 4);
  3656. for (y = y_start; y !== y_end; y += y_step) {
  3657. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3658. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3659. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3660. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3661. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3662. }
  3663. }
  3664. return imageData;
  3665. };
  3666. TGATools._TYPE_NO_DATA = 0;
  3667. TGATools._TYPE_INDEXED = 1;
  3668. TGATools._TYPE_RGB = 2;
  3669. TGATools._TYPE_GREY = 3;
  3670. TGATools._TYPE_RLE_INDEXED = 9;
  3671. TGATools._TYPE_RLE_RGB = 10;
  3672. TGATools._TYPE_RLE_GREY = 11;
  3673. TGATools._ORIGIN_MASK = 0x30;
  3674. TGATools._ORIGIN_SHIFT = 0x04;
  3675. TGATools._ORIGIN_BL = 0x00;
  3676. TGATools._ORIGIN_BR = 0x01;
  3677. TGATools._ORIGIN_UL = 0x02;
  3678. TGATools._ORIGIN_UR = 0x03;
  3679. return TGATools;
  3680. })();
  3681. Internals.TGATools = TGATools;
  3682. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3683. })(BABYLON || (BABYLON = {}));
  3684. var BABYLON;
  3685. (function (BABYLON) {
  3686. var SmartArray = (function () {
  3687. function SmartArray(capacity) {
  3688. this.length = 0;
  3689. this._duplicateId = 0;
  3690. this.data = new Array(capacity);
  3691. this._id = SmartArray._GlobalId++;
  3692. }
  3693. SmartArray.prototype.push = function (value) {
  3694. this.data[this.length++] = value;
  3695. if (this.length > this.data.length) {
  3696. this.data.length *= 2;
  3697. }
  3698. if (!value.__smartArrayFlags) {
  3699. value.__smartArrayFlags = {};
  3700. }
  3701. value.__smartArrayFlags[this._id] = this._duplicateId;
  3702. };
  3703. SmartArray.prototype.pushNoDuplicate = function (value) {
  3704. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3705. return;
  3706. }
  3707. this.push(value);
  3708. };
  3709. SmartArray.prototype.sort = function (compareFn) {
  3710. this.data.sort(compareFn);
  3711. };
  3712. SmartArray.prototype.reset = function () {
  3713. this.length = 0;
  3714. this._duplicateId++;
  3715. };
  3716. SmartArray.prototype.concat = function (array) {
  3717. if (array.length === 0) {
  3718. return;
  3719. }
  3720. if (this.length + array.length > this.data.length) {
  3721. this.data.length = (this.length + array.length) * 2;
  3722. }
  3723. for (var index = 0; index < array.length; index++) {
  3724. this.data[this.length++] = (array.data || array)[index];
  3725. }
  3726. };
  3727. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3728. if (array.length === 0) {
  3729. return;
  3730. }
  3731. if (this.length + array.length > this.data.length) {
  3732. this.data.length = (this.length + array.length) * 2;
  3733. }
  3734. for (var index = 0; index < array.length; index++) {
  3735. var item = (array.data || array)[index];
  3736. this.pushNoDuplicate(item);
  3737. }
  3738. };
  3739. SmartArray.prototype.indexOf = function (value) {
  3740. var position = this.data.indexOf(value);
  3741. if (position >= this.length) {
  3742. return -1;
  3743. }
  3744. return position;
  3745. };
  3746. // Statics
  3747. SmartArray._GlobalId = 0;
  3748. return SmartArray;
  3749. })();
  3750. BABYLON.SmartArray = SmartArray;
  3751. })(BABYLON || (BABYLON = {}));
  3752. var BABYLON;
  3753. (function (BABYLON) {
  3754. var SmartCollection = (function () {
  3755. function SmartCollection(capacity) {
  3756. if (capacity === void 0) { capacity = 10; }
  3757. this.count = 0;
  3758. this._initialCapacity = capacity;
  3759. this.items = {};
  3760. this._keys = new Array(this._initialCapacity);
  3761. }
  3762. SmartCollection.prototype.add = function (key, item) {
  3763. if (this.items[key] != undefined) {
  3764. return -1;
  3765. }
  3766. this.items[key] = item;
  3767. //literal keys are always strings, but we keep source type of key in _keys array
  3768. this._keys[this.count++] = key;
  3769. if (this.count > this._keys.length) {
  3770. this._keys.length *= 2;
  3771. }
  3772. return this.count;
  3773. };
  3774. SmartCollection.prototype.remove = function (key) {
  3775. if (this.items[key] == undefined) {
  3776. return -1;
  3777. }
  3778. return this.removeItemOfIndex(this.indexOf(key));
  3779. };
  3780. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3781. if (index < this.count && index > -1) {
  3782. delete this.items[this._keys[index]];
  3783. //here, shifting by hand is better optimised than .splice
  3784. while (index < this.count) {
  3785. this._keys[index] = this._keys[index + 1];
  3786. index++;
  3787. }
  3788. }
  3789. else {
  3790. return -1;
  3791. }
  3792. return --this.count;
  3793. };
  3794. SmartCollection.prototype.indexOf = function (key) {
  3795. for (var i = 0; i !== this.count; i++) {
  3796. if (this._keys[i] === key) {
  3797. return i;
  3798. }
  3799. }
  3800. return -1;
  3801. };
  3802. SmartCollection.prototype.item = function (key) {
  3803. return this.items[key];
  3804. };
  3805. SmartCollection.prototype.getAllKeys = function () {
  3806. if (this.count > 0) {
  3807. var keys = new Array(this.count);
  3808. for (var i = 0; i < this.count; i++) {
  3809. keys[i] = this._keys[i];
  3810. }
  3811. return keys;
  3812. }
  3813. else {
  3814. return undefined;
  3815. }
  3816. };
  3817. SmartCollection.prototype.getKeyByIndex = function (index) {
  3818. if (index < this.count && index > -1) {
  3819. return this._keys[index];
  3820. }
  3821. else {
  3822. return undefined;
  3823. }
  3824. };
  3825. SmartCollection.prototype.getItemByIndex = function (index) {
  3826. if (index < this.count && index > -1) {
  3827. return this.items[this._keys[index]];
  3828. }
  3829. else {
  3830. return undefined;
  3831. }
  3832. };
  3833. SmartCollection.prototype.empty = function () {
  3834. if (this.count > 0) {
  3835. this.count = 0;
  3836. this.items = {};
  3837. this._keys = new Array(this._initialCapacity);
  3838. }
  3839. };
  3840. SmartCollection.prototype.forEach = function (block) {
  3841. var key;
  3842. for (key in this.items) {
  3843. if (this.items.hasOwnProperty(key)) {
  3844. block(this.items[key]);
  3845. }
  3846. }
  3847. };
  3848. return SmartCollection;
  3849. })();
  3850. BABYLON.SmartCollection = SmartCollection;
  3851. })(BABYLON || (BABYLON = {}));
  3852. var BABYLON;
  3853. (function (BABYLON) {
  3854. // Screenshots
  3855. var screenshotCanvas;
  3856. var cloneValue = function (source, destinationObject) {
  3857. if (!source)
  3858. return null;
  3859. if (source instanceof BABYLON.Mesh) {
  3860. return null;
  3861. }
  3862. if (source instanceof BABYLON.SubMesh) {
  3863. return source.clone(destinationObject);
  3864. }
  3865. else if (source.clone) {
  3866. return source.clone();
  3867. }
  3868. return null;
  3869. };
  3870. var Tools = (function () {
  3871. function Tools() {
  3872. }
  3873. Tools.ToHex = function (i) {
  3874. var str = i.toString(16);
  3875. if (i <= 15) {
  3876. return ("0" + str).toUpperCase();
  3877. }
  3878. return str.toUpperCase();
  3879. };
  3880. Tools.SetImmediate = function (action) {
  3881. if (window.setImmediate) {
  3882. window.setImmediate(action);
  3883. }
  3884. else {
  3885. setTimeout(action, 1);
  3886. }
  3887. };
  3888. Tools.IsExponentOfTwo = function (value) {
  3889. var count = 1;
  3890. do {
  3891. count *= 2;
  3892. } while (count < value);
  3893. return count === value;
  3894. };
  3895. Tools.GetExponentOfTwo = function (value, max) {
  3896. var count = 1;
  3897. do {
  3898. count *= 2;
  3899. } while (count < value);
  3900. if (count > max)
  3901. count = max;
  3902. return count;
  3903. };
  3904. Tools.GetFilename = function (path) {
  3905. var index = path.lastIndexOf("/");
  3906. if (index < 0)
  3907. return path;
  3908. return path.substring(index + 1);
  3909. };
  3910. Tools.GetDOMTextContent = function (element) {
  3911. var result = "";
  3912. var child = element.firstChild;
  3913. while (child) {
  3914. if (child.nodeType === 3) {
  3915. result += child.textContent;
  3916. }
  3917. child = child.nextSibling;
  3918. }
  3919. return result;
  3920. };
  3921. Tools.ToDegrees = function (angle) {
  3922. return angle * 180 / Math.PI;
  3923. };
  3924. Tools.ToRadians = function (angle) {
  3925. return angle * Math.PI / 180;
  3926. };
  3927. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3928. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3929. var output = "";
  3930. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3931. var i = 0;
  3932. var bytes = new Uint8Array(buffer);
  3933. while (i < bytes.length) {
  3934. chr1 = bytes[i++];
  3935. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3936. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3937. enc1 = chr1 >> 2;
  3938. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3939. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3940. enc4 = chr3 & 63;
  3941. if (isNaN(chr2)) {
  3942. enc3 = enc4 = 64;
  3943. }
  3944. else if (isNaN(chr3)) {
  3945. enc4 = 64;
  3946. }
  3947. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3948. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  3949. }
  3950. return "data:image/png;base64," + output;
  3951. };
  3952. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3953. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3954. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3955. for (var index = indexStart; index < indexStart + indexCount; index++) {
  3956. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  3957. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3958. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3959. }
  3960. return {
  3961. minimum: minimum,
  3962. maximum: maximum
  3963. };
  3964. };
  3965. Tools.ExtractMinAndMax = function (positions, start, count) {
  3966. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3967. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3968. for (var index = start; index < start + count; index++) {
  3969. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  3970. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3971. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3972. }
  3973. return {
  3974. minimum: minimum,
  3975. maximum: maximum
  3976. };
  3977. };
  3978. Tools.MakeArray = function (obj, allowsNullUndefined) {
  3979. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  3980. return undefined;
  3981. return Array.isArray(obj) ? obj : [obj];
  3982. };
  3983. // Misc.
  3984. Tools.GetPointerPrefix = function () {
  3985. var eventPrefix = "pointer";
  3986. // Check if hand.js is referenced or if the browser natively supports pointer events
  3987. if (!navigator.pointerEnabled) {
  3988. eventPrefix = "mouse";
  3989. }
  3990. return eventPrefix;
  3991. };
  3992. Tools.QueueNewFrame = function (func) {
  3993. if (window.requestAnimationFrame)
  3994. window.requestAnimationFrame(func);
  3995. else if (window.msRequestAnimationFrame)
  3996. window.msRequestAnimationFrame(func);
  3997. else if (window.webkitRequestAnimationFrame)
  3998. window.webkitRequestAnimationFrame(func);
  3999. else if (window.mozRequestAnimationFrame)
  4000. window.mozRequestAnimationFrame(func);
  4001. else if (window.oRequestAnimationFrame)
  4002. window.oRequestAnimationFrame(func);
  4003. else {
  4004. window.setTimeout(func, 16);
  4005. }
  4006. };
  4007. Tools.RequestFullscreen = function (element) {
  4008. if (element.requestFullscreen)
  4009. element.requestFullscreen();
  4010. else if (element.msRequestFullscreen)
  4011. element.msRequestFullscreen();
  4012. else if (element.webkitRequestFullscreen)
  4013. element.webkitRequestFullscreen();
  4014. else if (element.mozRequestFullScreen)
  4015. element.mozRequestFullScreen();
  4016. };
  4017. Tools.ExitFullscreen = function () {
  4018. if (document.exitFullscreen) {
  4019. document.exitFullscreen();
  4020. }
  4021. else if (document.mozCancelFullScreen) {
  4022. document.mozCancelFullScreen();
  4023. }
  4024. else if (document.webkitCancelFullScreen) {
  4025. document.webkitCancelFullScreen();
  4026. }
  4027. else if (document.msCancelFullScreen) {
  4028. document.msCancelFullScreen();
  4029. }
  4030. };
  4031. // External files
  4032. Tools.CleanUrl = function (url) {
  4033. url = url.replace(/#/mg, "%23");
  4034. return url;
  4035. };
  4036. Tools.LoadImage = function (url, onload, onerror, database) {
  4037. if (url instanceof ArrayBuffer) {
  4038. url = Tools.EncodeArrayBufferTobase64(url);
  4039. }
  4040. url = Tools.CleanUrl(url);
  4041. var img = new Image();
  4042. if (url.substr(0, 5) !== "data:") {
  4043. if (Tools.CorsBehavior) {
  4044. switch (typeof (Tools.CorsBehavior)) {
  4045. case "function":
  4046. var result = Tools.CorsBehavior(url);
  4047. if (result) {
  4048. img.crossOrigin = result;
  4049. }
  4050. break;
  4051. case "string":
  4052. default:
  4053. img.crossOrigin = Tools.CorsBehavior;
  4054. break;
  4055. }
  4056. }
  4057. }
  4058. img.onload = function () {
  4059. onload(img);
  4060. };
  4061. img.onerror = function (err) {
  4062. Tools.Error("Error while trying to load texture: " + url);
  4063. 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";
  4064. onload(img);
  4065. };
  4066. var noIndexedDB = function () {
  4067. img.src = url;
  4068. };
  4069. var loadFromIndexedDB = function () {
  4070. database.loadImageFromDB(url, img);
  4071. };
  4072. //ANY database to do!
  4073. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4074. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4075. }
  4076. else {
  4077. if (url.indexOf("file:") === -1) {
  4078. noIndexedDB();
  4079. }
  4080. else {
  4081. try {
  4082. var textureName = url.substring(5);
  4083. var blobURL;
  4084. try {
  4085. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4086. }
  4087. catch (ex) {
  4088. // Chrome doesn't support oneTimeOnly parameter
  4089. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4090. }
  4091. img.src = blobURL;
  4092. }
  4093. catch (e) {
  4094. img.src = null;
  4095. }
  4096. }
  4097. }
  4098. return img;
  4099. };
  4100. //ANY
  4101. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4102. url = Tools.CleanUrl(url);
  4103. var noIndexedDB = function () {
  4104. var request = new XMLHttpRequest();
  4105. var loadUrl = Tools.BaseUrl + url;
  4106. request.open('GET', loadUrl, true);
  4107. if (useArrayBuffer) {
  4108. request.responseType = "arraybuffer";
  4109. }
  4110. request.onprogress = progressCallBack;
  4111. request.onreadystatechange = function () {
  4112. if (request.readyState === 4) {
  4113. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4114. callback(!useArrayBuffer ? request.responseText : request.response);
  4115. }
  4116. else {
  4117. if (onError) {
  4118. onError();
  4119. }
  4120. else {
  4121. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4122. }
  4123. }
  4124. }
  4125. };
  4126. request.send(null);
  4127. };
  4128. var loadFromIndexedDB = function () {
  4129. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4130. };
  4131. if (url.indexOf("file:") !== -1) {
  4132. var fileName = url.substring(5);
  4133. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4134. }
  4135. else {
  4136. // Caching all files
  4137. if (database && database.enableSceneOffline) {
  4138. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4139. }
  4140. else {
  4141. noIndexedDB();
  4142. }
  4143. }
  4144. };
  4145. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4146. var reader = new FileReader();
  4147. reader.onload = function (e) {
  4148. //target doesn't have result from ts 1.3
  4149. callback(e.target['result']);
  4150. };
  4151. reader.onprogress = progressCallback;
  4152. reader.readAsDataURL(fileToLoad);
  4153. };
  4154. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4155. var reader = new FileReader();
  4156. reader.onerror = function (e) {
  4157. Tools.Log("Error while reading file: " + fileToLoad.name);
  4158. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4159. };
  4160. reader.onload = function (e) {
  4161. //target doesn't have result from ts 1.3
  4162. callback(e.target['result']);
  4163. };
  4164. reader.onprogress = progressCallBack;
  4165. if (!useArrayBuffer) {
  4166. // Asynchronous read
  4167. reader.readAsText(fileToLoad);
  4168. }
  4169. else {
  4170. reader.readAsArrayBuffer(fileToLoad);
  4171. }
  4172. };
  4173. //returns a downloadable url to a file content.
  4174. Tools.FileAsURL = function (content) {
  4175. var fileBlob = new Blob([content]);
  4176. var url = window.URL || window.webkitURL;
  4177. var link = url.createObjectURL(fileBlob);
  4178. return link;
  4179. };
  4180. // Misc.
  4181. Tools.Clamp = function (value, min, max) {
  4182. if (min === void 0) { min = 0; }
  4183. if (max === void 0) { max = 1; }
  4184. return Math.min(max, Math.max(min, value));
  4185. };
  4186. // Returns -1 when value is a negative number and
  4187. // +1 when value is a positive number.
  4188. Tools.Sign = function (value) {
  4189. value = +value; // convert to a number
  4190. if (value === 0 || isNaN(value))
  4191. return value;
  4192. return value > 0 ? 1 : -1;
  4193. };
  4194. Tools.Format = function (value, decimals) {
  4195. if (decimals === void 0) { decimals = 2; }
  4196. return value.toFixed(decimals);
  4197. };
  4198. Tools.CheckExtends = function (v, min, max) {
  4199. if (v.x < min.x)
  4200. min.x = v.x;
  4201. if (v.y < min.y)
  4202. min.y = v.y;
  4203. if (v.z < min.z)
  4204. min.z = v.z;
  4205. if (v.x > max.x)
  4206. max.x = v.x;
  4207. if (v.y > max.y)
  4208. max.y = v.y;
  4209. if (v.z > max.z)
  4210. max.z = v.z;
  4211. };
  4212. Tools.WithinEpsilon = function (a, b, epsilon) {
  4213. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4214. var num = a - b;
  4215. return -epsilon <= num && num <= epsilon;
  4216. };
  4217. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4218. for (var prop in source) {
  4219. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4220. continue;
  4221. }
  4222. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4223. continue;
  4224. }
  4225. var sourceValue = source[prop];
  4226. var typeOfSourceValue = typeof sourceValue;
  4227. if (typeOfSourceValue === "function") {
  4228. continue;
  4229. }
  4230. if (typeOfSourceValue === "object") {
  4231. if (sourceValue instanceof Array) {
  4232. destination[prop] = [];
  4233. if (sourceValue.length > 0) {
  4234. if (typeof sourceValue[0] == "object") {
  4235. for (var index = 0; index < sourceValue.length; index++) {
  4236. var clonedValue = cloneValue(sourceValue[index], destination);
  4237. if (destination[prop].indexOf(clonedValue) === -1) {
  4238. destination[prop].push(clonedValue);
  4239. }
  4240. }
  4241. }
  4242. else {
  4243. destination[prop] = sourceValue.slice(0);
  4244. }
  4245. }
  4246. }
  4247. else {
  4248. destination[prop] = cloneValue(sourceValue, destination);
  4249. }
  4250. }
  4251. else {
  4252. destination[prop] = sourceValue;
  4253. }
  4254. }
  4255. };
  4256. Tools.IsEmpty = function (obj) {
  4257. for (var i in obj) {
  4258. return false;
  4259. }
  4260. return true;
  4261. };
  4262. Tools.RegisterTopRootEvents = function (events) {
  4263. for (var index = 0; index < events.length; index++) {
  4264. var event = events[index];
  4265. window.addEventListener(event.name, event.handler, false);
  4266. try {
  4267. if (window.parent) {
  4268. window.parent.addEventListener(event.name, event.handler, false);
  4269. }
  4270. }
  4271. catch (e) {
  4272. }
  4273. }
  4274. };
  4275. Tools.UnregisterTopRootEvents = function (events) {
  4276. for (var index = 0; index < events.length; index++) {
  4277. var event = events[index];
  4278. window.removeEventListener(event.name, event.handler);
  4279. try {
  4280. if (window.parent) {
  4281. window.parent.removeEventListener(event.name, event.handler);
  4282. }
  4283. }
  4284. catch (e) {
  4285. }
  4286. }
  4287. };
  4288. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4289. // Read the contents of the framebuffer
  4290. var numberOfChannelsByLine = width * 4;
  4291. var halfHeight = height / 2;
  4292. //Reading datas from WebGL
  4293. var data = engine.readPixels(0, 0, width, height);
  4294. //To flip image on Y axis.
  4295. for (var i = 0; i < halfHeight; i++) {
  4296. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4297. var currentCell = j + i * numberOfChannelsByLine;
  4298. var targetLine = height - i - 1;
  4299. var targetCell = j + targetLine * numberOfChannelsByLine;
  4300. var temp = data[currentCell];
  4301. data[currentCell] = data[targetCell];
  4302. data[targetCell] = temp;
  4303. }
  4304. }
  4305. // Create a 2D canvas to store the result
  4306. if (!screenshotCanvas) {
  4307. screenshotCanvas = document.createElement('canvas');
  4308. }
  4309. screenshotCanvas.width = width;
  4310. screenshotCanvas.height = height;
  4311. var context = screenshotCanvas.getContext('2d');
  4312. // Copy the pixels to a 2D canvas
  4313. var imageData = context.createImageData(width, height);
  4314. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4315. var castData = imageData.data;
  4316. castData.set(data);
  4317. context.putImageData(imageData, 0, 0);
  4318. var base64Image = screenshotCanvas.toDataURL();
  4319. if (successCallback) {
  4320. successCallback(base64Image);
  4321. }
  4322. else {
  4323. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4324. if (("download" in document.createElement("a"))) {
  4325. var a = window.document.createElement("a");
  4326. a.href = base64Image;
  4327. var date = new Date();
  4328. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4329. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4330. window.document.body.appendChild(a);
  4331. a.addEventListener("click", function () {
  4332. a.parentElement.removeChild(a);
  4333. });
  4334. a.click();
  4335. }
  4336. else {
  4337. var newWindow = window.open("");
  4338. var img = newWindow.document.createElement("img");
  4339. img.src = base64Image;
  4340. newWindow.document.body.appendChild(img);
  4341. }
  4342. }
  4343. };
  4344. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4345. var width;
  4346. var height;
  4347. //If a precision value is specified
  4348. if (size.precision) {
  4349. width = Math.round(engine.getRenderWidth() * size.precision);
  4350. height = Math.round(width / engine.getAspectRatio(camera));
  4351. size = { width: width, height: height };
  4352. }
  4353. else if (size.width && size.height) {
  4354. width = size.width;
  4355. height = size.height;
  4356. }
  4357. else if (size.width && !size.height) {
  4358. width = size.width;
  4359. height = Math.round(width / engine.getAspectRatio(camera));
  4360. size = { width: width, height: height };
  4361. }
  4362. else if (size.height && !size.width) {
  4363. height = size.height;
  4364. width = Math.round(height * engine.getAspectRatio(camera));
  4365. size = { width: width, height: height };
  4366. }
  4367. else if (!isNaN(size)) {
  4368. height = size;
  4369. width = size;
  4370. }
  4371. else {
  4372. Tools.Error("Invalid 'size' parameter !");
  4373. return;
  4374. }
  4375. var scene = camera.getScene();
  4376. var previousCamera = null;
  4377. if (scene.activeCamera !== camera) {
  4378. previousCamera = scene.activeCamera;
  4379. scene.activeCamera = camera;
  4380. }
  4381. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4382. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4383. texture.renderList = scene.meshes;
  4384. texture.onAfterRender = function () {
  4385. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4386. };
  4387. scene.incrementRenderId();
  4388. texture.render(true);
  4389. texture.dispose();
  4390. if (previousCamera) {
  4391. scene.activeCamera = previousCamera;
  4392. }
  4393. };
  4394. // XHR response validator for local file scenario
  4395. Tools.ValidateXHRData = function (xhr, dataType) {
  4396. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4397. if (dataType === void 0) { dataType = 7; }
  4398. try {
  4399. if (dataType & 1) {
  4400. if (xhr.responseText && xhr.responseText.length > 0) {
  4401. return true;
  4402. }
  4403. else if (dataType === 1) {
  4404. return false;
  4405. }
  4406. }
  4407. if (dataType & 2) {
  4408. // Check header width and height since there is no "TGA" magic number
  4409. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4410. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4411. return true;
  4412. }
  4413. else if (dataType === 2) {
  4414. return false;
  4415. }
  4416. }
  4417. if (dataType & 4) {
  4418. // Check for the "DDS" magic number
  4419. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4420. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4421. return true;
  4422. }
  4423. else {
  4424. return false;
  4425. }
  4426. }
  4427. }
  4428. catch (e) {
  4429. }
  4430. return false;
  4431. };
  4432. Object.defineProperty(Tools, "NoneLogLevel", {
  4433. get: function () {
  4434. return Tools._NoneLogLevel;
  4435. },
  4436. enumerable: true,
  4437. configurable: true
  4438. });
  4439. Object.defineProperty(Tools, "MessageLogLevel", {
  4440. get: function () {
  4441. return Tools._MessageLogLevel;
  4442. },
  4443. enumerable: true,
  4444. configurable: true
  4445. });
  4446. Object.defineProperty(Tools, "WarningLogLevel", {
  4447. get: function () {
  4448. return Tools._WarningLogLevel;
  4449. },
  4450. enumerable: true,
  4451. configurable: true
  4452. });
  4453. Object.defineProperty(Tools, "ErrorLogLevel", {
  4454. get: function () {
  4455. return Tools._ErrorLogLevel;
  4456. },
  4457. enumerable: true,
  4458. configurable: true
  4459. });
  4460. Object.defineProperty(Tools, "AllLogLevel", {
  4461. get: function () {
  4462. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4463. },
  4464. enumerable: true,
  4465. configurable: true
  4466. });
  4467. Tools._AddLogEntry = function (entry) {
  4468. Tools._LogCache = entry + Tools._LogCache;
  4469. if (Tools.OnNewCacheEntry) {
  4470. Tools.OnNewCacheEntry(entry);
  4471. }
  4472. };
  4473. Tools._FormatMessage = function (message) {
  4474. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4475. var date = new Date();
  4476. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4477. };
  4478. Tools._LogDisabled = function (message) {
  4479. // nothing to do
  4480. };
  4481. Tools._LogEnabled = function (message) {
  4482. var formattedMessage = Tools._FormatMessage(message);
  4483. console.log("BJS - " + formattedMessage);
  4484. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4485. Tools._AddLogEntry(entry);
  4486. };
  4487. Tools._WarnDisabled = function (message) {
  4488. // nothing to do
  4489. };
  4490. Tools._WarnEnabled = function (message) {
  4491. var formattedMessage = Tools._FormatMessage(message);
  4492. console.warn("BJS - " + formattedMessage);
  4493. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4494. Tools._AddLogEntry(entry);
  4495. };
  4496. Tools._ErrorDisabled = function (message) {
  4497. // nothing to do
  4498. };
  4499. Tools._ErrorEnabled = function (message) {
  4500. Tools.errorsCount++;
  4501. var formattedMessage = Tools._FormatMessage(message);
  4502. console.error("BJS - " + formattedMessage);
  4503. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4504. Tools._AddLogEntry(entry);
  4505. };
  4506. Object.defineProperty(Tools, "LogCache", {
  4507. get: function () {
  4508. return Tools._LogCache;
  4509. },
  4510. enumerable: true,
  4511. configurable: true
  4512. });
  4513. Tools.ClearLogCache = function () {
  4514. Tools._LogCache = "";
  4515. Tools.errorsCount = 0;
  4516. };
  4517. Object.defineProperty(Tools, "LogLevels", {
  4518. set: function (level) {
  4519. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4520. Tools.Log = Tools._LogEnabled;
  4521. }
  4522. else {
  4523. Tools.Log = Tools._LogDisabled;
  4524. }
  4525. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4526. Tools.Warn = Tools._WarnEnabled;
  4527. }
  4528. else {
  4529. Tools.Warn = Tools._WarnDisabled;
  4530. }
  4531. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4532. Tools.Error = Tools._ErrorEnabled;
  4533. }
  4534. else {
  4535. Tools.Error = Tools._ErrorDisabled;
  4536. }
  4537. },
  4538. enumerable: true,
  4539. configurable: true
  4540. });
  4541. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4542. get: function () {
  4543. return Tools._PerformanceNoneLogLevel;
  4544. },
  4545. enumerable: true,
  4546. configurable: true
  4547. });
  4548. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4549. get: function () {
  4550. return Tools._PerformanceUserMarkLogLevel;
  4551. },
  4552. enumerable: true,
  4553. configurable: true
  4554. });
  4555. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4556. get: function () {
  4557. return Tools._PerformanceConsoleLogLevel;
  4558. },
  4559. enumerable: true,
  4560. configurable: true
  4561. });
  4562. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4563. set: function (level) {
  4564. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4565. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4566. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4567. return;
  4568. }
  4569. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4570. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4571. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4572. return;
  4573. }
  4574. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4575. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4576. },
  4577. enumerable: true,
  4578. configurable: true
  4579. });
  4580. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4581. };
  4582. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4583. };
  4584. Tools._StartUserMark = function (counterName, condition) {
  4585. if (condition === void 0) { condition = true; }
  4586. if (!condition || !Tools._performance.mark) {
  4587. return;
  4588. }
  4589. Tools._performance.mark(counterName + "-Begin");
  4590. };
  4591. Tools._EndUserMark = function (counterName, condition) {
  4592. if (condition === void 0) { condition = true; }
  4593. if (!condition || !Tools._performance.mark) {
  4594. return;
  4595. }
  4596. Tools._performance.mark(counterName + "-End");
  4597. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4598. };
  4599. Tools._StartPerformanceConsole = function (counterName, condition) {
  4600. if (condition === void 0) { condition = true; }
  4601. if (!condition) {
  4602. return;
  4603. }
  4604. Tools._StartUserMark(counterName, condition);
  4605. if (console.time) {
  4606. console.time(counterName);
  4607. }
  4608. };
  4609. Tools._EndPerformanceConsole = function (counterName, condition) {
  4610. if (condition === void 0) { condition = true; }
  4611. if (!condition) {
  4612. return;
  4613. }
  4614. Tools._EndUserMark(counterName, condition);
  4615. if (console.time) {
  4616. console.timeEnd(counterName);
  4617. }
  4618. };
  4619. Object.defineProperty(Tools, "Now", {
  4620. get: function () {
  4621. if (window.performance && window.performance.now) {
  4622. return window.performance.now();
  4623. }
  4624. return new Date().getTime();
  4625. },
  4626. enumerable: true,
  4627. configurable: true
  4628. });
  4629. Tools.BaseUrl = "";
  4630. Tools.CorsBehavior = "anonymous";
  4631. // Logs
  4632. Tools._NoneLogLevel = 0;
  4633. Tools._MessageLogLevel = 1;
  4634. Tools._WarningLogLevel = 2;
  4635. Tools._ErrorLogLevel = 4;
  4636. Tools._LogCache = "";
  4637. Tools.errorsCount = 0;
  4638. Tools.Log = Tools._LogEnabled;
  4639. Tools.Warn = Tools._WarnEnabled;
  4640. Tools.Error = Tools._ErrorEnabled;
  4641. // Performances
  4642. Tools._PerformanceNoneLogLevel = 0;
  4643. Tools._PerformanceUserMarkLogLevel = 1;
  4644. Tools._PerformanceConsoleLogLevel = 2;
  4645. Tools._performance = window.performance;
  4646. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4647. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4648. return Tools;
  4649. })();
  4650. BABYLON.Tools = Tools;
  4651. /**
  4652. * An implementation of a loop for asynchronous functions.
  4653. */
  4654. var AsyncLoop = (function () {
  4655. /**
  4656. * Constroctor.
  4657. * @param iterations the number of iterations.
  4658. * @param _fn the function to run each iteration
  4659. * @param _successCallback the callback that will be called upon succesful execution
  4660. * @param offset starting offset.
  4661. */
  4662. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4663. if (offset === void 0) { offset = 0; }
  4664. this.iterations = iterations;
  4665. this._fn = _fn;
  4666. this._successCallback = _successCallback;
  4667. this.index = offset - 1;
  4668. this._done = false;
  4669. }
  4670. /**
  4671. * Execute the next iteration. Must be called after the last iteration was finished.
  4672. */
  4673. AsyncLoop.prototype.executeNext = function () {
  4674. if (!this._done) {
  4675. if (this.index + 1 < this.iterations) {
  4676. ++this.index;
  4677. this._fn(this);
  4678. }
  4679. else {
  4680. this.breakLoop();
  4681. }
  4682. }
  4683. };
  4684. /**
  4685. * Break the loop and run the success callback.
  4686. */
  4687. AsyncLoop.prototype.breakLoop = function () {
  4688. this._done = true;
  4689. this._successCallback();
  4690. };
  4691. /**
  4692. * Helper function
  4693. */
  4694. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4695. if (offset === void 0) { offset = 0; }
  4696. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4697. loop.executeNext();
  4698. return loop;
  4699. };
  4700. /**
  4701. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4702. * @param iterations total number of iterations
  4703. * @param syncedIterations number of synchronous iterations in each async iteration.
  4704. * @param fn the function to call each iteration.
  4705. * @param callback a success call back that will be called when iterating stops.
  4706. * @param breakFunction a break condition (optional)
  4707. * @param timeout timeout settings for the setTimeout function. default - 0.
  4708. * @constructor
  4709. */
  4710. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4711. if (timeout === void 0) { timeout = 0; }
  4712. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4713. if (breakFunction && breakFunction())
  4714. loop.breakLoop();
  4715. else {
  4716. setTimeout(function () {
  4717. for (var i = 0; i < syncedIterations; ++i) {
  4718. var iteration = (loop.index * syncedIterations) + i;
  4719. if (iteration >= iterations)
  4720. break;
  4721. fn(iteration);
  4722. if (breakFunction && breakFunction()) {
  4723. loop.breakLoop();
  4724. break;
  4725. }
  4726. }
  4727. loop.executeNext();
  4728. }, timeout);
  4729. }
  4730. }, callback);
  4731. };
  4732. return AsyncLoop;
  4733. })();
  4734. BABYLON.AsyncLoop = AsyncLoop;
  4735. })(BABYLON || (BABYLON = {}));
  4736. var BABYLON;
  4737. (function (BABYLON) {
  4738. var _DepthCullingState = (function () {
  4739. function _DepthCullingState() {
  4740. this._isDepthTestDirty = false;
  4741. this._isDepthMaskDirty = false;
  4742. this._isDepthFuncDirty = false;
  4743. this._isCullFaceDirty = false;
  4744. this._isCullDirty = false;
  4745. this._isZOffsetDirty = false;
  4746. }
  4747. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4748. get: function () {
  4749. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4750. },
  4751. enumerable: true,
  4752. configurable: true
  4753. });
  4754. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4755. get: function () {
  4756. return this._zOffset;
  4757. },
  4758. set: function (value) {
  4759. if (this._zOffset === value) {
  4760. return;
  4761. }
  4762. this._zOffset = value;
  4763. this._isZOffsetDirty = true;
  4764. },
  4765. enumerable: true,
  4766. configurable: true
  4767. });
  4768. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4769. get: function () {
  4770. return this._cullFace;
  4771. },
  4772. set: function (value) {
  4773. if (this._cullFace === value) {
  4774. return;
  4775. }
  4776. this._cullFace = value;
  4777. this._isCullFaceDirty = true;
  4778. },
  4779. enumerable: true,
  4780. configurable: true
  4781. });
  4782. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4783. get: function () {
  4784. return this._cull;
  4785. },
  4786. set: function (value) {
  4787. if (this._cull === value) {
  4788. return;
  4789. }
  4790. this._cull = value;
  4791. this._isCullDirty = true;
  4792. },
  4793. enumerable: true,
  4794. configurable: true
  4795. });
  4796. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4797. get: function () {
  4798. return this._depthFunc;
  4799. },
  4800. set: function (value) {
  4801. if (this._depthFunc === value) {
  4802. return;
  4803. }
  4804. this._depthFunc = value;
  4805. this._isDepthFuncDirty = true;
  4806. },
  4807. enumerable: true,
  4808. configurable: true
  4809. });
  4810. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4811. get: function () {
  4812. return this._depthMask;
  4813. },
  4814. set: function (value) {
  4815. if (this._depthMask === value) {
  4816. return;
  4817. }
  4818. this._depthMask = value;
  4819. this._isDepthMaskDirty = true;
  4820. },
  4821. enumerable: true,
  4822. configurable: true
  4823. });
  4824. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4825. get: function () {
  4826. return this._depthTest;
  4827. },
  4828. set: function (value) {
  4829. if (this._depthTest === value) {
  4830. return;
  4831. }
  4832. this._depthTest = value;
  4833. this._isDepthTestDirty = true;
  4834. },
  4835. enumerable: true,
  4836. configurable: true
  4837. });
  4838. _DepthCullingState.prototype.reset = function () {
  4839. this._depthMask = true;
  4840. this._depthTest = true;
  4841. this._depthFunc = null;
  4842. this._cull = null;
  4843. this._cullFace = null;
  4844. this._zOffset = 0;
  4845. this._isDepthTestDirty = true;
  4846. this._isDepthMaskDirty = true;
  4847. this._isDepthFuncDirty = false;
  4848. this._isCullFaceDirty = false;
  4849. this._isCullDirty = false;
  4850. this._isZOffsetDirty = false;
  4851. };
  4852. _DepthCullingState.prototype.apply = function (gl) {
  4853. if (!this.isDirty) {
  4854. return;
  4855. }
  4856. // Cull
  4857. if (this._isCullDirty) {
  4858. if (this.cull) {
  4859. gl.enable(gl.CULL_FACE);
  4860. }
  4861. else {
  4862. gl.disable(gl.CULL_FACE);
  4863. }
  4864. this._isCullDirty = false;
  4865. }
  4866. // Cull face
  4867. if (this._isCullFaceDirty) {
  4868. gl.cullFace(this.cullFace);
  4869. this._isCullFaceDirty = false;
  4870. }
  4871. // Depth mask
  4872. if (this._isDepthMaskDirty) {
  4873. gl.depthMask(this.depthMask);
  4874. this._isDepthMaskDirty = false;
  4875. }
  4876. // Depth test
  4877. if (this._isDepthTestDirty) {
  4878. if (this.depthTest) {
  4879. gl.enable(gl.DEPTH_TEST);
  4880. }
  4881. else {
  4882. gl.disable(gl.DEPTH_TEST);
  4883. }
  4884. this._isDepthTestDirty = false;
  4885. }
  4886. // Depth func
  4887. if (this._isDepthFuncDirty) {
  4888. gl.depthFunc(this.depthFunc);
  4889. this._isDepthFuncDirty = false;
  4890. }
  4891. // zOffset
  4892. if (this._isZOffsetDirty) {
  4893. if (this.zOffset) {
  4894. gl.enable(gl.POLYGON_OFFSET_FILL);
  4895. gl.polygonOffset(this.zOffset, 0);
  4896. }
  4897. else {
  4898. gl.disable(gl.POLYGON_OFFSET_FILL);
  4899. }
  4900. this._isZOffsetDirty = false;
  4901. }
  4902. };
  4903. return _DepthCullingState;
  4904. })();
  4905. BABYLON._DepthCullingState = _DepthCullingState;
  4906. var _AlphaState = (function () {
  4907. function _AlphaState() {
  4908. this._isAlphaBlendDirty = false;
  4909. this._isBlendFunctionParametersDirty = false;
  4910. this._alphaBlend = false;
  4911. this._blendFunctionParameters = new Array(4);
  4912. }
  4913. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4914. get: function () {
  4915. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4916. },
  4917. enumerable: true,
  4918. configurable: true
  4919. });
  4920. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4921. get: function () {
  4922. return this._alphaBlend;
  4923. },
  4924. set: function (value) {
  4925. if (this._alphaBlend === value) {
  4926. return;
  4927. }
  4928. this._alphaBlend = value;
  4929. this._isAlphaBlendDirty = true;
  4930. },
  4931. enumerable: true,
  4932. configurable: true
  4933. });
  4934. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4935. if (this._blendFunctionParameters[0] === value0 &&
  4936. this._blendFunctionParameters[1] === value1 &&
  4937. this._blendFunctionParameters[2] === value2 &&
  4938. this._blendFunctionParameters[3] === value3) {
  4939. return;
  4940. }
  4941. this._blendFunctionParameters[0] = value0;
  4942. this._blendFunctionParameters[1] = value1;
  4943. this._blendFunctionParameters[2] = value2;
  4944. this._blendFunctionParameters[3] = value3;
  4945. this._isBlendFunctionParametersDirty = true;
  4946. };
  4947. _AlphaState.prototype.reset = function () {
  4948. this._alphaBlend = false;
  4949. this._blendFunctionParameters[0] = null;
  4950. this._blendFunctionParameters[1] = null;
  4951. this._blendFunctionParameters[2] = null;
  4952. this._blendFunctionParameters[3] = null;
  4953. this._isAlphaBlendDirty = true;
  4954. this._isBlendFunctionParametersDirty = false;
  4955. };
  4956. _AlphaState.prototype.apply = function (gl) {
  4957. if (!this.isDirty) {
  4958. return;
  4959. }
  4960. // Alpha blend
  4961. if (this._isAlphaBlendDirty) {
  4962. if (this._alphaBlend) {
  4963. gl.enable(gl.BLEND);
  4964. }
  4965. else {
  4966. gl.disable(gl.BLEND);
  4967. }
  4968. this._isAlphaBlendDirty = false;
  4969. }
  4970. // Alpha function
  4971. if (this._isBlendFunctionParametersDirty) {
  4972. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4973. this._isBlendFunctionParametersDirty = false;
  4974. }
  4975. };
  4976. return _AlphaState;
  4977. })();
  4978. BABYLON._AlphaState = _AlphaState;
  4979. var compileShader = function (gl, source, type, defines) {
  4980. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4981. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  4982. gl.compileShader(shader);
  4983. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  4984. throw new Error(gl.getShaderInfoLog(shader));
  4985. }
  4986. return shader;
  4987. };
  4988. var getWebGLTextureType = function (gl, type) {
  4989. var textureType = gl.UNSIGNED_BYTE;
  4990. if (type === Engine.TEXTURETYPE_FLOAT)
  4991. textureType = gl.FLOAT;
  4992. return textureType;
  4993. };
  4994. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  4995. var magFilter = gl.NEAREST;
  4996. var minFilter = gl.NEAREST;
  4997. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4998. magFilter = gl.LINEAR;
  4999. if (generateMipMaps) {
  5000. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5001. }
  5002. else {
  5003. minFilter = gl.LINEAR;
  5004. }
  5005. }
  5006. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5007. magFilter = gl.LINEAR;
  5008. if (generateMipMaps) {
  5009. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5010. }
  5011. else {
  5012. minFilter = gl.LINEAR;
  5013. }
  5014. }
  5015. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5016. magFilter = gl.NEAREST;
  5017. if (generateMipMaps) {
  5018. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5019. }
  5020. else {
  5021. minFilter = gl.NEAREST;
  5022. }
  5023. }
  5024. return {
  5025. min: minFilter,
  5026. mag: magFilter
  5027. };
  5028. };
  5029. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5031. var engine = scene.getEngine();
  5032. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5033. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5034. gl.bindTexture(gl.TEXTURE_2D, texture);
  5035. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5036. texture._baseWidth = width;
  5037. texture._baseHeight = height;
  5038. texture._width = potWidth;
  5039. texture._height = potHeight;
  5040. texture.isReady = true;
  5041. processFunction(potWidth, potHeight);
  5042. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5043. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5044. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5045. if (!noMipmap && !isCompressed) {
  5046. gl.generateMipmap(gl.TEXTURE_2D);
  5047. }
  5048. gl.bindTexture(gl.TEXTURE_2D, null);
  5049. engine.resetTextureCache();
  5050. scene._removePendingData(texture);
  5051. };
  5052. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5053. var onload = function () {
  5054. loadedImages[index] = img;
  5055. loadedImages._internalCount++;
  5056. scene._removePendingData(img);
  5057. if (loadedImages._internalCount === 6) {
  5058. onfinish(loadedImages);
  5059. }
  5060. };
  5061. var onerror = function () {
  5062. scene._removePendingData(img);
  5063. };
  5064. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5065. scene._addPendingData(img);
  5066. };
  5067. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5068. var loadedImages = [];
  5069. loadedImages._internalCount = 0;
  5070. for (var index = 0; index < 6; index++) {
  5071. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5072. }
  5073. };
  5074. var EngineCapabilities = (function () {
  5075. function EngineCapabilities() {
  5076. }
  5077. return EngineCapabilities;
  5078. })();
  5079. BABYLON.EngineCapabilities = EngineCapabilities;
  5080. /**
  5081. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5082. */
  5083. var Engine = (function () {
  5084. /**
  5085. * @constructor
  5086. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5087. * @param {boolean} [antialias] - enable antialias
  5088. * @param options - further options to be sent to the getContext function
  5089. */
  5090. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5091. var _this = this;
  5092. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5093. // Public members
  5094. this.isFullscreen = false;
  5095. this.isPointerLock = false;
  5096. this.cullBackFaces = true;
  5097. this.renderEvenInBackground = true;
  5098. // To enable/disable IDB support and avoid XHR on .manifest
  5099. this.enableOfflineSupport = true;
  5100. this.scenes = new Array();
  5101. this._windowIsBackground = false;
  5102. this._drawCalls = 0;
  5103. this._renderingQueueLaunched = false;
  5104. this._activeRenderLoops = [];
  5105. // FPS
  5106. this.fpsRange = 60;
  5107. this.previousFramesDuration = [];
  5108. this.fps = 60;
  5109. this.deltaTime = 0;
  5110. // States
  5111. this._depthCullingState = new _DepthCullingState();
  5112. this._alphaState = new _AlphaState();
  5113. this._alphaMode = Engine.ALPHA_DISABLE;
  5114. // Cache
  5115. this._loadedTexturesCache = new Array();
  5116. this._maxTextureChannels = 16;
  5117. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5118. this._compiledEffects = {};
  5119. this._uintIndicesCurrentlySet = false;
  5120. this._renderingCanvas = canvas;
  5121. options = options || {};
  5122. options.antialias = antialias;
  5123. if (options.preserveDrawingBuffer === undefined) {
  5124. options.preserveDrawingBuffer = false;
  5125. }
  5126. // GL
  5127. try {
  5128. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5129. }
  5130. catch (e) {
  5131. throw new Error("WebGL not supported");
  5132. }
  5133. if (!this._gl) {
  5134. throw new Error("WebGL not supported");
  5135. }
  5136. this._onBlur = function () {
  5137. _this._windowIsBackground = true;
  5138. };
  5139. this._onFocus = function () {
  5140. _this._windowIsBackground = false;
  5141. };
  5142. window.addEventListener("blur", this._onBlur);
  5143. window.addEventListener("focus", this._onFocus);
  5144. // Viewport
  5145. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5146. this.resize();
  5147. // Caps
  5148. this._caps = new EngineCapabilities();
  5149. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5150. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5151. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5152. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5153. // Infos
  5154. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5155. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5156. if (rendererInfo != null) {
  5157. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5158. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5159. }
  5160. if (!this._glVendor) {
  5161. this._glVendor = "Unknown vendor";
  5162. }
  5163. if (!this._glRenderer) {
  5164. this._glRenderer = "Unknown renderer";
  5165. }
  5166. // Extensions
  5167. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5168. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5169. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5170. 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');
  5171. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5172. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5173. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5174. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5175. this._caps.highPrecisionShaderSupported = true;
  5176. if (this._gl.getShaderPrecisionFormat) {
  5177. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5178. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5179. }
  5180. // Depth buffer
  5181. this.setDepthBuffer(true);
  5182. this.setDepthFunctionToLessOrEqual();
  5183. this.setDepthWrite(true);
  5184. // Fullscreen
  5185. this._onFullscreenChange = function () {
  5186. if (document.fullscreen !== undefined) {
  5187. _this.isFullscreen = document.fullscreen;
  5188. }
  5189. else if (document.mozFullScreen !== undefined) {
  5190. _this.isFullscreen = document.mozFullScreen;
  5191. }
  5192. else if (document.webkitIsFullScreen !== undefined) {
  5193. _this.isFullscreen = document.webkitIsFullScreen;
  5194. }
  5195. else if (document.msIsFullScreen !== undefined) {
  5196. _this.isFullscreen = document.msIsFullScreen;
  5197. }
  5198. // Pointer lock
  5199. if (_this.isFullscreen && _this._pointerLockRequested) {
  5200. canvas.requestPointerLock = canvas.requestPointerLock ||
  5201. canvas.msRequestPointerLock ||
  5202. canvas.mozRequestPointerLock ||
  5203. canvas.webkitRequestPointerLock;
  5204. if (canvas.requestPointerLock) {
  5205. canvas.requestPointerLock();
  5206. }
  5207. }
  5208. };
  5209. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5210. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5211. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5212. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5213. // Pointer lock
  5214. this._onPointerLockChange = function () {
  5215. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5216. document.webkitPointerLockElement === canvas ||
  5217. document.msPointerLockElement === canvas ||
  5218. document.pointerLockElement === canvas);
  5219. };
  5220. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5221. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5222. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5223. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5224. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5225. Engine.audioEngine = new BABYLON.AudioEngine();
  5226. }
  5227. //default loading screen
  5228. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5229. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5230. }
  5231. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5232. get: function () {
  5233. return Engine._ALPHA_DISABLE;
  5234. },
  5235. enumerable: true,
  5236. configurable: true
  5237. });
  5238. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5239. get: function () {
  5240. return Engine._ALPHA_ONEONE;
  5241. },
  5242. enumerable: true,
  5243. configurable: true
  5244. });
  5245. Object.defineProperty(Engine, "ALPHA_ADD", {
  5246. get: function () {
  5247. return Engine._ALPHA_ADD;
  5248. },
  5249. enumerable: true,
  5250. configurable: true
  5251. });
  5252. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5253. get: function () {
  5254. return Engine._ALPHA_COMBINE;
  5255. },
  5256. enumerable: true,
  5257. configurable: true
  5258. });
  5259. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5260. get: function () {
  5261. return Engine._ALPHA_SUBTRACT;
  5262. },
  5263. enumerable: true,
  5264. configurable: true
  5265. });
  5266. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5267. get: function () {
  5268. return Engine._ALPHA_MULTIPLY;
  5269. },
  5270. enumerable: true,
  5271. configurable: true
  5272. });
  5273. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5274. get: function () {
  5275. return Engine._ALPHA_MAXIMIZED;
  5276. },
  5277. enumerable: true,
  5278. configurable: true
  5279. });
  5280. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5281. get: function () {
  5282. return Engine._DELAYLOADSTATE_NONE;
  5283. },
  5284. enumerable: true,
  5285. configurable: true
  5286. });
  5287. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5288. get: function () {
  5289. return Engine._DELAYLOADSTATE_LOADED;
  5290. },
  5291. enumerable: true,
  5292. configurable: true
  5293. });
  5294. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5295. get: function () {
  5296. return Engine._DELAYLOADSTATE_LOADING;
  5297. },
  5298. enumerable: true,
  5299. configurable: true
  5300. });
  5301. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5302. get: function () {
  5303. return Engine._DELAYLOADSTATE_NOTLOADED;
  5304. },
  5305. enumerable: true,
  5306. configurable: true
  5307. });
  5308. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5309. get: function () {
  5310. return Engine._TEXTUREFORMAT_ALPHA;
  5311. },
  5312. enumerable: true,
  5313. configurable: true
  5314. });
  5315. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5316. get: function () {
  5317. return Engine._TEXTUREFORMAT_LUMINANCE;
  5318. },
  5319. enumerable: true,
  5320. configurable: true
  5321. });
  5322. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5323. get: function () {
  5324. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5325. },
  5326. enumerable: true,
  5327. configurable: true
  5328. });
  5329. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5330. get: function () {
  5331. return Engine._TEXTUREFORMAT_RGB;
  5332. },
  5333. enumerable: true,
  5334. configurable: true
  5335. });
  5336. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5337. get: function () {
  5338. return Engine._TEXTUREFORMAT_RGBA;
  5339. },
  5340. enumerable: true,
  5341. configurable: true
  5342. });
  5343. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5344. get: function () {
  5345. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5346. },
  5347. enumerable: true,
  5348. configurable: true
  5349. });
  5350. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5351. get: function () {
  5352. return Engine._TEXTURETYPE_FLOAT;
  5353. },
  5354. enumerable: true,
  5355. configurable: true
  5356. });
  5357. Object.defineProperty(Engine, "Version", {
  5358. get: function () {
  5359. return "2.3.0-alpha";
  5360. },
  5361. enumerable: true,
  5362. configurable: true
  5363. });
  5364. Engine.prototype._prepareWorkingCanvas = function () {
  5365. if (this._workingCanvas) {
  5366. return;
  5367. }
  5368. this._workingCanvas = document.createElement("canvas");
  5369. this._workingContext = this._workingCanvas.getContext("2d");
  5370. };
  5371. Engine.prototype.resetTextureCache = function () {
  5372. for (var index = 0; index < this._maxTextureChannels; index++) {
  5373. this._activeTexturesCache[index] = null;
  5374. }
  5375. };
  5376. Engine.prototype.getGlInfo = function () {
  5377. return {
  5378. vendor: this._glVendor,
  5379. renderer: this._glRenderer,
  5380. version: this._glVersion
  5381. };
  5382. };
  5383. Engine.prototype.getAspectRatio = function (camera) {
  5384. var viewport = camera.viewport;
  5385. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5386. };
  5387. Engine.prototype.getRenderWidth = function () {
  5388. if (this._currentRenderTarget) {
  5389. return this._currentRenderTarget._width;
  5390. }
  5391. return this._renderingCanvas.width;
  5392. };
  5393. Engine.prototype.getRenderHeight = function () {
  5394. if (this._currentRenderTarget) {
  5395. return this._currentRenderTarget._height;
  5396. }
  5397. return this._renderingCanvas.height;
  5398. };
  5399. Engine.prototype.getRenderingCanvas = function () {
  5400. return this._renderingCanvas;
  5401. };
  5402. Engine.prototype.getRenderingCanvasClientRect = function () {
  5403. return this._renderingCanvas.getBoundingClientRect();
  5404. };
  5405. Engine.prototype.setHardwareScalingLevel = function (level) {
  5406. this._hardwareScalingLevel = level;
  5407. this.resize();
  5408. };
  5409. Engine.prototype.getHardwareScalingLevel = function () {
  5410. return this._hardwareScalingLevel;
  5411. };
  5412. Engine.prototype.getLoadedTexturesCache = function () {
  5413. return this._loadedTexturesCache;
  5414. };
  5415. Engine.prototype.getCaps = function () {
  5416. return this._caps;
  5417. };
  5418. Object.defineProperty(Engine.prototype, "drawCalls", {
  5419. get: function () {
  5420. return this._drawCalls;
  5421. },
  5422. enumerable: true,
  5423. configurable: true
  5424. });
  5425. // Methods
  5426. Engine.prototype.resetDrawCalls = function () {
  5427. this._drawCalls = 0;
  5428. };
  5429. Engine.prototype.setDepthFunctionToGreater = function () {
  5430. this._depthCullingState.depthFunc = this._gl.GREATER;
  5431. };
  5432. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5433. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5434. };
  5435. Engine.prototype.setDepthFunctionToLess = function () {
  5436. this._depthCullingState.depthFunc = this._gl.LESS;
  5437. };
  5438. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5439. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5440. };
  5441. /**
  5442. * stop executing a render loop function and remove it from the execution array
  5443. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5444. */
  5445. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5446. if (!renderFunction) {
  5447. this._activeRenderLoops = [];
  5448. return;
  5449. }
  5450. var index = this._activeRenderLoops.indexOf(renderFunction);
  5451. if (index >= 0) {
  5452. this._activeRenderLoops.splice(index, 1);
  5453. }
  5454. };
  5455. Engine.prototype._renderLoop = function () {
  5456. var shouldRender = true;
  5457. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5458. shouldRender = false;
  5459. }
  5460. if (shouldRender) {
  5461. // Start new frame
  5462. this.beginFrame();
  5463. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5464. var renderFunction = this._activeRenderLoops[index];
  5465. renderFunction();
  5466. }
  5467. // Present
  5468. this.endFrame();
  5469. }
  5470. if (this._activeRenderLoops.length > 0) {
  5471. // Register new frame
  5472. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5473. }
  5474. else {
  5475. this._renderingQueueLaunched = false;
  5476. }
  5477. };
  5478. /**
  5479. * Register and execute a render loop. The engine can have more than one render function.
  5480. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5481. * @example
  5482. * engine.runRenderLoop(function () {
  5483. * scene.render()
  5484. * })
  5485. */
  5486. Engine.prototype.runRenderLoop = function (renderFunction) {
  5487. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5488. return;
  5489. }
  5490. this._activeRenderLoops.push(renderFunction);
  5491. if (!this._renderingQueueLaunched) {
  5492. this._renderingQueueLaunched = true;
  5493. this._bindedRenderFunction = this._renderLoop.bind(this);
  5494. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5495. }
  5496. };
  5497. /**
  5498. * Toggle full screen mode.
  5499. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5500. */
  5501. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5502. if (this.isFullscreen) {
  5503. BABYLON.Tools.ExitFullscreen();
  5504. }
  5505. else {
  5506. this._pointerLockRequested = requestPointerLock;
  5507. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5508. }
  5509. };
  5510. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5511. this.applyStates();
  5512. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5513. if (this._depthCullingState.depthMask) {
  5514. this._gl.clearDepth(1.0);
  5515. }
  5516. var mode = 0;
  5517. if (backBuffer)
  5518. mode |= this._gl.COLOR_BUFFER_BIT;
  5519. if (depthStencil && this._depthCullingState.depthMask)
  5520. mode |= this._gl.DEPTH_BUFFER_BIT;
  5521. this._gl.clear(mode);
  5522. };
  5523. /**
  5524. * Set the WebGL's viewport
  5525. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5526. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5527. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5528. */
  5529. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5530. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5531. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5532. var x = viewport.x || 0;
  5533. var y = viewport.y || 0;
  5534. this._cachedViewport = viewport;
  5535. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5536. };
  5537. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5538. this._cachedViewport = null;
  5539. this._gl.viewport(x, y, width, height);
  5540. };
  5541. Engine.prototype.beginFrame = function () {
  5542. this._measureFps();
  5543. };
  5544. Engine.prototype.endFrame = function () {
  5545. //this.flushFramebuffer();
  5546. };
  5547. /**
  5548. * resize the view according to the canvas' size.
  5549. * @example
  5550. * window.addEventListener("resize", function () {
  5551. * engine.resize();
  5552. * });
  5553. */
  5554. Engine.prototype.resize = function () {
  5555. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5556. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5557. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5558. for (var index = 0; index < this.scenes.length; index++) {
  5559. var scene = this.scenes[index];
  5560. if (scene.debugLayer.isVisible()) {
  5561. scene.debugLayer._syncPositions();
  5562. }
  5563. }
  5564. };
  5565. /**
  5566. * force a specific size of the canvas
  5567. * @param {number} width - the new canvas' width
  5568. * @param {number} height - the new canvas' height
  5569. */
  5570. Engine.prototype.setSize = function (width, height) {
  5571. this._renderingCanvas.width = width;
  5572. this._renderingCanvas.height = height;
  5573. for (var index = 0; index < this.scenes.length; index++) {
  5574. var scene = this.scenes[index];
  5575. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5576. var cam = scene.cameras[camIndex];
  5577. cam._currentRenderId = 0;
  5578. }
  5579. }
  5580. };
  5581. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5582. this._currentRenderTarget = texture;
  5583. var gl = this._gl;
  5584. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5585. if (texture.isCube) {
  5586. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5587. }
  5588. else {
  5589. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5590. }
  5591. this._gl.viewport(0, 0, texture._width, texture._height);
  5592. this.wipeCaches();
  5593. };
  5594. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5595. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5596. this._currentRenderTarget = null;
  5597. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5598. var gl = this._gl;
  5599. gl.bindTexture(gl.TEXTURE_2D, texture);
  5600. gl.generateMipmap(gl.TEXTURE_2D);
  5601. gl.bindTexture(gl.TEXTURE_2D, null);
  5602. }
  5603. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5604. };
  5605. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5606. if (texture.generateMipMaps) {
  5607. var gl = this._gl;
  5608. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5609. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5610. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5611. }
  5612. };
  5613. Engine.prototype.flushFramebuffer = function () {
  5614. this._gl.flush();
  5615. };
  5616. Engine.prototype.restoreDefaultFramebuffer = function () {
  5617. this._currentRenderTarget = null;
  5618. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5619. this.setViewport(this._cachedViewport);
  5620. this.wipeCaches();
  5621. };
  5622. // VBOs
  5623. Engine.prototype._resetVertexBufferBinding = function () {
  5624. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5625. this._cachedVertexBuffers = null;
  5626. };
  5627. Engine.prototype.createVertexBuffer = function (vertices) {
  5628. var vbo = this._gl.createBuffer();
  5629. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5630. if (vertices instanceof Float32Array) {
  5631. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5632. }
  5633. else {
  5634. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5635. }
  5636. this._resetVertexBufferBinding();
  5637. vbo.references = 1;
  5638. return vbo;
  5639. };
  5640. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5641. var vbo = this._gl.createBuffer();
  5642. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5643. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5644. this._resetVertexBufferBinding();
  5645. vbo.references = 1;
  5646. return vbo;
  5647. };
  5648. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5649. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5650. if (offset === undefined) {
  5651. offset = 0;
  5652. }
  5653. if (vertices instanceof Float32Array) {
  5654. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5655. }
  5656. else {
  5657. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5658. }
  5659. this._resetVertexBufferBinding();
  5660. };
  5661. Engine.prototype._resetIndexBufferBinding = function () {
  5662. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5663. this._cachedIndexBuffer = null;
  5664. };
  5665. Engine.prototype.createIndexBuffer = function (indices) {
  5666. var vbo = this._gl.createBuffer();
  5667. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5668. // Check for 32 bits indices
  5669. var arrayBuffer;
  5670. var need32Bits = false;
  5671. if (this._caps.uintIndices) {
  5672. for (var index = 0; index < indices.length; index++) {
  5673. if (indices[index] > 65535) {
  5674. need32Bits = true;
  5675. break;
  5676. }
  5677. }
  5678. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5679. }
  5680. else {
  5681. arrayBuffer = new Uint16Array(indices);
  5682. }
  5683. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5684. this._resetIndexBufferBinding();
  5685. vbo.references = 1;
  5686. vbo.is32Bits = need32Bits;
  5687. return vbo;
  5688. };
  5689. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5690. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5691. this._cachedVertexBuffers = vertexBuffer;
  5692. this._cachedEffectForVertexBuffers = effect;
  5693. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5694. var offset = 0;
  5695. for (var index = 0; index < vertexDeclaration.length; index++) {
  5696. var order = effect.getAttributeLocation(index);
  5697. if (order >= 0) {
  5698. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5699. }
  5700. offset += vertexDeclaration[index] * 4;
  5701. }
  5702. }
  5703. if (this._cachedIndexBuffer !== indexBuffer) {
  5704. this._cachedIndexBuffer = indexBuffer;
  5705. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5706. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5707. }
  5708. };
  5709. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5710. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5711. this._cachedVertexBuffers = vertexBuffers;
  5712. this._cachedEffectForVertexBuffers = effect;
  5713. var attributes = effect.getAttributesNames();
  5714. for (var index = 0; index < attributes.length; index++) {
  5715. var order = effect.getAttributeLocation(index);
  5716. if (order >= 0) {
  5717. var vertexBuffer = vertexBuffers[attributes[index]];
  5718. if (!vertexBuffer) {
  5719. continue;
  5720. }
  5721. var stride = vertexBuffer.getStrideSize();
  5722. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5723. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5724. }
  5725. }
  5726. }
  5727. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5728. this._cachedIndexBuffer = indexBuffer;
  5729. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5730. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5731. }
  5732. };
  5733. Engine.prototype._releaseBuffer = function (buffer) {
  5734. buffer.references--;
  5735. if (buffer.references === 0) {
  5736. this._gl.deleteBuffer(buffer);
  5737. return true;
  5738. }
  5739. return false;
  5740. };
  5741. Engine.prototype.createInstancesBuffer = function (capacity) {
  5742. var buffer = this._gl.createBuffer();
  5743. buffer.capacity = capacity;
  5744. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5745. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5746. return buffer;
  5747. };
  5748. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5749. this._gl.deleteBuffer(buffer);
  5750. };
  5751. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5752. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5753. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5754. for (var index = 0; index < 4; index++) {
  5755. var offsetLocation = offsetLocations[index];
  5756. this._gl.enableVertexAttribArray(offsetLocation);
  5757. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5758. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5759. }
  5760. };
  5761. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5762. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5763. for (var index = 0; index < 4; index++) {
  5764. var offsetLocation = offsetLocations[index];
  5765. this._gl.disableVertexAttribArray(offsetLocation);
  5766. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5767. }
  5768. };
  5769. Engine.prototype.applyStates = function () {
  5770. this._depthCullingState.apply(this._gl);
  5771. this._alphaState.apply(this._gl);
  5772. };
  5773. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5774. // Apply states
  5775. this.applyStates();
  5776. this._drawCalls++;
  5777. // Render
  5778. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5779. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5780. if (instancesCount) {
  5781. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5782. return;
  5783. }
  5784. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5785. };
  5786. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5787. // Apply states
  5788. this.applyStates();
  5789. this._drawCalls++;
  5790. if (instancesCount) {
  5791. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5792. return;
  5793. }
  5794. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5795. };
  5796. // Shaders
  5797. Engine.prototype._releaseEffect = function (effect) {
  5798. if (this._compiledEffects[effect._key]) {
  5799. delete this._compiledEffects[effect._key];
  5800. if (effect.getProgram()) {
  5801. this._gl.deleteProgram(effect.getProgram());
  5802. }
  5803. }
  5804. };
  5805. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5806. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5807. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5808. var name = vertex + "+" + fragment + "@" + defines;
  5809. if (this._compiledEffects[name]) {
  5810. return this._compiledEffects[name];
  5811. }
  5812. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5813. effect._key = name;
  5814. this._compiledEffects[name] = effect;
  5815. return effect;
  5816. };
  5817. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5818. if (uniformsNames === void 0) { uniformsNames = []; }
  5819. if (samplers === void 0) { samplers = []; }
  5820. if (defines === void 0) { defines = ""; }
  5821. return this.createEffect({
  5822. vertex: "particles",
  5823. fragmentElement: fragmentName
  5824. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5825. };
  5826. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5827. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5828. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5829. var shaderProgram = this._gl.createProgram();
  5830. this._gl.attachShader(shaderProgram, vertexShader);
  5831. this._gl.attachShader(shaderProgram, fragmentShader);
  5832. this._gl.linkProgram(shaderProgram);
  5833. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5834. if (!linked) {
  5835. var error = this._gl.getProgramInfoLog(shaderProgram);
  5836. if (error) {
  5837. throw new Error(error);
  5838. }
  5839. }
  5840. this._gl.deleteShader(vertexShader);
  5841. this._gl.deleteShader(fragmentShader);
  5842. return shaderProgram;
  5843. };
  5844. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5845. var results = [];
  5846. for (var index = 0; index < uniformsNames.length; index++) {
  5847. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5848. }
  5849. return results;
  5850. };
  5851. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5852. var results = [];
  5853. for (var index = 0; index < attributesNames.length; index++) {
  5854. try {
  5855. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5856. }
  5857. catch (e) {
  5858. results.push(-1);
  5859. }
  5860. }
  5861. return results;
  5862. };
  5863. Engine.prototype.enableEffect = function (effect) {
  5864. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5865. if (effect && effect.onBind) {
  5866. effect.onBind(effect);
  5867. }
  5868. return;
  5869. }
  5870. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5871. // Use program
  5872. this._gl.useProgram(effect.getProgram());
  5873. for (var i in this._vertexAttribArrays) {
  5874. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5875. continue;
  5876. }
  5877. this._vertexAttribArrays[i] = false;
  5878. this._gl.disableVertexAttribArray(i);
  5879. }
  5880. var attributesCount = effect.getAttributesCount();
  5881. for (var index = 0; index < attributesCount; index++) {
  5882. // Attributes
  5883. var order = effect.getAttributeLocation(index);
  5884. if (order >= 0) {
  5885. this._vertexAttribArrays[order] = true;
  5886. this._gl.enableVertexAttribArray(order);
  5887. }
  5888. }
  5889. this._currentEffect = effect;
  5890. if (effect.onBind) {
  5891. effect.onBind(effect);
  5892. }
  5893. };
  5894. Engine.prototype.setArray = function (uniform, array) {
  5895. if (!uniform)
  5896. return;
  5897. this._gl.uniform1fv(uniform, array);
  5898. };
  5899. Engine.prototype.setArray2 = function (uniform, array) {
  5900. if (!uniform || array.length % 2 !== 0)
  5901. return;
  5902. this._gl.uniform2fv(uniform, array);
  5903. };
  5904. Engine.prototype.setArray3 = function (uniform, array) {
  5905. if (!uniform || array.length % 3 !== 0)
  5906. return;
  5907. this._gl.uniform3fv(uniform, array);
  5908. };
  5909. Engine.prototype.setArray4 = function (uniform, array) {
  5910. if (!uniform || array.length % 4 !== 0)
  5911. return;
  5912. this._gl.uniform4fv(uniform, array);
  5913. };
  5914. Engine.prototype.setMatrices = function (uniform, matrices) {
  5915. if (!uniform)
  5916. return;
  5917. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5918. };
  5919. Engine.prototype.setMatrix = function (uniform, matrix) {
  5920. if (!uniform)
  5921. return;
  5922. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5923. };
  5924. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5925. if (!uniform)
  5926. return;
  5927. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5928. };
  5929. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5930. if (!uniform)
  5931. return;
  5932. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5933. };
  5934. Engine.prototype.setFloat = function (uniform, value) {
  5935. if (!uniform)
  5936. return;
  5937. this._gl.uniform1f(uniform, value);
  5938. };
  5939. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5940. if (!uniform)
  5941. return;
  5942. this._gl.uniform2f(uniform, x, y);
  5943. };
  5944. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5945. if (!uniform)
  5946. return;
  5947. this._gl.uniform3f(uniform, x, y, z);
  5948. };
  5949. Engine.prototype.setBool = function (uniform, bool) {
  5950. if (!uniform)
  5951. return;
  5952. this._gl.uniform1i(uniform, bool);
  5953. };
  5954. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5955. if (!uniform)
  5956. return;
  5957. this._gl.uniform4f(uniform, x, y, z, w);
  5958. };
  5959. Engine.prototype.setColor3 = function (uniform, color3) {
  5960. if (!uniform)
  5961. return;
  5962. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5963. };
  5964. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5965. if (!uniform)
  5966. return;
  5967. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5968. };
  5969. // States
  5970. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  5971. if (zOffset === void 0) { zOffset = 0; }
  5972. if (reverseSide === void 0) { reverseSide = false; }
  5973. // Culling
  5974. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  5975. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  5976. var cullFace = this.cullBackFaces ? showSide : hideSide;
  5977. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  5978. if (culling) {
  5979. this._depthCullingState.cullFace = cullFace;
  5980. this._depthCullingState.cull = true;
  5981. }
  5982. else {
  5983. this._depthCullingState.cull = false;
  5984. }
  5985. }
  5986. // Z offset
  5987. this._depthCullingState.zOffset = zOffset;
  5988. };
  5989. Engine.prototype.setDepthBuffer = function (enable) {
  5990. this._depthCullingState.depthTest = enable;
  5991. };
  5992. Engine.prototype.getDepthWrite = function () {
  5993. return this._depthCullingState.depthMask;
  5994. };
  5995. Engine.prototype.setDepthWrite = function (enable) {
  5996. this._depthCullingState.depthMask = enable;
  5997. };
  5998. Engine.prototype.setColorWrite = function (enable) {
  5999. this._gl.colorMask(enable, enable, enable, enable);
  6000. };
  6001. Engine.prototype.setAlphaMode = function (mode) {
  6002. if (this._alphaMode === mode) {
  6003. return;
  6004. }
  6005. switch (mode) {
  6006. case Engine.ALPHA_DISABLE:
  6007. this.setDepthWrite(true);
  6008. this._alphaState.alphaBlend = false;
  6009. break;
  6010. case Engine.ALPHA_COMBINE:
  6011. this.setDepthWrite(false);
  6012. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6013. this._alphaState.alphaBlend = true;
  6014. break;
  6015. case Engine.ALPHA_ONEONE:
  6016. this.setDepthWrite(false);
  6017. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6018. this._alphaState.alphaBlend = true;
  6019. break;
  6020. case Engine.ALPHA_ADD:
  6021. this.setDepthWrite(false);
  6022. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6023. this._alphaState.alphaBlend = true;
  6024. break;
  6025. case Engine.ALPHA_SUBTRACT:
  6026. this.setDepthWrite(false);
  6027. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6028. this._alphaState.alphaBlend = true;
  6029. break;
  6030. case Engine.ALPHA_MULTIPLY:
  6031. this.setDepthWrite(false);
  6032. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6033. this._alphaState.alphaBlend = true;
  6034. break;
  6035. case Engine.ALPHA_MAXIMIZED:
  6036. this.setDepthWrite(false);
  6037. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6038. this._alphaState.alphaBlend = true;
  6039. break;
  6040. }
  6041. this._alphaMode = mode;
  6042. };
  6043. Engine.prototype.getAlphaMode = function () {
  6044. return this._alphaMode;
  6045. };
  6046. Engine.prototype.setAlphaTesting = function (enable) {
  6047. this._alphaTest = enable;
  6048. };
  6049. Engine.prototype.getAlphaTesting = function () {
  6050. return this._alphaTest;
  6051. };
  6052. // Textures
  6053. Engine.prototype.wipeCaches = function () {
  6054. this.resetTextureCache();
  6055. this._currentEffect = null;
  6056. this._depthCullingState.reset();
  6057. this._alphaState.reset();
  6058. this._cachedVertexBuffers = null;
  6059. this._cachedIndexBuffer = null;
  6060. this._cachedEffectForVertexBuffers = null;
  6061. };
  6062. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6063. var gl = this._gl;
  6064. gl.bindTexture(gl.TEXTURE_2D, texture);
  6065. var magFilter = gl.NEAREST;
  6066. var minFilter = gl.NEAREST;
  6067. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6068. magFilter = gl.LINEAR;
  6069. minFilter = gl.LINEAR;
  6070. }
  6071. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6072. magFilter = gl.LINEAR;
  6073. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6074. }
  6075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6077. gl.bindTexture(gl.TEXTURE_2D, null);
  6078. texture.samplingMode = samplingMode;
  6079. };
  6080. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6081. var _this = this;
  6082. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6083. if (onLoad === void 0) { onLoad = null; }
  6084. if (onError === void 0) { onError = null; }
  6085. if (buffer === void 0) { buffer = null; }
  6086. var texture = this._gl.createTexture();
  6087. var extension;
  6088. var fromData = false;
  6089. if (url.substr(0, 5) === "data:") {
  6090. fromData = true;
  6091. }
  6092. if (!fromData)
  6093. extension = url.substr(url.length - 4, 4).toLowerCase();
  6094. else {
  6095. var oldUrl = url;
  6096. fromData = oldUrl.split(':');
  6097. url = oldUrl;
  6098. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6099. }
  6100. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6101. var isTGA = (extension === ".tga");
  6102. scene._addPendingData(texture);
  6103. texture.url = url;
  6104. texture.noMipmap = noMipmap;
  6105. texture.references = 1;
  6106. texture.samplingMode = samplingMode;
  6107. this._loadedTexturesCache.push(texture);
  6108. var onerror = function () {
  6109. scene._removePendingData(texture);
  6110. if (onError) {
  6111. onError();
  6112. }
  6113. };
  6114. var callback;
  6115. if (isTGA) {
  6116. callback = function (arrayBuffer) {
  6117. var data = new Uint8Array(arrayBuffer);
  6118. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6119. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6120. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6121. if (onLoad) {
  6122. onLoad();
  6123. }
  6124. }, samplingMode);
  6125. };
  6126. if (!(fromData instanceof Array))
  6127. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6128. callback(arrayBuffer);
  6129. }, onerror, scene.database, true);
  6130. else
  6131. callback(buffer);
  6132. }
  6133. else if (isDDS) {
  6134. callback = function (data) {
  6135. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6136. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6137. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6138. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6139. if (onLoad) {
  6140. onLoad();
  6141. }
  6142. }, samplingMode);
  6143. };
  6144. if (!(fromData instanceof Array))
  6145. BABYLON.Tools.LoadFile(url, function (data) {
  6146. callback(data);
  6147. }, onerror, scene.database, true);
  6148. else
  6149. callback(buffer);
  6150. }
  6151. else {
  6152. var onload = function (img) {
  6153. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6154. var isPot = (img.width === potWidth && img.height === potHeight);
  6155. if (!isPot) {
  6156. _this._prepareWorkingCanvas();
  6157. _this._workingCanvas.width = potWidth;
  6158. _this._workingCanvas.height = potHeight;
  6159. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6160. _this._workingContext.imageSmoothingEnabled = false;
  6161. _this._workingContext.mozImageSmoothingEnabled = false;
  6162. _this._workingContext.oImageSmoothingEnabled = false;
  6163. _this._workingContext.webkitImageSmoothingEnabled = false;
  6164. _this._workingContext.msImageSmoothingEnabled = false;
  6165. }
  6166. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6167. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6168. _this._workingContext.imageSmoothingEnabled = true;
  6169. _this._workingContext.mozImageSmoothingEnabled = true;
  6170. _this._workingContext.oImageSmoothingEnabled = true;
  6171. _this._workingContext.webkitImageSmoothingEnabled = true;
  6172. _this._workingContext.msImageSmoothingEnabled = true;
  6173. }
  6174. }
  6175. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6176. if (onLoad) {
  6177. onLoad();
  6178. }
  6179. }, samplingMode);
  6180. };
  6181. if (!(fromData instanceof Array))
  6182. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6183. else
  6184. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6185. }
  6186. return texture;
  6187. };
  6188. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6189. if (compression === void 0) { compression = null; }
  6190. var internalFormat = this._gl.RGBA;
  6191. switch (format) {
  6192. case Engine.TEXTUREFORMAT_ALPHA:
  6193. internalFormat = this._gl.ALPHA;
  6194. break;
  6195. case Engine.TEXTUREFORMAT_LUMINANCE:
  6196. internalFormat = this._gl.LUMINANCE;
  6197. break;
  6198. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6199. internalFormat = this._gl.LUMINANCE_ALPHA;
  6200. break;
  6201. case Engine.TEXTUREFORMAT_RGB:
  6202. internalFormat = this._gl.RGB;
  6203. break;
  6204. case Engine.TEXTUREFORMAT_RGBA:
  6205. internalFormat = this._gl.RGBA;
  6206. break;
  6207. }
  6208. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6209. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6210. if (compression) {
  6211. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6212. }
  6213. else {
  6214. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6215. }
  6216. if (texture.generateMipMaps) {
  6217. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6218. }
  6219. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6220. this.resetTextureCache();
  6221. texture.isReady = true;
  6222. };
  6223. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6224. if (compression === void 0) { compression = null; }
  6225. var texture = this._gl.createTexture();
  6226. texture._baseWidth = width;
  6227. texture._baseHeight = height;
  6228. texture._width = width;
  6229. texture._height = height;
  6230. texture.references = 1;
  6231. this.updateRawTexture(texture, data, format, invertY, compression);
  6232. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6233. // Filters
  6234. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6235. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6236. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6237. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6238. texture.samplingMode = samplingMode;
  6239. this._loadedTexturesCache.push(texture);
  6240. return texture;
  6241. };
  6242. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6243. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6244. var texture = this._gl.createTexture();
  6245. texture._baseWidth = width;
  6246. texture._baseHeight = height;
  6247. if (forceExponantOfTwo) {
  6248. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6249. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6250. }
  6251. this.resetTextureCache();
  6252. texture._width = width;
  6253. texture._height = height;
  6254. texture.isReady = false;
  6255. texture.generateMipMaps = generateMipMaps;
  6256. texture.references = 1;
  6257. texture.samplingMode = samplingMode;
  6258. this.updateTextureSamplingMode(samplingMode, texture);
  6259. this._loadedTexturesCache.push(texture);
  6260. return texture;
  6261. };
  6262. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6263. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6264. if (texture.isCube) {
  6265. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6266. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6267. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6268. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6269. }
  6270. else {
  6271. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6272. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6273. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6274. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6275. }
  6276. };
  6277. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6278. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6279. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6280. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6281. if (texture.generateMipMaps) {
  6282. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6283. }
  6284. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6285. this.resetTextureCache();
  6286. texture.isReady = true;
  6287. };
  6288. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6289. if (texture._isDisabled) {
  6290. return;
  6291. }
  6292. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6293. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6294. try {
  6295. // Testing video texture support
  6296. if (this._videoTextureSupported === undefined) {
  6297. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6298. if (this._gl.getError() !== 0) {
  6299. this._videoTextureSupported = false;
  6300. }
  6301. else {
  6302. this._videoTextureSupported = true;
  6303. }
  6304. }
  6305. // Copy video through the current working canvas if video texture is not supported
  6306. if (!this._videoTextureSupported) {
  6307. if (!texture._workingCanvas) {
  6308. texture._workingCanvas = document.createElement("canvas");
  6309. texture._workingContext = texture._workingCanvas.getContext("2d");
  6310. texture._workingCanvas.width = texture._width;
  6311. texture._workingCanvas.height = texture._height;
  6312. }
  6313. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6314. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6315. }
  6316. else {
  6317. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6318. }
  6319. if (texture.generateMipMaps) {
  6320. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6321. }
  6322. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6323. this.resetTextureCache();
  6324. texture.isReady = true;
  6325. }
  6326. catch (ex) {
  6327. // Something unexpected
  6328. // Let's disable the texture
  6329. texture._isDisabled = true;
  6330. }
  6331. };
  6332. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6333. // old version had a "generateMipMaps" arg instead of options.
  6334. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6335. // in the same way, generateDepthBuffer is defaulted to true
  6336. var generateMipMaps = false;
  6337. var generateDepthBuffer = true;
  6338. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6339. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6340. if (options !== undefined) {
  6341. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6342. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6343. type = options.type === undefined ? type : options.type;
  6344. if (options.samplingMode !== undefined) {
  6345. samplingMode = options.samplingMode;
  6346. }
  6347. if (type === Engine.TEXTURETYPE_FLOAT) {
  6348. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6349. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6350. }
  6351. }
  6352. var gl = this._gl;
  6353. var texture = gl.createTexture();
  6354. gl.bindTexture(gl.TEXTURE_2D, texture);
  6355. var width = size.width || size;
  6356. var height = size.height || size;
  6357. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6358. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6359. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6360. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6361. }
  6362. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6363. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6364. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6366. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6367. var depthBuffer;
  6368. // Create the depth buffer
  6369. if (generateDepthBuffer) {
  6370. depthBuffer = gl.createRenderbuffer();
  6371. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6372. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6373. }
  6374. // Create the framebuffer
  6375. var framebuffer = gl.createFramebuffer();
  6376. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6377. if (generateDepthBuffer) {
  6378. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6379. }
  6380. if (generateMipMaps) {
  6381. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6382. }
  6383. // Unbind
  6384. gl.bindTexture(gl.TEXTURE_2D, null);
  6385. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6386. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6387. texture._framebuffer = framebuffer;
  6388. if (generateDepthBuffer) {
  6389. texture._depthBuffer = depthBuffer;
  6390. }
  6391. texture._width = width;
  6392. texture._height = height;
  6393. texture.isReady = true;
  6394. texture.generateMipMaps = generateMipMaps;
  6395. texture.references = 1;
  6396. texture.samplingMode = samplingMode;
  6397. this.resetTextureCache();
  6398. this._loadedTexturesCache.push(texture);
  6399. return texture;
  6400. };
  6401. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6402. var gl = this._gl;
  6403. var texture = gl.createTexture();
  6404. var generateMipMaps = true;
  6405. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6406. if (options !== undefined) {
  6407. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6408. if (options.samplingMode !== undefined) {
  6409. samplingMode = options.samplingMode;
  6410. }
  6411. }
  6412. texture.isCube = true;
  6413. texture.references = 1;
  6414. texture.generateMipMaps = generateMipMaps;
  6415. texture.references = 1;
  6416. texture.samplingMode = samplingMode;
  6417. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6418. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6419. for (var face = 0; face < 6; face++) {
  6420. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6421. }
  6422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6424. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6426. // Create the depth buffer
  6427. var depthBuffer = gl.createRenderbuffer();
  6428. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6429. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6430. // Create the framebuffer
  6431. var framebuffer = gl.createFramebuffer();
  6432. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6433. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6434. // mipmaps
  6435. if (texture.generateMipMaps) {
  6436. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6437. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6438. }
  6439. // Unbind
  6440. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6441. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6442. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6443. texture._framebuffer = framebuffer;
  6444. texture._depthBuffer = depthBuffer;
  6445. this.resetTextureCache();
  6446. texture._width = size;
  6447. texture._height = size;
  6448. texture.isReady = true;
  6449. return texture;
  6450. };
  6451. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6452. var _this = this;
  6453. var gl = this._gl;
  6454. var texture = gl.createTexture();
  6455. texture.isCube = true;
  6456. texture.url = rootUrl;
  6457. texture.references = 1;
  6458. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6459. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6460. if (isDDS) {
  6461. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6462. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6463. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6464. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6465. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6466. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6467. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6468. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6469. }
  6470. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6471. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6472. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6473. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6474. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6475. _this.resetTextureCache();
  6476. texture._width = info.width;
  6477. texture._height = info.height;
  6478. texture.isReady = true;
  6479. }, null, null, true);
  6480. }
  6481. else {
  6482. cascadeLoad(rootUrl, scene, function (imgs) {
  6483. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6484. var height = width;
  6485. _this._prepareWorkingCanvas();
  6486. _this._workingCanvas.width = width;
  6487. _this._workingCanvas.height = height;
  6488. var faces = [
  6489. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6490. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6491. ];
  6492. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6493. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6494. for (var index = 0; index < faces.length; index++) {
  6495. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6496. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6497. }
  6498. if (!noMipmap) {
  6499. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6500. }
  6501. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6502. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6504. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6505. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6506. _this.resetTextureCache();
  6507. texture._width = width;
  6508. texture._height = height;
  6509. texture.isReady = true;
  6510. }, extensions);
  6511. }
  6512. return texture;
  6513. };
  6514. Engine.prototype._releaseTexture = function (texture) {
  6515. var gl = this._gl;
  6516. if (texture._framebuffer) {
  6517. gl.deleteFramebuffer(texture._framebuffer);
  6518. }
  6519. if (texture._depthBuffer) {
  6520. gl.deleteRenderbuffer(texture._depthBuffer);
  6521. }
  6522. gl.deleteTexture(texture);
  6523. // Unbind channels
  6524. this.unbindAllTextures();
  6525. var index = this._loadedTexturesCache.indexOf(texture);
  6526. if (index !== -1) {
  6527. this._loadedTexturesCache.splice(index, 1);
  6528. }
  6529. };
  6530. Engine.prototype.bindSamplers = function (effect) {
  6531. this._gl.useProgram(effect.getProgram());
  6532. var samplers = effect.getSamplers();
  6533. for (var index = 0; index < samplers.length; index++) {
  6534. var uniform = effect.getUniform(samplers[index]);
  6535. this._gl.uniform1i(uniform, index);
  6536. }
  6537. this._currentEffect = null;
  6538. };
  6539. Engine.prototype._bindTexture = function (channel, texture) {
  6540. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6541. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6542. this._activeTexturesCache[channel] = null;
  6543. };
  6544. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6545. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6546. };
  6547. Engine.prototype.unbindAllTextures = function () {
  6548. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6549. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6550. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6551. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6552. this._activeTexturesCache[channel] = null;
  6553. }
  6554. };
  6555. Engine.prototype.setTexture = function (channel, texture) {
  6556. if (channel < 0) {
  6557. return;
  6558. }
  6559. // Not ready?
  6560. if (!texture || !texture.isReady()) {
  6561. if (this._activeTexturesCache[channel] != null) {
  6562. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6563. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6564. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6565. this._activeTexturesCache[channel] = null;
  6566. }
  6567. return;
  6568. }
  6569. // Video
  6570. var alreadyActivated = false;
  6571. if (texture instanceof BABYLON.VideoTexture) {
  6572. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6573. alreadyActivated = true;
  6574. texture.update();
  6575. }
  6576. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6577. texture.delayLoad();
  6578. return;
  6579. }
  6580. if (this._activeTexturesCache[channel] === texture) {
  6581. return;
  6582. }
  6583. this._activeTexturesCache[channel] = texture;
  6584. var internalTexture = texture.getInternalTexture();
  6585. if (!alreadyActivated) {
  6586. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6587. }
  6588. if (internalTexture.isCube) {
  6589. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6590. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6591. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6592. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6593. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6594. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6595. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6596. }
  6597. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6598. }
  6599. else {
  6600. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6601. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6602. internalTexture._cachedWrapU = texture.wrapU;
  6603. switch (texture.wrapU) {
  6604. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6605. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6606. break;
  6607. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6608. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6609. break;
  6610. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6611. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6612. break;
  6613. }
  6614. }
  6615. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6616. internalTexture._cachedWrapV = texture.wrapV;
  6617. switch (texture.wrapV) {
  6618. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6619. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6620. break;
  6621. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6622. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6623. break;
  6624. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6626. break;
  6627. }
  6628. }
  6629. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6630. }
  6631. };
  6632. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6633. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6634. var value = texture.anisotropicFilteringLevel;
  6635. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6636. value = 1;
  6637. }
  6638. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6639. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6640. texture._cachedAnisotropicFilteringLevel = value;
  6641. }
  6642. };
  6643. Engine.prototype.readPixels = function (x, y, width, height) {
  6644. var data = new Uint8Array(height * width * 4);
  6645. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6646. return data;
  6647. };
  6648. Engine.prototype.releaseInternalTexture = function (texture) {
  6649. if (!texture) {
  6650. return;
  6651. }
  6652. texture.references--;
  6653. // Final reference ?
  6654. if (texture.references === 0) {
  6655. var texturesCache = this.getLoadedTexturesCache();
  6656. var index = texturesCache.indexOf(texture);
  6657. if (index > -1) {
  6658. texturesCache.splice(index, 1);
  6659. }
  6660. this._releaseTexture(texture);
  6661. }
  6662. };
  6663. // Dispose
  6664. Engine.prototype.dispose = function () {
  6665. this.hideLoadingUI();
  6666. this.stopRenderLoop();
  6667. // Release scenes
  6668. while (this.scenes.length) {
  6669. this.scenes[0].dispose();
  6670. }
  6671. // Release audio engine
  6672. Engine.audioEngine.dispose();
  6673. // Release effects
  6674. for (var name in this._compiledEffects) {
  6675. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6676. }
  6677. // Unbind
  6678. for (var i in this._vertexAttribArrays) {
  6679. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6680. continue;
  6681. }
  6682. this._gl.disableVertexAttribArray(i);
  6683. }
  6684. this._gl = null;
  6685. // Events
  6686. window.removeEventListener("blur", this._onBlur);
  6687. window.removeEventListener("focus", this._onFocus);
  6688. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6689. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6690. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6691. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6692. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6693. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6694. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6695. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6696. };
  6697. // Loading screen
  6698. Engine.prototype.displayLoadingUI = function () {
  6699. this._loadingScreen.displayLoadingUI();
  6700. };
  6701. Engine.prototype.hideLoadingUI = function () {
  6702. this._loadingScreen.hideLoadingUI();
  6703. };
  6704. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6705. get: function () {
  6706. return this._loadingScreen;
  6707. },
  6708. set: function (loadingScreen) {
  6709. this._loadingScreen = loadingScreen;
  6710. },
  6711. enumerable: true,
  6712. configurable: true
  6713. });
  6714. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6715. set: function (text) {
  6716. this._loadingScreen.loadingUIText = text;
  6717. },
  6718. enumerable: true,
  6719. configurable: true
  6720. });
  6721. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6722. set: function (color) {
  6723. this._loadingScreen.loadingUIBackgroundColor = color;
  6724. },
  6725. enumerable: true,
  6726. configurable: true
  6727. });
  6728. // FPS
  6729. Engine.prototype.getFps = function () {
  6730. return this.fps;
  6731. };
  6732. Engine.prototype.getDeltaTime = function () {
  6733. return this.deltaTime;
  6734. };
  6735. Engine.prototype._measureFps = function () {
  6736. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6737. var length = this.previousFramesDuration.length;
  6738. if (length >= 2) {
  6739. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6740. }
  6741. if (length >= this.fpsRange) {
  6742. if (length > this.fpsRange) {
  6743. this.previousFramesDuration.splice(0, 1);
  6744. length = this.previousFramesDuration.length;
  6745. }
  6746. var sum = 0;
  6747. for (var id = 0; id < length - 1; id++) {
  6748. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6749. }
  6750. this.fps = 1000.0 / (sum / (length - 1));
  6751. }
  6752. };
  6753. // Statics
  6754. Engine.isSupported = function () {
  6755. try {
  6756. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6757. if (navigator.isCocoonJS) {
  6758. return true;
  6759. }
  6760. var tempcanvas = document.createElement("canvas");
  6761. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6762. return gl != null && !!window.WebGLRenderingContext;
  6763. }
  6764. catch (e) {
  6765. return false;
  6766. }
  6767. };
  6768. // Const statics
  6769. Engine._ALPHA_DISABLE = 0;
  6770. Engine._ALPHA_ADD = 1;
  6771. Engine._ALPHA_COMBINE = 2;
  6772. Engine._ALPHA_SUBTRACT = 3;
  6773. Engine._ALPHA_MULTIPLY = 4;
  6774. Engine._ALPHA_MAXIMIZED = 5;
  6775. Engine._ALPHA_ONEONE = 6;
  6776. Engine._DELAYLOADSTATE_NONE = 0;
  6777. Engine._DELAYLOADSTATE_LOADED = 1;
  6778. Engine._DELAYLOADSTATE_LOADING = 2;
  6779. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6780. Engine._TEXTUREFORMAT_ALPHA = 0;
  6781. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6782. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6783. Engine._TEXTUREFORMAT_RGB = 4;
  6784. Engine._TEXTUREFORMAT_RGBA = 5;
  6785. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6786. Engine._TEXTURETYPE_FLOAT = 1;
  6787. // Updatable statics so stick with vars here
  6788. Engine.Epsilon = 0.001;
  6789. Engine.CollisionsEpsilon = 0.001;
  6790. Engine.CodeRepository = "src/";
  6791. Engine.ShadersRepository = "src/Shaders/";
  6792. return Engine;
  6793. })();
  6794. BABYLON.Engine = Engine;
  6795. })(BABYLON || (BABYLON = {}));
  6796. var BABYLON;
  6797. (function (BABYLON) {
  6798. /**
  6799. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6800. */
  6801. var Node = (function () {
  6802. /**
  6803. * @constructor
  6804. * @param {string} name - the name and id to be given to this node
  6805. * @param {BABYLON.Scene} the scene this node will be added to
  6806. */
  6807. function Node(name, scene) {
  6808. this.state = "";
  6809. this.animations = new Array();
  6810. this._childrenFlag = -1;
  6811. this._isEnabled = true;
  6812. this._isReady = true;
  6813. this._currentRenderId = -1;
  6814. this._parentRenderId = -1;
  6815. this.name = name;
  6816. this.id = name;
  6817. this._scene = scene;
  6818. this._initCache();
  6819. }
  6820. Node.prototype.getScene = function () {
  6821. return this._scene;
  6822. };
  6823. Node.prototype.getEngine = function () {
  6824. return this._scene.getEngine();
  6825. };
  6826. // override it in derived class
  6827. Node.prototype.getWorldMatrix = function () {
  6828. return BABYLON.Matrix.Identity();
  6829. };
  6830. // override it in derived class if you add new variables to the cache
  6831. // and call the parent class method
  6832. Node.prototype._initCache = function () {
  6833. this._cache = {};
  6834. this._cache.parent = undefined;
  6835. };
  6836. Node.prototype.updateCache = function (force) {
  6837. if (!force && this.isSynchronized())
  6838. return;
  6839. this._cache.parent = this.parent;
  6840. this._updateCache();
  6841. };
  6842. // override it in derived class if you add new variables to the cache
  6843. // and call the parent class method if !ignoreParentClass
  6844. Node.prototype._updateCache = function (ignoreParentClass) {
  6845. };
  6846. // override it in derived class if you add new variables to the cache
  6847. Node.prototype._isSynchronized = function () {
  6848. return true;
  6849. };
  6850. Node.prototype._markSyncedWithParent = function () {
  6851. this._parentRenderId = this.parent._currentRenderId;
  6852. };
  6853. Node.prototype.isSynchronizedWithParent = function () {
  6854. if (!this.parent) {
  6855. return true;
  6856. }
  6857. if (this._parentRenderId !== this.parent._currentRenderId) {
  6858. return false;
  6859. }
  6860. return this.parent.isSynchronized();
  6861. };
  6862. Node.prototype.isSynchronized = function (updateCache) {
  6863. var check = this.hasNewParent();
  6864. check = check || !this.isSynchronizedWithParent();
  6865. check = check || !this._isSynchronized();
  6866. if (updateCache)
  6867. this.updateCache(true);
  6868. return !check;
  6869. };
  6870. Node.prototype.hasNewParent = function (update) {
  6871. if (this._cache.parent === this.parent)
  6872. return false;
  6873. if (update)
  6874. this._cache.parent = this.parent;
  6875. return true;
  6876. };
  6877. /**
  6878. * Is this node ready to be used/rendered
  6879. * @return {boolean} is it ready
  6880. */
  6881. Node.prototype.isReady = function () {
  6882. return this._isReady;
  6883. };
  6884. /**
  6885. * Is this node enabled.
  6886. * If the node has a parent and is enabled, the parent will be inspected as well.
  6887. * @return {boolean} whether this node (and its parent) is enabled.
  6888. * @see setEnabled
  6889. */
  6890. Node.prototype.isEnabled = function () {
  6891. if (!this._isEnabled) {
  6892. return false;
  6893. }
  6894. if (this.parent) {
  6895. return this.parent.isEnabled();
  6896. }
  6897. return true;
  6898. };
  6899. /**
  6900. * Set the enabled state of this node.
  6901. * @param {boolean} value - the new enabled state
  6902. * @see isEnabled
  6903. */
  6904. Node.prototype.setEnabled = function (value) {
  6905. this._isEnabled = value;
  6906. };
  6907. /**
  6908. * Is this node a descendant of the given node.
  6909. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6910. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6911. * @see parent
  6912. */
  6913. Node.prototype.isDescendantOf = function (ancestor) {
  6914. if (this.parent) {
  6915. if (this.parent === ancestor) {
  6916. return true;
  6917. }
  6918. return this.parent.isDescendantOf(ancestor);
  6919. }
  6920. return false;
  6921. };
  6922. Node.prototype._getDescendants = function (list, results) {
  6923. for (var index = 0; index < list.length; index++) {
  6924. var item = list[index];
  6925. if (item.isDescendantOf(this)) {
  6926. results.push(item);
  6927. }
  6928. }
  6929. };
  6930. /**
  6931. * Will return all nodes that have this node as parent.
  6932. * @return {BABYLON.Node[]} all children nodes of all types.
  6933. */
  6934. Node.prototype.getDescendants = function () {
  6935. var results = [];
  6936. this._getDescendants(this._scene.meshes, results);
  6937. this._getDescendants(this._scene.lights, results);
  6938. this._getDescendants(this._scene.cameras, results);
  6939. return results;
  6940. };
  6941. Node.prototype._setReady = function (state) {
  6942. if (state === this._isReady) {
  6943. return;
  6944. }
  6945. if (!state) {
  6946. this._isReady = false;
  6947. return;
  6948. }
  6949. this._isReady = true;
  6950. if (this.onReady) {
  6951. this.onReady(this);
  6952. }
  6953. };
  6954. Node.prototype.getAnimationByName = function (name) {
  6955. for (var i = 0; i < this.animations.length; i++) {
  6956. var animation = this.animations[i];
  6957. if (animation.name === name) {
  6958. return animation;
  6959. }
  6960. }
  6961. return null;
  6962. };
  6963. return Node;
  6964. })();
  6965. BABYLON.Node = Node;
  6966. })(BABYLON || (BABYLON = {}));
  6967. var BABYLON;
  6968. (function (BABYLON) {
  6969. var FilesInput = (function () {
  6970. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6971. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6972. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6973. this._engine = p_engine;
  6974. this._canvas = p_canvas;
  6975. this._currentScene = p_scene;
  6976. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6977. this._progressCallback = p_progressCallback;
  6978. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6979. this._textureLoadingCallback = p_textureLoadingCallback;
  6980. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6981. }
  6982. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6983. var _this = this;
  6984. if (p_elementToMonitor) {
  6985. this._elementToMonitor = p_elementToMonitor;
  6986. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  6987. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  6988. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  6989. }
  6990. };
  6991. FilesInput.prototype.renderFunction = function () {
  6992. if (this._additionnalRenderLoopLogicCallback) {
  6993. this._additionnalRenderLoopLogicCallback();
  6994. }
  6995. if (this._currentScene) {
  6996. if (this._textureLoadingCallback) {
  6997. var remaining = this._currentScene.getWaitingItemsCount();
  6998. if (remaining > 0) {
  6999. this._textureLoadingCallback(remaining);
  7000. }
  7001. }
  7002. this._currentScene.render();
  7003. }
  7004. };
  7005. FilesInput.prototype.drag = function (e) {
  7006. e.stopPropagation();
  7007. e.preventDefault();
  7008. };
  7009. FilesInput.prototype.drop = function (eventDrop) {
  7010. eventDrop.stopPropagation();
  7011. eventDrop.preventDefault();
  7012. this.loadFiles(eventDrop);
  7013. };
  7014. FilesInput.prototype.loadFiles = function (event) {
  7015. if (this._startingProcessingFilesCallback)
  7016. this._startingProcessingFilesCallback();
  7017. // Handling data transfer via drag'n'drop
  7018. if (event && event.dataTransfer && event.dataTransfer.files) {
  7019. this._filesToLoad = event.dataTransfer.files;
  7020. }
  7021. // Handling files from input files
  7022. if (event && event.target && event.target.files) {
  7023. this._filesToLoad = event.target.files;
  7024. }
  7025. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7026. for (var i = 0; i < this._filesToLoad.length; i++) {
  7027. switch (this._filesToLoad[i].type) {
  7028. case "image/jpeg":
  7029. case "image/png":
  7030. case "image/bmp":
  7031. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7032. break;
  7033. case "image/targa":
  7034. case "image/vnd.ms-dds":
  7035. case "audio/wav":
  7036. case "audio/x-wav":
  7037. case "audio/mp3":
  7038. case "audio/mpeg":
  7039. case "audio/mpeg3":
  7040. case "audio/x-mpeg-3":
  7041. case "audio/ogg":
  7042. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7043. break;
  7044. default:
  7045. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7046. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7047. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7048. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7049. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7050. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7051. this._sceneFileToLoad = this._filesToLoad[i];
  7052. }
  7053. break;
  7054. }
  7055. }
  7056. this.reload();
  7057. }
  7058. };
  7059. FilesInput.prototype.reload = function () {
  7060. var _this = this;
  7061. var that = this;
  7062. // If a ".babylon" file has been provided
  7063. if (this._sceneFileToLoad) {
  7064. if (this._currentScene) {
  7065. if (BABYLON.Tools.errorsCount > 0) {
  7066. BABYLON.Tools.ClearLogCache();
  7067. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7068. }
  7069. this._engine.stopRenderLoop();
  7070. this._currentScene.dispose();
  7071. }
  7072. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7073. that._currentScene = newScene;
  7074. // Wait for textures and shaders to be ready
  7075. that._currentScene.executeWhenReady(function () {
  7076. // Attach camera to canvas inputs
  7077. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7078. that._currentScene.createDefaultCameraOrLight();
  7079. }
  7080. that._currentScene.activeCamera.attachControl(that._canvas);
  7081. if (that._sceneLoadedCallback) {
  7082. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7083. }
  7084. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7085. });
  7086. }, function (progress) {
  7087. if (_this._progressCallback) {
  7088. _this._progressCallback(progress);
  7089. }
  7090. });
  7091. }
  7092. else {
  7093. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7094. }
  7095. };
  7096. FilesInput.FilesTextures = new Array();
  7097. FilesInput.FilesToLoad = new Array();
  7098. return FilesInput;
  7099. })();
  7100. BABYLON.FilesInput = FilesInput;
  7101. })(BABYLON || (BABYLON = {}));
  7102. var BABYLON;
  7103. (function (BABYLON) {
  7104. var IntersectionInfo = (function () {
  7105. function IntersectionInfo(bu, bv, distance) {
  7106. this.bu = bu;
  7107. this.bv = bv;
  7108. this.distance = distance;
  7109. this.faceId = 0;
  7110. this.subMeshId = 0;
  7111. }
  7112. return IntersectionInfo;
  7113. })();
  7114. BABYLON.IntersectionInfo = IntersectionInfo;
  7115. var PickingInfo = (function () {
  7116. function PickingInfo() {
  7117. this.hit = false;
  7118. this.distance = 0;
  7119. this.pickedPoint = null;
  7120. this.pickedMesh = null;
  7121. this.bu = 0;
  7122. this.bv = 0;
  7123. this.faceId = -1;
  7124. this.subMeshId = 0;
  7125. this.pickedSprite = null;
  7126. }
  7127. // Methods
  7128. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7129. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7130. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7131. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7132. return null;
  7133. }
  7134. var indices = this.pickedMesh.getIndices();
  7135. var result;
  7136. if (useVerticesNormals) {
  7137. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7138. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7139. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7140. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7141. normal0 = normal0.scale(this.bu);
  7142. normal1 = normal1.scale(this.bv);
  7143. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7144. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7145. }
  7146. else {
  7147. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7148. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7149. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7150. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7151. var p1p2 = vertex1.subtract(vertex2);
  7152. var p3p2 = vertex3.subtract(vertex2);
  7153. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7154. }
  7155. if (useWorldCoordinates) {
  7156. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7157. }
  7158. return BABYLON.Vector3.Normalize(result);
  7159. };
  7160. PickingInfo.prototype.getTextureCoordinates = function () {
  7161. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7162. return null;
  7163. }
  7164. var indices = this.pickedMesh.getIndices();
  7165. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7166. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7167. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7168. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7169. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7170. uv1 = uv1.scale(this.bu);
  7171. uv2 = uv2.scale(this.bv);
  7172. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7173. };
  7174. return PickingInfo;
  7175. })();
  7176. BABYLON.PickingInfo = PickingInfo;
  7177. })(BABYLON || (BABYLON = {}));
  7178. var BABYLON;
  7179. (function (BABYLON) {
  7180. var BoundingSphere = (function () {
  7181. function BoundingSphere(minimum, maximum) {
  7182. this.minimum = minimum;
  7183. this.maximum = maximum;
  7184. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7185. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7186. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7187. this.radius = distance * 0.5;
  7188. this.centerWorld = BABYLON.Vector3.Zero();
  7189. this._update(BABYLON.Matrix.Identity());
  7190. }
  7191. // Methods
  7192. BoundingSphere.prototype._update = function (world) {
  7193. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7194. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7195. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7196. };
  7197. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7198. for (var i = 0; i < 6; i++) {
  7199. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7200. return false;
  7201. }
  7202. return true;
  7203. };
  7204. BoundingSphere.prototype.intersectsPoint = function (point) {
  7205. var x = this.centerWorld.x - point.x;
  7206. var y = this.centerWorld.y - point.y;
  7207. var z = this.centerWorld.z - point.z;
  7208. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7209. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7210. return false;
  7211. return true;
  7212. };
  7213. // Statics
  7214. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7215. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7216. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7217. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7218. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7219. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7220. return false;
  7221. return true;
  7222. };
  7223. return BoundingSphere;
  7224. })();
  7225. BABYLON.BoundingSphere = BoundingSphere;
  7226. })(BABYLON || (BABYLON = {}));
  7227. var BABYLON;
  7228. (function (BABYLON) {
  7229. var BoundingBox = (function () {
  7230. function BoundingBox(minimum, maximum) {
  7231. this.minimum = minimum;
  7232. this.maximum = maximum;
  7233. this.vectors = new Array();
  7234. this.vectorsWorld = new Array();
  7235. // Bounding vectors
  7236. this.vectors.push(this.minimum.clone());
  7237. this.vectors.push(this.maximum.clone());
  7238. this.vectors.push(this.minimum.clone());
  7239. this.vectors[2].x = this.maximum.x;
  7240. this.vectors.push(this.minimum.clone());
  7241. this.vectors[3].y = this.maximum.y;
  7242. this.vectors.push(this.minimum.clone());
  7243. this.vectors[4].z = this.maximum.z;
  7244. this.vectors.push(this.maximum.clone());
  7245. this.vectors[5].z = this.minimum.z;
  7246. this.vectors.push(this.maximum.clone());
  7247. this.vectors[6].x = this.minimum.x;
  7248. this.vectors.push(this.maximum.clone());
  7249. this.vectors[7].y = this.minimum.y;
  7250. // OBB
  7251. this.center = this.maximum.add(this.minimum).scale(0.5);
  7252. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7253. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7254. // World
  7255. for (var index = 0; index < this.vectors.length; index++) {
  7256. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7257. }
  7258. this.minimumWorld = BABYLON.Vector3.Zero();
  7259. this.maximumWorld = BABYLON.Vector3.Zero();
  7260. this._update(BABYLON.Matrix.Identity());
  7261. }
  7262. // Methods
  7263. BoundingBox.prototype.getWorldMatrix = function () {
  7264. return this._worldMatrix;
  7265. };
  7266. BoundingBox.prototype._update = function (world) {
  7267. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7268. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7269. for (var index = 0; index < this.vectors.length; index++) {
  7270. var v = this.vectorsWorld[index];
  7271. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7272. if (v.x < this.minimumWorld.x)
  7273. this.minimumWorld.x = v.x;
  7274. if (v.y < this.minimumWorld.y)
  7275. this.minimumWorld.y = v.y;
  7276. if (v.z < this.minimumWorld.z)
  7277. this.minimumWorld.z = v.z;
  7278. if (v.x > this.maximumWorld.x)
  7279. this.maximumWorld.x = v.x;
  7280. if (v.y > this.maximumWorld.y)
  7281. this.maximumWorld.y = v.y;
  7282. if (v.z > this.maximumWorld.z)
  7283. this.maximumWorld.z = v.z;
  7284. }
  7285. // OBB
  7286. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7287. this.center.scaleInPlace(0.5);
  7288. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7289. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7290. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7291. this._worldMatrix = world;
  7292. };
  7293. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7294. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7295. };
  7296. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7297. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7298. };
  7299. BoundingBox.prototype.intersectsPoint = function (point) {
  7300. var delta = -BABYLON.Engine.Epsilon;
  7301. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7302. return false;
  7303. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7304. return false;
  7305. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7306. return false;
  7307. return true;
  7308. };
  7309. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7310. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7311. };
  7312. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7313. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7314. return false;
  7315. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7316. return false;
  7317. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7318. return false;
  7319. return true;
  7320. };
  7321. // Statics
  7322. BoundingBox.Intersects = function (box0, box1) {
  7323. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7324. return false;
  7325. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7326. return false;
  7327. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7328. return false;
  7329. return true;
  7330. };
  7331. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7332. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7333. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7334. return (num <= (sphereRadius * sphereRadius));
  7335. };
  7336. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7337. for (var p = 0; p < 6; p++) {
  7338. for (var i = 0; i < 8; i++) {
  7339. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7340. return false;
  7341. }
  7342. }
  7343. }
  7344. return true;
  7345. };
  7346. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7347. for (var p = 0; p < 6; p++) {
  7348. var inCount = 8;
  7349. for (var i = 0; i < 8; i++) {
  7350. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7351. --inCount;
  7352. }
  7353. else {
  7354. break;
  7355. }
  7356. }
  7357. if (inCount === 0)
  7358. return false;
  7359. }
  7360. return true;
  7361. };
  7362. return BoundingBox;
  7363. })();
  7364. BABYLON.BoundingBox = BoundingBox;
  7365. })(BABYLON || (BABYLON = {}));
  7366. var BABYLON;
  7367. (function (BABYLON) {
  7368. var computeBoxExtents = function (axis, box) {
  7369. var p = BABYLON.Vector3.Dot(box.center, axis);
  7370. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7371. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7372. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7373. var r = r0 + r1 + r2;
  7374. return {
  7375. min: p - r,
  7376. max: p + r
  7377. };
  7378. };
  7379. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7380. var axisOverlap = function (axis, box0, box1) {
  7381. var result0 = computeBoxExtents(axis, box0);
  7382. var result1 = computeBoxExtents(axis, box1);
  7383. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7384. };
  7385. var BoundingInfo = (function () {
  7386. function BoundingInfo(minimum, maximum) {
  7387. this.minimum = minimum;
  7388. this.maximum = maximum;
  7389. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7390. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7391. }
  7392. // Methods
  7393. BoundingInfo.prototype._update = function (world) {
  7394. this.boundingBox._update(world);
  7395. this.boundingSphere._update(world);
  7396. };
  7397. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7398. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7399. return false;
  7400. return this.boundingBox.isInFrustum(frustumPlanes);
  7401. };
  7402. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7403. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7404. };
  7405. BoundingInfo.prototype._checkCollision = function (collider) {
  7406. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7407. };
  7408. BoundingInfo.prototype.intersectsPoint = function (point) {
  7409. if (!this.boundingSphere.centerWorld) {
  7410. return false;
  7411. }
  7412. if (!this.boundingSphere.intersectsPoint(point)) {
  7413. return false;
  7414. }
  7415. if (!this.boundingBox.intersectsPoint(point)) {
  7416. return false;
  7417. }
  7418. return true;
  7419. };
  7420. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7421. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7422. return false;
  7423. }
  7424. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7425. return false;
  7426. }
  7427. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7428. return false;
  7429. }
  7430. if (!precise) {
  7431. return true;
  7432. }
  7433. var box0 = this.boundingBox;
  7434. var box1 = boundingInfo.boundingBox;
  7435. if (!axisOverlap(box0.directions[0], box0, box1))
  7436. return false;
  7437. if (!axisOverlap(box0.directions[1], box0, box1))
  7438. return false;
  7439. if (!axisOverlap(box0.directions[2], box0, box1))
  7440. return false;
  7441. if (!axisOverlap(box1.directions[0], box0, box1))
  7442. return false;
  7443. if (!axisOverlap(box1.directions[1], box0, box1))
  7444. return false;
  7445. if (!axisOverlap(box1.directions[2], box0, box1))
  7446. return false;
  7447. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7448. return false;
  7449. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7450. return false;
  7451. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7452. return false;
  7453. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7454. return false;
  7455. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7456. return false;
  7457. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7458. return false;
  7459. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7460. return false;
  7461. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7462. return false;
  7463. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7464. return false;
  7465. return true;
  7466. };
  7467. return BoundingInfo;
  7468. })();
  7469. BABYLON.BoundingInfo = BoundingInfo;
  7470. })(BABYLON || (BABYLON = {}));
  7471. var BABYLON;
  7472. (function (BABYLON) {
  7473. var AbstractMesh = (function (_super) {
  7474. __extends(AbstractMesh, _super);
  7475. function AbstractMesh(name, scene) {
  7476. var _this = this;
  7477. _super.call(this, name, scene);
  7478. // Properties
  7479. this.definedFacingForward = true; // orientation for POV movement & rotation
  7480. this.position = new BABYLON.Vector3(0, 0, 0);
  7481. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7482. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7483. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7484. this.visibility = 1.0;
  7485. this.alphaIndex = Number.MAX_VALUE;
  7486. this.infiniteDistance = false;
  7487. this.isVisible = true;
  7488. this.isPickable = true;
  7489. this.showBoundingBox = false;
  7490. this.showSubMeshesBoundingBox = false;
  7491. this.onDispose = null;
  7492. this.isBlocker = false;
  7493. this.renderingGroupId = 0;
  7494. this.receiveShadows = false;
  7495. this.renderOutline = false;
  7496. this.outlineColor = BABYLON.Color3.Red();
  7497. this.outlineWidth = 0.02;
  7498. this.renderOverlay = false;
  7499. this.overlayColor = BABYLON.Color3.Red();
  7500. this.overlayAlpha = 0.5;
  7501. this.hasVertexAlpha = false;
  7502. this.useVertexColors = true;
  7503. this.applyFog = true;
  7504. this.computeBonesUsingShaders = true;
  7505. this.scalingDeterminant = 1;
  7506. this.numBoneInfluencers = 4;
  7507. this.useOctreeForRenderingSelection = true;
  7508. this.useOctreeForPicking = true;
  7509. this.useOctreeForCollisions = true;
  7510. this.layerMask = 0x0FFFFFFF;
  7511. this.alwaysSelectAsActiveMesh = false;
  7512. // Physics
  7513. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7514. // Collisions
  7515. this._checkCollisions = false;
  7516. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7517. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7518. this._collider = new BABYLON.Collider();
  7519. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7520. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7521. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7522. // Edges
  7523. this.edgesWidth = 1;
  7524. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7525. // Cache
  7526. this._localScaling = BABYLON.Matrix.Zero();
  7527. this._localRotation = BABYLON.Matrix.Zero();
  7528. this._localTranslation = BABYLON.Matrix.Zero();
  7529. this._localBillboard = BABYLON.Matrix.Zero();
  7530. this._localPivotScaling = BABYLON.Matrix.Zero();
  7531. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7532. this._localWorld = BABYLON.Matrix.Zero();
  7533. this._worldMatrix = BABYLON.Matrix.Zero();
  7534. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7535. this._absolutePosition = BABYLON.Vector3.Zero();
  7536. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7537. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7538. this._isDirty = false;
  7539. this._pivotMatrix = BABYLON.Matrix.Identity();
  7540. this._isDisposed = false;
  7541. this._renderId = 0;
  7542. this._intersectionsInProgress = new Array();
  7543. this._onAfterWorldMatrixUpdate = new Array();
  7544. this._isWorldMatrixFrozen = false;
  7545. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7546. if (collidedMesh === void 0) { collidedMesh = null; }
  7547. //TODO move this to the collision coordinator!
  7548. if (_this.getScene().workerCollisions)
  7549. newPosition.multiplyInPlace(_this._collider.radius);
  7550. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7551. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7552. _this.position.addInPlace(_this._diffPositionForCollisions);
  7553. }
  7554. if (_this.onCollide && collidedMesh) {
  7555. _this.onCollide(collidedMesh);
  7556. }
  7557. if (_this.onCollisionPositionChange) {
  7558. _this.onCollisionPositionChange(_this.position);
  7559. }
  7560. };
  7561. scene.addMesh(this);
  7562. }
  7563. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7564. get: function () {
  7565. return AbstractMesh._BILLBOARDMODE_NONE;
  7566. },
  7567. enumerable: true,
  7568. configurable: true
  7569. });
  7570. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7571. get: function () {
  7572. return AbstractMesh._BILLBOARDMODE_X;
  7573. },
  7574. enumerable: true,
  7575. configurable: true
  7576. });
  7577. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7578. get: function () {
  7579. return AbstractMesh._BILLBOARDMODE_Y;
  7580. },
  7581. enumerable: true,
  7582. configurable: true
  7583. });
  7584. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7585. get: function () {
  7586. return AbstractMesh._BILLBOARDMODE_Z;
  7587. },
  7588. enumerable: true,
  7589. configurable: true
  7590. });
  7591. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7592. get: function () {
  7593. return AbstractMesh._BILLBOARDMODE_ALL;
  7594. },
  7595. enumerable: true,
  7596. configurable: true
  7597. });
  7598. // Methods
  7599. AbstractMesh.prototype.disableEdgesRendering = function () {
  7600. if (this._edgesRenderer !== undefined) {
  7601. this._edgesRenderer.dispose();
  7602. this._edgesRenderer = undefined;
  7603. }
  7604. };
  7605. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7606. if (epsilon === void 0) { epsilon = 0.95; }
  7607. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7608. this.disableEdgesRendering();
  7609. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7610. };
  7611. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7612. get: function () {
  7613. return false;
  7614. },
  7615. enumerable: true,
  7616. configurable: true
  7617. });
  7618. AbstractMesh.prototype.getLOD = function (camera) {
  7619. return this;
  7620. };
  7621. AbstractMesh.prototype.getTotalVertices = function () {
  7622. return 0;
  7623. };
  7624. AbstractMesh.prototype.getIndices = function () {
  7625. return null;
  7626. };
  7627. AbstractMesh.prototype.getVerticesData = function (kind) {
  7628. return null;
  7629. };
  7630. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7631. return false;
  7632. };
  7633. AbstractMesh.prototype.getBoundingInfo = function () {
  7634. if (this._masterMesh) {
  7635. return this._masterMesh.getBoundingInfo();
  7636. }
  7637. if (!this._boundingInfo) {
  7638. this._updateBoundingInfo();
  7639. }
  7640. return this._boundingInfo;
  7641. };
  7642. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7643. get: function () {
  7644. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7645. },
  7646. enumerable: true,
  7647. configurable: true
  7648. });
  7649. AbstractMesh.prototype._preActivate = function () {
  7650. };
  7651. AbstractMesh.prototype._activate = function (renderId) {
  7652. this._renderId = renderId;
  7653. };
  7654. AbstractMesh.prototype.getWorldMatrix = function () {
  7655. if (this._masterMesh) {
  7656. return this._masterMesh.getWorldMatrix();
  7657. }
  7658. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7659. this.computeWorldMatrix();
  7660. }
  7661. return this._worldMatrix;
  7662. };
  7663. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7664. get: function () {
  7665. return this._worldMatrix;
  7666. },
  7667. enumerable: true,
  7668. configurable: true
  7669. });
  7670. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7671. get: function () {
  7672. return this._absolutePosition;
  7673. },
  7674. enumerable: true,
  7675. configurable: true
  7676. });
  7677. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7678. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7679. this.computeWorldMatrix(true);
  7680. this._isWorldMatrixFrozen = true;
  7681. };
  7682. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7683. this._isWorldMatrixFrozen = false;
  7684. this.computeWorldMatrix(true);
  7685. };
  7686. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7687. get: function () {
  7688. return this._isWorldMatrixFrozen;
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7694. axis.normalize();
  7695. if (!this.rotationQuaternion) {
  7696. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7697. this.rotation = BABYLON.Vector3.Zero();
  7698. }
  7699. var rotationQuaternion;
  7700. if (!space || space === BABYLON.Space.LOCAL) {
  7701. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7702. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7703. }
  7704. else {
  7705. if (this.parent) {
  7706. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7707. invertParentWorldMatrix.invert();
  7708. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7709. }
  7710. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7711. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7712. }
  7713. };
  7714. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7715. var displacementVector = axis.scale(distance);
  7716. if (!space || space === BABYLON.Space.LOCAL) {
  7717. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7718. this.setPositionWithLocalVector(tempV3);
  7719. }
  7720. else {
  7721. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7722. }
  7723. };
  7724. AbstractMesh.prototype.getAbsolutePosition = function () {
  7725. this.computeWorldMatrix();
  7726. return this._absolutePosition;
  7727. };
  7728. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7729. if (!absolutePosition) {
  7730. return;
  7731. }
  7732. var absolutePositionX;
  7733. var absolutePositionY;
  7734. var absolutePositionZ;
  7735. if (absolutePosition.x === undefined) {
  7736. if (arguments.length < 3) {
  7737. return;
  7738. }
  7739. absolutePositionX = arguments[0];
  7740. absolutePositionY = arguments[1];
  7741. absolutePositionZ = arguments[2];
  7742. }
  7743. else {
  7744. absolutePositionX = absolutePosition.x;
  7745. absolutePositionY = absolutePosition.y;
  7746. absolutePositionZ = absolutePosition.z;
  7747. }
  7748. if (this.parent) {
  7749. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7750. invertParentWorldMatrix.invert();
  7751. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7752. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7753. }
  7754. else {
  7755. this.position.x = absolutePositionX;
  7756. this.position.y = absolutePositionY;
  7757. this.position.z = absolutePositionZ;
  7758. }
  7759. };
  7760. // ================================== Point of View Movement =================================
  7761. /**
  7762. * Perform relative position change from the point of view of behind the front of the mesh.
  7763. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7764. * Supports definition of mesh facing forward or backward.
  7765. * @param {number} amountRight
  7766. * @param {number} amountUp
  7767. * @param {number} amountForward
  7768. */
  7769. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7770. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7771. };
  7772. /**
  7773. * Calculate relative position change from the point of view of behind the front of the mesh.
  7774. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7775. * Supports definition of mesh facing forward or backward.
  7776. * @param {number} amountRight
  7777. * @param {number} amountUp
  7778. * @param {number} amountForward
  7779. */
  7780. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7781. var rotMatrix = new BABYLON.Matrix();
  7782. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7783. rotQuaternion.toRotationMatrix(rotMatrix);
  7784. var translationDelta = BABYLON.Vector3.Zero();
  7785. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7786. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7787. return translationDelta;
  7788. };
  7789. // ================================== Point of View Rotation =================================
  7790. /**
  7791. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7792. * Supports definition of mesh facing forward or backward.
  7793. * @param {number} flipBack
  7794. * @param {number} twirlClockwise
  7795. * @param {number} tiltRight
  7796. */
  7797. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7798. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7799. };
  7800. /**
  7801. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7802. * Supports definition of mesh facing forward or backward.
  7803. * @param {number} flipBack
  7804. * @param {number} twirlClockwise
  7805. * @param {number} tiltRight
  7806. */
  7807. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7808. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7809. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7810. };
  7811. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7812. this._pivotMatrix = matrix;
  7813. this._cache.pivotMatrixUpdated = true;
  7814. };
  7815. AbstractMesh.prototype.getPivotMatrix = function () {
  7816. return this._pivotMatrix;
  7817. };
  7818. AbstractMesh.prototype._isSynchronized = function () {
  7819. if (this._isDirty) {
  7820. return false;
  7821. }
  7822. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7823. return false;
  7824. if (this._cache.pivotMatrixUpdated) {
  7825. return false;
  7826. }
  7827. if (this.infiniteDistance) {
  7828. return false;
  7829. }
  7830. if (!this._cache.position.equals(this.position))
  7831. return false;
  7832. if (this.rotationQuaternion) {
  7833. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7834. return false;
  7835. }
  7836. else {
  7837. if (!this._cache.rotation.equals(this.rotation))
  7838. return false;
  7839. }
  7840. if (!this._cache.scaling.equals(this.scaling))
  7841. return false;
  7842. return true;
  7843. };
  7844. AbstractMesh.prototype._initCache = function () {
  7845. _super.prototype._initCache.call(this);
  7846. this._cache.localMatrixUpdated = false;
  7847. this._cache.position = BABYLON.Vector3.Zero();
  7848. this._cache.scaling = BABYLON.Vector3.Zero();
  7849. this._cache.rotation = BABYLON.Vector3.Zero();
  7850. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7851. this._cache.billboardMode = -1;
  7852. };
  7853. AbstractMesh.prototype.markAsDirty = function (property) {
  7854. if (property === "rotation") {
  7855. this.rotationQuaternion = null;
  7856. }
  7857. this._currentRenderId = Number.MAX_VALUE;
  7858. this._isDirty = true;
  7859. };
  7860. AbstractMesh.prototype._updateBoundingInfo = function () {
  7861. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7862. this._boundingInfo._update(this.worldMatrixFromCache);
  7863. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7864. };
  7865. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7866. if (!this.subMeshes) {
  7867. return;
  7868. }
  7869. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7870. var subMesh = this.subMeshes[subIndex];
  7871. subMesh.updateBoundingInfo(matrix);
  7872. }
  7873. };
  7874. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7875. if (this._isWorldMatrixFrozen) {
  7876. return this._worldMatrix;
  7877. }
  7878. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7879. return this._worldMatrix;
  7880. }
  7881. this._cache.position.copyFrom(this.position);
  7882. this._cache.scaling.copyFrom(this.scaling);
  7883. this._cache.pivotMatrixUpdated = false;
  7884. this._cache.billboardMode = this.billboardMode;
  7885. this._currentRenderId = this.getScene().getRenderId();
  7886. this._isDirty = false;
  7887. // Scaling
  7888. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7889. // Rotation
  7890. if (this.rotationQuaternion) {
  7891. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7892. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7893. }
  7894. else {
  7895. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7896. this._cache.rotation.copyFrom(this.rotation);
  7897. }
  7898. // Translation
  7899. if (this.infiniteDistance && !this.parent) {
  7900. var camera = this.getScene().activeCamera;
  7901. if (camera) {
  7902. var cameraWorldMatrix = camera.getWorldMatrix();
  7903. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7904. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7905. }
  7906. }
  7907. else {
  7908. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7909. }
  7910. // Composing transformations
  7911. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7912. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7913. // Billboarding
  7914. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7915. var localPosition = this.position.clone();
  7916. var zero = this.getScene().activeCamera.globalPosition.clone();
  7917. if (this.parent && this.parent.position) {
  7918. localPosition.addInPlace(this.parent.position);
  7919. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7920. }
  7921. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7922. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7923. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7924. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7925. zero.y = localPosition.y + 0.001;
  7926. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7927. zero.z = localPosition.z + 0.001;
  7928. }
  7929. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7930. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7931. this._localBillboard.invert();
  7932. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7933. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7934. }
  7935. // Local world
  7936. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7937. // Parent
  7938. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7939. this._markSyncedWithParent();
  7940. if (this._meshToBoneReferal) {
  7941. if (!this._localMeshReferalTransform) {
  7942. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7943. }
  7944. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7945. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7946. }
  7947. else {
  7948. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7949. }
  7950. }
  7951. else {
  7952. this._worldMatrix.copyFrom(this._localWorld);
  7953. }
  7954. // Bounding info
  7955. this._updateBoundingInfo();
  7956. // Absolute position
  7957. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7958. // Callbacks
  7959. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7960. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7961. }
  7962. return this._worldMatrix;
  7963. };
  7964. /**
  7965. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7966. * @param func: callback function to add
  7967. */
  7968. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7969. this._onAfterWorldMatrixUpdate.push(func);
  7970. };
  7971. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7972. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7973. if (index > -1) {
  7974. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7975. }
  7976. };
  7977. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7978. this.computeWorldMatrix();
  7979. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7980. };
  7981. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7982. this.computeWorldMatrix();
  7983. var invLocalWorldMatrix = this._localWorld.clone();
  7984. invLocalWorldMatrix.invert();
  7985. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7986. };
  7987. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7988. this.computeWorldMatrix(true);
  7989. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7990. };
  7991. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7992. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7993. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7994. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7995. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7996. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7997. /// <returns>Mesh oriented towards targetMesh</returns>
  7998. yawCor = yawCor || 0; // default to zero if undefined
  7999. pitchCor = pitchCor || 0;
  8000. rollCor = rollCor || 0;
  8001. var dv = targetPoint.subtract(this.position);
  8002. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8003. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8004. var pitch = Math.atan2(dv.y, len);
  8005. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8006. };
  8007. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8008. this._meshToBoneReferal = affectedMesh;
  8009. this.parent = bone;
  8010. if (bone.getWorldMatrix().determinant() < 0) {
  8011. this.scalingDeterminant *= -1;
  8012. }
  8013. };
  8014. AbstractMesh.prototype.detachFromBone = function () {
  8015. if (this.parent.getWorldMatrix().determinant() < 0) {
  8016. this.scalingDeterminant *= -1;
  8017. }
  8018. this._meshToBoneReferal = null;
  8019. this.parent = null;
  8020. };
  8021. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8022. return this._boundingInfo.isInFrustum(frustumPlanes);
  8023. };
  8024. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8025. if (!camera) {
  8026. camera = this.getScene().activeCamera;
  8027. }
  8028. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8029. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8030. return false;
  8031. }
  8032. return true;
  8033. };
  8034. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8035. if (!this._boundingInfo || !mesh._boundingInfo) {
  8036. return false;
  8037. }
  8038. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8039. };
  8040. AbstractMesh.prototype.intersectsPoint = function (point) {
  8041. if (!this._boundingInfo) {
  8042. return false;
  8043. }
  8044. return this._boundingInfo.intersectsPoint(point);
  8045. };
  8046. // Physics
  8047. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8048. var physicsEngine = this.getScene().getPhysicsEngine();
  8049. if (!physicsEngine) {
  8050. return null;
  8051. }
  8052. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8053. if (impostor.impostor) {
  8054. // Old API
  8055. options = impostor;
  8056. impostor = impostor.impostor;
  8057. }
  8058. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8059. physicsEngine._unregisterMesh(this);
  8060. return null;
  8061. }
  8062. if (!options) {
  8063. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8064. }
  8065. else {
  8066. if (!options.mass && options.mass !== 0)
  8067. options.mass = 0;
  8068. if (!options.friction && options.friction !== 0)
  8069. options.friction = 0.2;
  8070. if (!options.restitution && options.restitution !== 0)
  8071. options.restitution = 0.2;
  8072. }
  8073. this._physicImpostor = impostor;
  8074. this._physicsMass = options.mass;
  8075. this._physicsFriction = options.friction;
  8076. this._physicRestitution = options.restitution;
  8077. return physicsEngine._registerMesh(this, impostor, options);
  8078. };
  8079. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8080. if (!this._physicImpostor) {
  8081. return BABYLON.PhysicsEngine.NoImpostor;
  8082. }
  8083. return this._physicImpostor;
  8084. };
  8085. AbstractMesh.prototype.getPhysicsMass = function () {
  8086. if (!this._physicsMass) {
  8087. return 0;
  8088. }
  8089. return this._physicsMass;
  8090. };
  8091. AbstractMesh.prototype.getPhysicsFriction = function () {
  8092. if (!this._physicsFriction) {
  8093. return 0;
  8094. }
  8095. return this._physicsFriction;
  8096. };
  8097. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8098. if (!this._physicRestitution) {
  8099. return 0;
  8100. }
  8101. return this._physicRestitution;
  8102. };
  8103. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8104. if (!camera) {
  8105. camera = this.getScene().activeCamera;
  8106. }
  8107. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8108. };
  8109. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8110. if (!camera) {
  8111. camera = this.getScene().activeCamera;
  8112. }
  8113. return this.absolutePosition.subtract(camera.position).length();
  8114. };
  8115. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8116. if (!this._physicImpostor) {
  8117. return;
  8118. }
  8119. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8120. };
  8121. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8122. if (!this._physicImpostor) {
  8123. return;
  8124. }
  8125. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8126. };
  8127. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8128. if (!this._physicImpostor) {
  8129. return;
  8130. }
  8131. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8132. };
  8133. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8134. // Collisions
  8135. get: function () {
  8136. return this._checkCollisions;
  8137. },
  8138. set: function (collisionEnabled) {
  8139. this._checkCollisions = collisionEnabled;
  8140. if (this.getScene().workerCollisions) {
  8141. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8142. }
  8143. },
  8144. enumerable: true,
  8145. configurable: true
  8146. });
  8147. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8148. var globalPosition = this.getAbsolutePosition();
  8149. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8150. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8151. this._collider.radius = this.ellipsoid;
  8152. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8153. };
  8154. // Submeshes octree
  8155. /**
  8156. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8157. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8158. */
  8159. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8160. if (maxCapacity === void 0) { maxCapacity = 64; }
  8161. if (maxDepth === void 0) { maxDepth = 2; }
  8162. if (!this._submeshesOctree) {
  8163. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8164. }
  8165. this.computeWorldMatrix(true);
  8166. // Update octree
  8167. var bbox = this.getBoundingInfo().boundingBox;
  8168. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8169. return this._submeshesOctree;
  8170. };
  8171. // Collisions
  8172. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8173. this._generatePointsArray();
  8174. // Transformation
  8175. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8176. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8177. subMesh._lastColliderWorldVertices = [];
  8178. subMesh._trianglePlanes = [];
  8179. var start = subMesh.verticesStart;
  8180. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8181. for (var i = start; i < end; i++) {
  8182. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8183. }
  8184. }
  8185. // Collide
  8186. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8187. if (collider.collisionFound) {
  8188. collider.collidedMesh = this;
  8189. }
  8190. };
  8191. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8192. var subMeshes;
  8193. var len;
  8194. // Octrees
  8195. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8196. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8197. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8198. len = intersections.length;
  8199. subMeshes = intersections.data;
  8200. }
  8201. else {
  8202. subMeshes = this.subMeshes;
  8203. len = subMeshes.length;
  8204. }
  8205. for (var index = 0; index < len; index++) {
  8206. var subMesh = subMeshes[index];
  8207. // Bounding test
  8208. if (len > 1 && !subMesh._checkCollision(collider))
  8209. continue;
  8210. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8211. }
  8212. };
  8213. AbstractMesh.prototype._checkCollision = function (collider) {
  8214. // Bounding box test
  8215. if (!this._boundingInfo._checkCollision(collider))
  8216. return;
  8217. // Transformation matrix
  8218. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8219. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8220. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8221. };
  8222. // Picking
  8223. AbstractMesh.prototype._generatePointsArray = function () {
  8224. return false;
  8225. };
  8226. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8227. var pickingInfo = new BABYLON.PickingInfo();
  8228. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8229. return pickingInfo;
  8230. }
  8231. if (!this._generatePointsArray()) {
  8232. return pickingInfo;
  8233. }
  8234. var intersectInfo = null;
  8235. // Octrees
  8236. var subMeshes;
  8237. var len;
  8238. if (this._submeshesOctree && this.useOctreeForPicking) {
  8239. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8240. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8241. len = intersections.length;
  8242. subMeshes = intersections.data;
  8243. }
  8244. else {
  8245. subMeshes = this.subMeshes;
  8246. len = subMeshes.length;
  8247. }
  8248. for (var index = 0; index < len; index++) {
  8249. var subMesh = subMeshes[index];
  8250. // Bounding test
  8251. if (len > 1 && !subMesh.canIntersects(ray))
  8252. continue;
  8253. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8254. if (currentIntersectInfo) {
  8255. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8256. intersectInfo = currentIntersectInfo;
  8257. intersectInfo.subMeshId = index;
  8258. if (fastCheck) {
  8259. break;
  8260. }
  8261. }
  8262. }
  8263. }
  8264. if (intersectInfo) {
  8265. // Get picked point
  8266. var world = this.getWorldMatrix();
  8267. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8268. var direction = ray.direction.clone();
  8269. direction = direction.scale(intersectInfo.distance);
  8270. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8271. var pickedPoint = worldOrigin.add(worldDirection);
  8272. // Return result
  8273. pickingInfo.hit = true;
  8274. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8275. pickingInfo.pickedPoint = pickedPoint;
  8276. pickingInfo.pickedMesh = this;
  8277. pickingInfo.bu = intersectInfo.bu;
  8278. pickingInfo.bv = intersectInfo.bv;
  8279. pickingInfo.faceId = intersectInfo.faceId;
  8280. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8281. return pickingInfo;
  8282. }
  8283. return pickingInfo;
  8284. };
  8285. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8286. return null;
  8287. };
  8288. AbstractMesh.prototype.releaseSubMeshes = function () {
  8289. if (this.subMeshes) {
  8290. while (this.subMeshes.length) {
  8291. this.subMeshes[0].dispose();
  8292. }
  8293. }
  8294. else {
  8295. this.subMeshes = new Array();
  8296. }
  8297. };
  8298. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8299. var index;
  8300. // Animations
  8301. this.getScene().stopAnimation(this);
  8302. // Physics
  8303. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8304. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8305. }
  8306. // Intersections in progress
  8307. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8308. var other = this._intersectionsInProgress[index];
  8309. var pos = other._intersectionsInProgress.indexOf(this);
  8310. other._intersectionsInProgress.splice(pos, 1);
  8311. }
  8312. this._intersectionsInProgress = [];
  8313. // Edges
  8314. if (this._edgesRenderer) {
  8315. this._edgesRenderer.dispose();
  8316. this._edgesRenderer = null;
  8317. }
  8318. // SubMeshes
  8319. this.releaseSubMeshes();
  8320. // Remove from scene
  8321. this.getScene().removeMesh(this);
  8322. if (!doNotRecurse) {
  8323. // Particles
  8324. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8325. if (this.getScene().particleSystems[index].emitter === this) {
  8326. this.getScene().particleSystems[index].dispose();
  8327. index--;
  8328. }
  8329. }
  8330. // Children
  8331. var objects = this.getScene().meshes.slice(0);
  8332. for (index = 0; index < objects.length; index++) {
  8333. if (objects[index].parent === this) {
  8334. objects[index].dispose();
  8335. }
  8336. }
  8337. }
  8338. else {
  8339. for (index = 0; index < this.getScene().meshes.length; index++) {
  8340. var obj = this.getScene().meshes[index];
  8341. if (obj.parent === this) {
  8342. obj.parent = null;
  8343. obj.computeWorldMatrix(true);
  8344. }
  8345. }
  8346. }
  8347. this._onAfterWorldMatrixUpdate = [];
  8348. this._isDisposed = true;
  8349. // Callback
  8350. if (this.onDispose) {
  8351. this.onDispose();
  8352. }
  8353. };
  8354. // Statics
  8355. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8356. AbstractMesh._BILLBOARDMODE_X = 1;
  8357. AbstractMesh._BILLBOARDMODE_Y = 2;
  8358. AbstractMesh._BILLBOARDMODE_Z = 4;
  8359. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8360. return AbstractMesh;
  8361. })(BABYLON.Node);
  8362. BABYLON.AbstractMesh = AbstractMesh;
  8363. })(BABYLON || (BABYLON = {}));
  8364. var BABYLON;
  8365. (function (BABYLON) {
  8366. var Light = (function (_super) {
  8367. __extends(Light, _super);
  8368. function Light(name, scene) {
  8369. _super.call(this, name, scene);
  8370. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8371. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8372. this.intensity = 1.0;
  8373. this.range = Number.MAX_VALUE;
  8374. this.includeOnlyWithLayerMask = 0;
  8375. this.includedOnlyMeshes = new Array();
  8376. this.excludedMeshes = new Array();
  8377. this.excludeWithLayerMask = 0;
  8378. this._excludedMeshesIds = new Array();
  8379. this._includedOnlyMeshesIds = new Array();
  8380. scene.addLight(this);
  8381. }
  8382. Light.prototype.getShadowGenerator = function () {
  8383. return this._shadowGenerator;
  8384. };
  8385. Light.prototype.getAbsolutePosition = function () {
  8386. return BABYLON.Vector3.Zero();
  8387. };
  8388. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8389. };
  8390. Light.prototype._getWorldMatrix = function () {
  8391. return BABYLON.Matrix.Identity();
  8392. };
  8393. Light.prototype.canAffectMesh = function (mesh) {
  8394. if (!mesh) {
  8395. return true;
  8396. }
  8397. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8398. return false;
  8399. }
  8400. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8401. return false;
  8402. }
  8403. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8404. return false;
  8405. }
  8406. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8407. return false;
  8408. }
  8409. return true;
  8410. };
  8411. Light.prototype.getWorldMatrix = function () {
  8412. this._currentRenderId = this.getScene().getRenderId();
  8413. var worldMatrix = this._getWorldMatrix();
  8414. if (this.parent && this.parent.getWorldMatrix) {
  8415. if (!this._parentedWorldMatrix) {
  8416. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8417. }
  8418. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8419. this._markSyncedWithParent();
  8420. return this._parentedWorldMatrix;
  8421. }
  8422. return worldMatrix;
  8423. };
  8424. Light.prototype.dispose = function () {
  8425. if (this._shadowGenerator) {
  8426. this._shadowGenerator.dispose();
  8427. this._shadowGenerator = null;
  8428. }
  8429. // Animations
  8430. this.getScene().stopAnimation(this);
  8431. // Remove from scene
  8432. this.getScene().removeLight(this);
  8433. };
  8434. return Light;
  8435. })(BABYLON.Node);
  8436. BABYLON.Light = Light;
  8437. })(BABYLON || (BABYLON = {}));
  8438. var BABYLON;
  8439. (function (BABYLON) {
  8440. var PointLight = (function (_super) {
  8441. __extends(PointLight, _super);
  8442. function PointLight(name, position, scene) {
  8443. _super.call(this, name, scene);
  8444. this.position = position;
  8445. }
  8446. PointLight.prototype.getAbsolutePosition = function () {
  8447. return this.transformedPosition ? this.transformedPosition : this.position;
  8448. };
  8449. PointLight.prototype.computeTransformedPosition = function () {
  8450. if (this.parent && this.parent.getWorldMatrix) {
  8451. if (!this.transformedPosition) {
  8452. this.transformedPosition = BABYLON.Vector3.Zero();
  8453. }
  8454. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8455. return true;
  8456. }
  8457. return false;
  8458. };
  8459. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8460. if (this.parent && this.parent.getWorldMatrix) {
  8461. this.computeTransformedPosition();
  8462. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8463. return;
  8464. }
  8465. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8466. };
  8467. PointLight.prototype.needCube = function () {
  8468. return true;
  8469. };
  8470. PointLight.prototype.supportsVSM = function () {
  8471. return false;
  8472. };
  8473. PointLight.prototype.needRefreshPerFrame = function () {
  8474. return false;
  8475. };
  8476. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8477. switch (faceIndex) {
  8478. case 0:
  8479. return new BABYLON.Vector3(1, 0, 0);
  8480. case 1:
  8481. return new BABYLON.Vector3(-1, 0, 0);
  8482. case 2:
  8483. return new BABYLON.Vector3(0, -1, 0);
  8484. case 3:
  8485. return new BABYLON.Vector3(0, 1, 0);
  8486. case 4:
  8487. return new BABYLON.Vector3(0, 0, 1);
  8488. case 5:
  8489. return new BABYLON.Vector3(0, 0, -1);
  8490. }
  8491. return BABYLON.Vector3.Zero();
  8492. };
  8493. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8494. var activeCamera = this.getScene().activeCamera;
  8495. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8496. };
  8497. PointLight.prototype._getWorldMatrix = function () {
  8498. if (!this._worldMatrix) {
  8499. this._worldMatrix = BABYLON.Matrix.Identity();
  8500. }
  8501. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8502. return this._worldMatrix;
  8503. };
  8504. return PointLight;
  8505. })(BABYLON.Light);
  8506. BABYLON.PointLight = PointLight;
  8507. })(BABYLON || (BABYLON = {}));
  8508. var BABYLON;
  8509. (function (BABYLON) {
  8510. var SpotLight = (function (_super) {
  8511. __extends(SpotLight, _super);
  8512. function SpotLight(name, position, direction, angle, exponent, scene) {
  8513. _super.call(this, name, scene);
  8514. this.position = position;
  8515. this.direction = direction;
  8516. this.angle = angle;
  8517. this.exponent = exponent;
  8518. }
  8519. SpotLight.prototype.getAbsolutePosition = function () {
  8520. return this.transformedPosition ? this.transformedPosition : this.position;
  8521. };
  8522. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8523. var activeCamera = this.getScene().activeCamera;
  8524. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8525. };
  8526. SpotLight.prototype.needCube = function () {
  8527. return false;
  8528. };
  8529. SpotLight.prototype.supportsVSM = function () {
  8530. return true;
  8531. };
  8532. SpotLight.prototype.needRefreshPerFrame = function () {
  8533. return false;
  8534. };
  8535. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8536. return this.direction;
  8537. };
  8538. SpotLight.prototype.setDirectionToTarget = function (target) {
  8539. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8540. return this.direction;
  8541. };
  8542. SpotLight.prototype.computeTransformedPosition = function () {
  8543. if (this.parent && this.parent.getWorldMatrix) {
  8544. if (!this.transformedPosition) {
  8545. this.transformedPosition = BABYLON.Vector3.Zero();
  8546. }
  8547. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8548. return true;
  8549. }
  8550. return false;
  8551. };
  8552. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8553. var normalizeDirection;
  8554. if (this.parent && this.parent.getWorldMatrix) {
  8555. if (!this._transformedDirection) {
  8556. this._transformedDirection = BABYLON.Vector3.Zero();
  8557. }
  8558. this.computeTransformedPosition();
  8559. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8560. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8561. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8562. }
  8563. else {
  8564. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8565. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8566. }
  8567. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8568. };
  8569. SpotLight.prototype._getWorldMatrix = function () {
  8570. if (!this._worldMatrix) {
  8571. this._worldMatrix = BABYLON.Matrix.Identity();
  8572. }
  8573. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8574. return this._worldMatrix;
  8575. };
  8576. return SpotLight;
  8577. })(BABYLON.Light);
  8578. BABYLON.SpotLight = SpotLight;
  8579. })(BABYLON || (BABYLON = {}));
  8580. var BABYLON;
  8581. (function (BABYLON) {
  8582. var HemisphericLight = (function (_super) {
  8583. __extends(HemisphericLight, _super);
  8584. function HemisphericLight(name, direction, scene) {
  8585. _super.call(this, name, scene);
  8586. this.direction = direction;
  8587. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8588. }
  8589. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8590. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8591. return this.direction;
  8592. };
  8593. HemisphericLight.prototype.getShadowGenerator = function () {
  8594. return null;
  8595. };
  8596. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8597. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8598. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8599. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8600. };
  8601. HemisphericLight.prototype._getWorldMatrix = function () {
  8602. if (!this._worldMatrix) {
  8603. this._worldMatrix = BABYLON.Matrix.Identity();
  8604. }
  8605. return this._worldMatrix;
  8606. };
  8607. return HemisphericLight;
  8608. })(BABYLON.Light);
  8609. BABYLON.HemisphericLight = HemisphericLight;
  8610. })(BABYLON || (BABYLON = {}));
  8611. var BABYLON;
  8612. (function (BABYLON) {
  8613. var DirectionalLight = (function (_super) {
  8614. __extends(DirectionalLight, _super);
  8615. function DirectionalLight(name, direction, scene) {
  8616. _super.call(this, name, scene);
  8617. this.direction = direction;
  8618. this.shadowOrthoScale = 0.5;
  8619. this.autoUpdateExtends = true;
  8620. // Cache
  8621. this._orthoLeft = Number.MAX_VALUE;
  8622. this._orthoRight = Number.MIN_VALUE;
  8623. this._orthoTop = Number.MIN_VALUE;
  8624. this._orthoBottom = Number.MAX_VALUE;
  8625. this.position = direction.scale(-1);
  8626. }
  8627. DirectionalLight.prototype.getAbsolutePosition = function () {
  8628. return this.transformedPosition ? this.transformedPosition : this.position;
  8629. };
  8630. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8631. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8632. return this.direction;
  8633. };
  8634. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8635. var activeCamera = this.getScene().activeCamera;
  8636. // Check extends
  8637. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8638. var tempVector3 = BABYLON.Vector3.Zero();
  8639. this._orthoLeft = Number.MAX_VALUE;
  8640. this._orthoRight = Number.MIN_VALUE;
  8641. this._orthoTop = Number.MIN_VALUE;
  8642. this._orthoBottom = Number.MAX_VALUE;
  8643. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8644. var mesh = renderList[meshIndex];
  8645. if (!mesh) {
  8646. continue;
  8647. }
  8648. var boundingInfo = mesh.getBoundingInfo();
  8649. if (!boundingInfo) {
  8650. continue;
  8651. }
  8652. var boundingBox = boundingInfo.boundingBox;
  8653. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8654. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8655. if (tempVector3.x < this._orthoLeft)
  8656. this._orthoLeft = tempVector3.x;
  8657. if (tempVector3.y < this._orthoBottom)
  8658. this._orthoBottom = tempVector3.y;
  8659. if (tempVector3.x > this._orthoRight)
  8660. this._orthoRight = tempVector3.x;
  8661. if (tempVector3.y > this._orthoTop)
  8662. this._orthoTop = tempVector3.y;
  8663. }
  8664. }
  8665. }
  8666. var xOffset = this._orthoRight - this._orthoLeft;
  8667. var yOffset = this._orthoTop - this._orthoBottom;
  8668. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8669. };
  8670. DirectionalLight.prototype.supportsVSM = function () {
  8671. return true;
  8672. };
  8673. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8674. return true;
  8675. };
  8676. DirectionalLight.prototype.needCube = function () {
  8677. return false;
  8678. };
  8679. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8680. return this.direction;
  8681. };
  8682. DirectionalLight.prototype.computeTransformedPosition = function () {
  8683. if (this.parent && this.parent.getWorldMatrix) {
  8684. if (!this.transformedPosition) {
  8685. this.transformedPosition = BABYLON.Vector3.Zero();
  8686. }
  8687. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8688. return true;
  8689. }
  8690. return false;
  8691. };
  8692. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8693. if (this.parent && this.parent.getWorldMatrix) {
  8694. if (!this._transformedDirection) {
  8695. this._transformedDirection = BABYLON.Vector3.Zero();
  8696. }
  8697. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8698. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8699. return;
  8700. }
  8701. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8702. };
  8703. DirectionalLight.prototype._getWorldMatrix = function () {
  8704. if (!this._worldMatrix) {
  8705. this._worldMatrix = BABYLON.Matrix.Identity();
  8706. }
  8707. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8708. return this._worldMatrix;
  8709. };
  8710. return DirectionalLight;
  8711. })(BABYLON.Light);
  8712. BABYLON.DirectionalLight = DirectionalLight;
  8713. })(BABYLON || (BABYLON = {}));
  8714. var BABYLON;
  8715. (function (BABYLON) {
  8716. var ShadowGenerator = (function () {
  8717. function ShadowGenerator(mapSize, light) {
  8718. var _this = this;
  8719. // Members
  8720. this._filter = ShadowGenerator.FILTER_NONE;
  8721. this.blurScale = 2;
  8722. this._blurBoxOffset = 0;
  8723. this._bias = 0.00005;
  8724. this._lightDirection = BABYLON.Vector3.Zero();
  8725. this._darkness = 0;
  8726. this._transparencyShadow = false;
  8727. this._viewMatrix = BABYLON.Matrix.Zero();
  8728. this._projectionMatrix = BABYLON.Matrix.Zero();
  8729. this._transformMatrix = BABYLON.Matrix.Zero();
  8730. this._worldViewProjection = BABYLON.Matrix.Zero();
  8731. this._currentFaceIndex = 0;
  8732. this._currentFaceIndexCache = 0;
  8733. this._light = light;
  8734. this._scene = light.getScene();
  8735. this._mapSize = mapSize;
  8736. light._shadowGenerator = this;
  8737. // Render target
  8738. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8739. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8740. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8741. this._shadowMap.anisotropicFilteringLevel = 1;
  8742. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8743. this._shadowMap.renderParticles = false;
  8744. this._shadowMap.onBeforeRender = function (faceIndex) {
  8745. _this._currentFaceIndex = faceIndex;
  8746. };
  8747. this._shadowMap.onAfterUnbind = function () {
  8748. if (!_this.useBlurVarianceShadowMap) {
  8749. return;
  8750. }
  8751. if (!_this._shadowMap2) {
  8752. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8753. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8754. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8755. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8756. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8757. _this._downSamplePostprocess.onApply = function (effect) {
  8758. effect.setTexture("textureSampler", _this._shadowMap);
  8759. };
  8760. _this.blurBoxOffset = 1;
  8761. }
  8762. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8763. };
  8764. // Custom render function
  8765. var renderSubMesh = function (subMesh) {
  8766. var mesh = subMesh.getRenderingMesh();
  8767. var scene = _this._scene;
  8768. var engine = scene.getEngine();
  8769. // Culling
  8770. engine.setState(subMesh.getMaterial().backFaceCulling);
  8771. // Managing instances
  8772. var batch = mesh._getInstancesRenderList(subMesh._id);
  8773. if (batch.mustReturn) {
  8774. return;
  8775. }
  8776. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8777. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8778. engine.enableEffect(_this._effect);
  8779. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8780. var material = subMesh.getMaterial();
  8781. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8782. // Alpha test
  8783. if (material && material.needAlphaTesting()) {
  8784. var alphaTexture = material.getAlphaTestTexture();
  8785. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8786. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8787. }
  8788. // Bones
  8789. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8790. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8791. }
  8792. // Draw
  8793. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8794. }
  8795. else {
  8796. // Need to reset refresh rate of the shadowMap
  8797. _this._shadowMap.resetRefreshCounter();
  8798. }
  8799. };
  8800. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8801. var index;
  8802. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8803. renderSubMesh(opaqueSubMeshes.data[index]);
  8804. }
  8805. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8806. renderSubMesh(alphaTestSubMeshes.data[index]);
  8807. }
  8808. if (_this._transparencyShadow) {
  8809. for (index = 0; index < transparentSubMeshes.length; index++) {
  8810. renderSubMesh(transparentSubMeshes.data[index]);
  8811. }
  8812. }
  8813. };
  8814. this._shadowMap.onClear = function (engine) {
  8815. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8816. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8817. }
  8818. else {
  8819. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8820. }
  8821. };
  8822. }
  8823. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8824. // Static
  8825. get: function () {
  8826. return ShadowGenerator._FILTER_NONE;
  8827. },
  8828. enumerable: true,
  8829. configurable: true
  8830. });
  8831. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8832. get: function () {
  8833. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8834. },
  8835. enumerable: true,
  8836. configurable: true
  8837. });
  8838. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8839. get: function () {
  8840. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8841. },
  8842. enumerable: true,
  8843. configurable: true
  8844. });
  8845. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8846. get: function () {
  8847. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8848. },
  8849. enumerable: true,
  8850. configurable: true
  8851. });
  8852. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8853. get: function () {
  8854. return this._bias;
  8855. },
  8856. set: function (bias) {
  8857. this._bias = bias;
  8858. },
  8859. enumerable: true,
  8860. configurable: true
  8861. });
  8862. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8863. get: function () {
  8864. return this._blurBoxOffset;
  8865. },
  8866. set: function (value) {
  8867. var _this = this;
  8868. if (this._blurBoxOffset === value) {
  8869. return;
  8870. }
  8871. this._blurBoxOffset = value;
  8872. if (this._boxBlurPostprocess) {
  8873. this._boxBlurPostprocess.dispose();
  8874. }
  8875. 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);
  8876. this._boxBlurPostprocess.onApply = function (effect) {
  8877. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8878. };
  8879. },
  8880. enumerable: true,
  8881. configurable: true
  8882. });
  8883. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8884. get: function () {
  8885. return this._filter;
  8886. },
  8887. set: function (value) {
  8888. if (this._filter === value) {
  8889. return;
  8890. }
  8891. this._filter = value;
  8892. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  8893. this._shadowMap.anisotropicFilteringLevel = 16;
  8894. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8895. }
  8896. else {
  8897. this._shadowMap.anisotropicFilteringLevel = 1;
  8898. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8899. }
  8900. },
  8901. enumerable: true,
  8902. configurable: true
  8903. });
  8904. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8905. get: function () {
  8906. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8907. },
  8908. set: function (value) {
  8909. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8910. },
  8911. enumerable: true,
  8912. configurable: true
  8913. });
  8914. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8915. get: function () {
  8916. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8917. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8918. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8919. },
  8920. set: function (value) {
  8921. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8922. },
  8923. enumerable: true,
  8924. configurable: true
  8925. });
  8926. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8927. get: function () {
  8928. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8929. },
  8930. set: function (value) {
  8931. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8932. },
  8933. enumerable: true,
  8934. configurable: true
  8935. });
  8936. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8937. var defines = [];
  8938. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8939. defines.push("#define VSM");
  8940. }
  8941. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8942. var mesh = subMesh.getMesh();
  8943. var material = subMesh.getMaterial();
  8944. // Alpha test
  8945. if (material && material.needAlphaTesting()) {
  8946. defines.push("#define ALPHATEST");
  8947. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8948. attribs.push(BABYLON.VertexBuffer.UVKind);
  8949. defines.push("#define UV1");
  8950. }
  8951. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8952. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8953. defines.push("#define UV2");
  8954. }
  8955. }
  8956. // Bones
  8957. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8958. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8959. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8960. if (mesh.numBoneInfluencers > 4) {
  8961. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  8962. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  8963. }
  8964. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  8965. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8966. }
  8967. else {
  8968. defines.push("#define NUM_BONE_INFLUENCERS 0");
  8969. }
  8970. // Instances
  8971. if (useInstances) {
  8972. defines.push("#define INSTANCES");
  8973. attribs.push("world0");
  8974. attribs.push("world1");
  8975. attribs.push("world2");
  8976. attribs.push("world3");
  8977. }
  8978. // Get correct effect
  8979. var join = defines.join("\n");
  8980. if (this._cachedDefines !== join) {
  8981. this._cachedDefines = join;
  8982. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8983. }
  8984. return this._effect.isReady();
  8985. };
  8986. ShadowGenerator.prototype.getShadowMap = function () {
  8987. return this._shadowMap;
  8988. };
  8989. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8990. if (this._shadowMap2) {
  8991. return this._shadowMap2;
  8992. }
  8993. return this._shadowMap;
  8994. };
  8995. ShadowGenerator.prototype.getLight = function () {
  8996. return this._light;
  8997. };
  8998. // Methods
  8999. ShadowGenerator.prototype.getTransformMatrix = function () {
  9000. var scene = this._scene;
  9001. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9002. return this._transformMatrix;
  9003. }
  9004. this._currentRenderID = scene.getRenderId();
  9005. this._currentFaceIndexCache = this._currentFaceIndex;
  9006. var lightPosition = this._light.position;
  9007. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9008. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9009. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9010. }
  9011. if (this._light.computeTransformedPosition()) {
  9012. lightPosition = this._light.transformedPosition;
  9013. }
  9014. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9015. this._cachedPosition = lightPosition.clone();
  9016. this._cachedDirection = this._lightDirection.clone();
  9017. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9018. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9019. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9020. }
  9021. return this._transformMatrix;
  9022. };
  9023. ShadowGenerator.prototype.getDarkness = function () {
  9024. return this._darkness;
  9025. };
  9026. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9027. if (darkness >= 1.0)
  9028. this._darkness = 1.0;
  9029. else if (darkness <= 0.0)
  9030. this._darkness = 0.0;
  9031. else
  9032. this._darkness = darkness;
  9033. };
  9034. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9035. this._transparencyShadow = hasShadow;
  9036. };
  9037. ShadowGenerator.prototype._packHalf = function (depth) {
  9038. var scale = depth * 255.0;
  9039. var fract = scale - Math.floor(scale);
  9040. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9041. };
  9042. ShadowGenerator.prototype.dispose = function () {
  9043. this._shadowMap.dispose();
  9044. if (this._shadowMap2) {
  9045. this._shadowMap2.dispose();
  9046. }
  9047. if (this._downSamplePostprocess) {
  9048. this._downSamplePostprocess.dispose();
  9049. }
  9050. if (this._boxBlurPostprocess) {
  9051. this._boxBlurPostprocess.dispose();
  9052. }
  9053. };
  9054. ShadowGenerator._FILTER_NONE = 0;
  9055. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9056. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9057. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9058. return ShadowGenerator;
  9059. })();
  9060. BABYLON.ShadowGenerator = ShadowGenerator;
  9061. })(BABYLON || (BABYLON = {}));
  9062. var BABYLON;
  9063. (function (BABYLON) {
  9064. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9065. if (boxMin.x > sphereCenter.x + sphereRadius)
  9066. return false;
  9067. if (sphereCenter.x - sphereRadius > boxMax.x)
  9068. return false;
  9069. if (boxMin.y > sphereCenter.y + sphereRadius)
  9070. return false;
  9071. if (sphereCenter.y - sphereRadius > boxMax.y)
  9072. return false;
  9073. if (boxMin.z > sphereCenter.z + sphereRadius)
  9074. return false;
  9075. if (sphereCenter.z - sphereRadius > boxMax.z)
  9076. return false;
  9077. return true;
  9078. };
  9079. var getLowestRoot = function (a, b, c, maxR) {
  9080. var determinant = b * b - 4.0 * a * c;
  9081. var result = { root: 0, found: false };
  9082. if (determinant < 0)
  9083. return result;
  9084. var sqrtD = Math.sqrt(determinant);
  9085. var r1 = (-b - sqrtD) / (2.0 * a);
  9086. var r2 = (-b + sqrtD) / (2.0 * a);
  9087. if (r1 > r2) {
  9088. var temp = r2;
  9089. r2 = r1;
  9090. r1 = temp;
  9091. }
  9092. if (r1 > 0 && r1 < maxR) {
  9093. result.root = r1;
  9094. result.found = true;
  9095. return result;
  9096. }
  9097. if (r2 > 0 && r2 < maxR) {
  9098. result.root = r2;
  9099. result.found = true;
  9100. return result;
  9101. }
  9102. return result;
  9103. };
  9104. var Collider = (function () {
  9105. function Collider() {
  9106. this.radius = new BABYLON.Vector3(1, 1, 1);
  9107. this.retry = 0;
  9108. this.basePointWorld = BABYLON.Vector3.Zero();
  9109. this.velocityWorld = BABYLON.Vector3.Zero();
  9110. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9111. this._collisionPoint = BABYLON.Vector3.Zero();
  9112. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9113. this._tempVector = BABYLON.Vector3.Zero();
  9114. this._tempVector2 = BABYLON.Vector3.Zero();
  9115. this._tempVector3 = BABYLON.Vector3.Zero();
  9116. this._tempVector4 = BABYLON.Vector3.Zero();
  9117. this._edge = BABYLON.Vector3.Zero();
  9118. this._baseToVertex = BABYLON.Vector3.Zero();
  9119. this._destinationPoint = BABYLON.Vector3.Zero();
  9120. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9121. this._displacementVector = BABYLON.Vector3.Zero();
  9122. }
  9123. // Methods
  9124. Collider.prototype._initialize = function (source, dir, e) {
  9125. this.velocity = dir;
  9126. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9127. this.basePoint = source;
  9128. source.multiplyToRef(this.radius, this.basePointWorld);
  9129. dir.multiplyToRef(this.radius, this.velocityWorld);
  9130. this.velocityWorldLength = this.velocityWorld.length();
  9131. this.epsilon = e;
  9132. this.collisionFound = false;
  9133. };
  9134. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9135. pa.subtractToRef(point, this._tempVector);
  9136. pb.subtractToRef(point, this._tempVector2);
  9137. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9138. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9139. if (d < 0)
  9140. return false;
  9141. pc.subtractToRef(point, this._tempVector3);
  9142. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9143. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9144. if (d < 0)
  9145. return false;
  9146. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9147. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9148. return d >= 0;
  9149. };
  9150. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9151. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9152. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9153. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9154. return false;
  9155. }
  9156. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9157. return false;
  9158. return true;
  9159. };
  9160. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9161. var t0;
  9162. var embeddedInPlane = false;
  9163. //defensive programming, actually not needed.
  9164. if (!trianglePlaneArray) {
  9165. trianglePlaneArray = [];
  9166. }
  9167. if (!trianglePlaneArray[faceIndex]) {
  9168. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9169. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9170. }
  9171. var trianglePlane = trianglePlaneArray[faceIndex];
  9172. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9173. return;
  9174. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9175. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9176. if (normalDotVelocity == 0) {
  9177. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9178. return;
  9179. embeddedInPlane = true;
  9180. t0 = 0;
  9181. }
  9182. else {
  9183. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9184. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9185. if (t0 > t1) {
  9186. var temp = t1;
  9187. t1 = t0;
  9188. t0 = temp;
  9189. }
  9190. if (t0 > 1.0 || t1 < 0.0)
  9191. return;
  9192. if (t0 < 0)
  9193. t0 = 0;
  9194. if (t0 > 1.0)
  9195. t0 = 1.0;
  9196. }
  9197. this._collisionPoint.copyFromFloats(0, 0, 0);
  9198. var found = false;
  9199. var t = 1.0;
  9200. if (!embeddedInPlane) {
  9201. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9202. this.velocity.scaleToRef(t0, this._tempVector);
  9203. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9204. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9205. found = true;
  9206. t = t0;
  9207. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9208. }
  9209. }
  9210. if (!found) {
  9211. var velocitySquaredLength = this.velocity.lengthSquared();
  9212. var a = velocitySquaredLength;
  9213. this.basePoint.subtractToRef(p1, this._tempVector);
  9214. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9215. var c = this._tempVector.lengthSquared() - 1.0;
  9216. var lowestRoot = getLowestRoot(a, b, c, t);
  9217. if (lowestRoot.found) {
  9218. t = lowestRoot.root;
  9219. found = true;
  9220. this._collisionPoint.copyFrom(p1);
  9221. }
  9222. this.basePoint.subtractToRef(p2, this._tempVector);
  9223. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9224. c = this._tempVector.lengthSquared() - 1.0;
  9225. lowestRoot = getLowestRoot(a, b, c, t);
  9226. if (lowestRoot.found) {
  9227. t = lowestRoot.root;
  9228. found = true;
  9229. this._collisionPoint.copyFrom(p2);
  9230. }
  9231. this.basePoint.subtractToRef(p3, this._tempVector);
  9232. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9233. c = this._tempVector.lengthSquared() - 1.0;
  9234. lowestRoot = getLowestRoot(a, b, c, t);
  9235. if (lowestRoot.found) {
  9236. t = lowestRoot.root;
  9237. found = true;
  9238. this._collisionPoint.copyFrom(p3);
  9239. }
  9240. p2.subtractToRef(p1, this._edge);
  9241. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9242. var edgeSquaredLength = this._edge.lengthSquared();
  9243. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9244. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9245. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9246. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9247. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9248. lowestRoot = getLowestRoot(a, b, c, t);
  9249. if (lowestRoot.found) {
  9250. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9251. if (f >= 0.0 && f <= 1.0) {
  9252. t = lowestRoot.root;
  9253. found = true;
  9254. this._edge.scaleInPlace(f);
  9255. p1.addToRef(this._edge, this._collisionPoint);
  9256. }
  9257. }
  9258. p3.subtractToRef(p2, this._edge);
  9259. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9260. edgeSquaredLength = this._edge.lengthSquared();
  9261. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9262. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9263. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9264. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9265. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9266. lowestRoot = getLowestRoot(a, b, c, t);
  9267. if (lowestRoot.found) {
  9268. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9269. if (f >= 0.0 && f <= 1.0) {
  9270. t = lowestRoot.root;
  9271. found = true;
  9272. this._edge.scaleInPlace(f);
  9273. p2.addToRef(this._edge, this._collisionPoint);
  9274. }
  9275. }
  9276. p1.subtractToRef(p3, this._edge);
  9277. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9278. edgeSquaredLength = this._edge.lengthSquared();
  9279. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9280. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9281. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9282. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9283. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9284. lowestRoot = getLowestRoot(a, b, c, t);
  9285. if (lowestRoot.found) {
  9286. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9287. if (f >= 0.0 && f <= 1.0) {
  9288. t = lowestRoot.root;
  9289. found = true;
  9290. this._edge.scaleInPlace(f);
  9291. p3.addToRef(this._edge, this._collisionPoint);
  9292. }
  9293. }
  9294. }
  9295. if (found) {
  9296. var distToCollision = t * this.velocity.length();
  9297. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9298. if (!this.intersectionPoint) {
  9299. this.intersectionPoint = this._collisionPoint.clone();
  9300. }
  9301. else {
  9302. this.intersectionPoint.copyFrom(this._collisionPoint);
  9303. }
  9304. this.nearestDistance = distToCollision;
  9305. this.collisionFound = true;
  9306. }
  9307. }
  9308. };
  9309. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9310. for (var i = indexStart; i < indexEnd; i += 3) {
  9311. var p1 = pts[indices[i] - decal];
  9312. var p2 = pts[indices[i + 1] - decal];
  9313. var p3 = pts[indices[i + 2] - decal];
  9314. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9315. }
  9316. };
  9317. Collider.prototype._getResponse = function (pos, vel) {
  9318. pos.addToRef(vel, this._destinationPoint);
  9319. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9320. this.basePoint.addToRef(vel, pos);
  9321. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9322. this._slidePlaneNormal.normalize();
  9323. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9324. pos.addInPlace(this._displacementVector);
  9325. this.intersectionPoint.addInPlace(this._displacementVector);
  9326. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9327. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9328. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9329. };
  9330. return Collider;
  9331. })();
  9332. BABYLON.Collider = Collider;
  9333. })(BABYLON || (BABYLON = {}));
  9334. var BABYLON;
  9335. (function (BABYLON) {
  9336. //WebWorker code will be inserted to this variable.
  9337. BABYLON.CollisionWorker = "";
  9338. (function (WorkerTaskType) {
  9339. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9340. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9341. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9342. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9343. var WorkerTaskType = BABYLON.WorkerTaskType;
  9344. (function (WorkerReplyType) {
  9345. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9346. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9347. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9348. var WorkerReplyType = BABYLON.WorkerReplyType;
  9349. var CollisionCoordinatorWorker = (function () {
  9350. function CollisionCoordinatorWorker() {
  9351. var _this = this;
  9352. this._scaledPosition = BABYLON.Vector3.Zero();
  9353. this._scaledVelocity = BABYLON.Vector3.Zero();
  9354. this.onMeshUpdated = function (mesh) {
  9355. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9356. };
  9357. this.onGeometryUpdated = function (geometry) {
  9358. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9359. };
  9360. this._afterRender = function () {
  9361. if (!_this._init)
  9362. return;
  9363. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9364. return;
  9365. }
  9366. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9367. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9368. if (_this._runningUpdated > 4) {
  9369. return;
  9370. }
  9371. ++_this._runningUpdated;
  9372. var payload = {
  9373. updatedMeshes: _this._addUpdateMeshesList,
  9374. updatedGeometries: _this._addUpdateGeometriesList,
  9375. removedGeometries: _this._toRemoveGeometryArray,
  9376. removedMeshes: _this._toRemoveMeshesArray
  9377. };
  9378. var message = {
  9379. payload: payload,
  9380. taskType: WorkerTaskType.UPDATE
  9381. };
  9382. var serializable = [];
  9383. for (var id in payload.updatedGeometries) {
  9384. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9385. //prepare transferables
  9386. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9387. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9388. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9389. }
  9390. }
  9391. _this._worker.postMessage(message, serializable);
  9392. _this._addUpdateMeshesList = {};
  9393. _this._addUpdateGeometriesList = {};
  9394. _this._toRemoveGeometryArray = [];
  9395. _this._toRemoveMeshesArray = [];
  9396. };
  9397. this._onMessageFromWorker = function (e) {
  9398. var returnData = e.data;
  9399. if (returnData.error != WorkerReplyType.SUCCESS) {
  9400. //TODO what errors can be returned from the worker?
  9401. BABYLON.Tools.Warn("error returned from worker!");
  9402. return;
  9403. }
  9404. switch (returnData.taskType) {
  9405. case WorkerTaskType.INIT:
  9406. _this._init = true;
  9407. //Update the worked with ALL of the scene's current state
  9408. _this._scene.meshes.forEach(function (mesh) {
  9409. _this.onMeshAdded(mesh);
  9410. });
  9411. _this._scene.getGeometries().forEach(function (geometry) {
  9412. _this.onGeometryAdded(geometry);
  9413. });
  9414. break;
  9415. case WorkerTaskType.UPDATE:
  9416. _this._runningUpdated--;
  9417. break;
  9418. case WorkerTaskType.COLLIDE:
  9419. _this._runningCollisionTask = false;
  9420. var returnPayload = returnData.payload;
  9421. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9422. return;
  9423. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9424. //cleanup
  9425. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9426. break;
  9427. }
  9428. };
  9429. this._collisionsCallbackArray = [];
  9430. this._init = false;
  9431. this._runningUpdated = 0;
  9432. this._runningCollisionTask = false;
  9433. this._addUpdateMeshesList = {};
  9434. this._addUpdateGeometriesList = {};
  9435. this._toRemoveGeometryArray = [];
  9436. this._toRemoveMeshesArray = [];
  9437. }
  9438. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9439. if (!this._init)
  9440. return;
  9441. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9442. return;
  9443. position.divideToRef(collider.radius, this._scaledPosition);
  9444. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9445. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9446. var payload = {
  9447. collider: {
  9448. position: this._scaledPosition.asArray(),
  9449. velocity: this._scaledVelocity.asArray(),
  9450. radius: collider.radius.asArray()
  9451. },
  9452. collisionId: collisionIndex,
  9453. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9454. maximumRetry: maximumRetry
  9455. };
  9456. var message = {
  9457. payload: payload,
  9458. taskType: WorkerTaskType.COLLIDE
  9459. };
  9460. this._worker.postMessage(message);
  9461. };
  9462. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9463. this._scene = scene;
  9464. this._scene.registerAfterRender(this._afterRender);
  9465. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9466. this._worker = new Worker(workerUrl);
  9467. this._worker.onmessage = this._onMessageFromWorker;
  9468. var message = {
  9469. payload: {},
  9470. taskType: WorkerTaskType.INIT
  9471. };
  9472. this._worker.postMessage(message);
  9473. };
  9474. CollisionCoordinatorWorker.prototype.destroy = function () {
  9475. this._scene.unregisterAfterRender(this._afterRender);
  9476. this._worker.terminate();
  9477. };
  9478. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9479. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9480. this.onMeshUpdated(mesh);
  9481. };
  9482. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9483. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9484. };
  9485. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9486. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9487. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9488. this.onGeometryUpdated(geometry);
  9489. };
  9490. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9491. this._toRemoveGeometryArray.push(geometry.id);
  9492. };
  9493. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9494. var submeshes = [];
  9495. if (mesh.subMeshes) {
  9496. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9497. return {
  9498. position: idx,
  9499. verticesStart: sm.verticesStart,
  9500. verticesCount: sm.verticesCount,
  9501. indexStart: sm.indexStart,
  9502. indexCount: sm.indexCount,
  9503. hasMaterial: !!sm.getMaterial(),
  9504. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9505. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9506. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9507. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9508. };
  9509. });
  9510. }
  9511. var geometryId = null;
  9512. if (mesh instanceof BABYLON.Mesh) {
  9513. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9514. }
  9515. else if (mesh instanceof BABYLON.InstancedMesh) {
  9516. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9517. }
  9518. return {
  9519. uniqueId: mesh.uniqueId,
  9520. id: mesh.id,
  9521. name: mesh.name,
  9522. geometryId: geometryId,
  9523. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9524. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9525. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9526. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9527. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9528. subMeshes: submeshes,
  9529. checkCollisions: mesh.checkCollisions
  9530. };
  9531. };
  9532. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9533. return {
  9534. id: geometry.id,
  9535. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9536. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9537. indices: new Int32Array(geometry.getIndices() || []),
  9538. };
  9539. };
  9540. return CollisionCoordinatorWorker;
  9541. })();
  9542. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9543. var CollisionCoordinatorLegacy = (function () {
  9544. function CollisionCoordinatorLegacy() {
  9545. this._scaledPosition = BABYLON.Vector3.Zero();
  9546. this._scaledVelocity = BABYLON.Vector3.Zero();
  9547. this._finalPosition = BABYLON.Vector3.Zero();
  9548. }
  9549. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9550. position.divideToRef(collider.radius, this._scaledPosition);
  9551. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9552. collider.collidedMesh = null;
  9553. collider.retry = 0;
  9554. collider.initialVelocity = this._scaledVelocity;
  9555. collider.initialPosition = this._scaledPosition;
  9556. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9557. this._finalPosition.multiplyInPlace(collider.radius);
  9558. //run the callback
  9559. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9560. };
  9561. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9562. this._scene = scene;
  9563. };
  9564. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9565. //Legacy need no destruction method.
  9566. };
  9567. //No update in legacy mode
  9568. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9569. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9570. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9571. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9572. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9573. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9574. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9575. if (excludedMesh === void 0) { excludedMesh = null; }
  9576. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9577. if (collider.retry >= maximumRetry) {
  9578. finalPosition.copyFrom(position);
  9579. return;
  9580. }
  9581. collider._initialize(position, velocity, closeDistance);
  9582. // Check all meshes
  9583. for (var index = 0; index < this._scene.meshes.length; index++) {
  9584. var mesh = this._scene.meshes[index];
  9585. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9586. mesh._checkCollision(collider);
  9587. }
  9588. }
  9589. if (!collider.collisionFound) {
  9590. position.addToRef(velocity, finalPosition);
  9591. return;
  9592. }
  9593. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9594. collider._getResponse(position, velocity);
  9595. }
  9596. if (velocity.length() <= closeDistance) {
  9597. finalPosition.copyFrom(position);
  9598. return;
  9599. }
  9600. collider.retry++;
  9601. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9602. };
  9603. return CollisionCoordinatorLegacy;
  9604. })();
  9605. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9606. })(BABYLON || (BABYLON = {}));
  9607. var BABYLON;
  9608. (function (BABYLON) {
  9609. var VRCameraMetrics = (function () {
  9610. function VRCameraMetrics() {
  9611. this.compensateDistortion = true;
  9612. }
  9613. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9614. get: function () {
  9615. return this.hResolution / (2 * this.vResolution);
  9616. },
  9617. enumerable: true,
  9618. configurable: true
  9619. });
  9620. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9621. get: function () {
  9622. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9628. get: function () {
  9629. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9630. var h = (4 * meters) / this.hScreenSize;
  9631. return BABYLON.Matrix.Translation(h, 0, 0);
  9632. },
  9633. enumerable: true,
  9634. configurable: true
  9635. });
  9636. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9637. get: function () {
  9638. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9639. var h = (4 * meters) / this.hScreenSize;
  9640. return BABYLON.Matrix.Translation(-h, 0, 0);
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9646. get: function () {
  9647. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9653. get: function () {
  9654. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. VRCameraMetrics.GetDefault = function () {
  9660. var result = new VRCameraMetrics();
  9661. result.hResolution = 1280;
  9662. result.vResolution = 800;
  9663. result.hScreenSize = 0.149759993;
  9664. result.vScreenSize = 0.0935999975;
  9665. result.vScreenCenter = 0.0467999987,
  9666. result.eyeToScreenDistance = 0.0410000011;
  9667. result.lensSeparationDistance = 0.0635000020;
  9668. result.interpupillaryDistance = 0.0640000030;
  9669. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9670. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9671. result.postProcessScaleFactor = 1.714605507808412;
  9672. result.lensCenterOffset = 0.151976421;
  9673. return result;
  9674. };
  9675. return VRCameraMetrics;
  9676. })();
  9677. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9678. var Camera = (function (_super) {
  9679. __extends(Camera, _super);
  9680. function Camera(name, position, scene) {
  9681. _super.call(this, name, scene);
  9682. this.position = position;
  9683. // Members
  9684. this.upVector = BABYLON.Vector3.Up();
  9685. this.orthoLeft = null;
  9686. this.orthoRight = null;
  9687. this.orthoBottom = null;
  9688. this.orthoTop = null;
  9689. this.fov = 0.8;
  9690. this.minZ = 1.0;
  9691. this.maxZ = 10000.0;
  9692. this.inertia = 0.9;
  9693. this.mode = Camera.PERSPECTIVE_CAMERA;
  9694. this.isIntermediate = false;
  9695. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9696. this.layerMask = 0x0FFFFFFF;
  9697. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9698. // Camera rig members
  9699. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9700. this._rigCameras = new Array();
  9701. // Cache
  9702. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9703. this._projectionMatrix = new BABYLON.Matrix();
  9704. this._postProcesses = new Array();
  9705. this._postProcessesTakenIndices = [];
  9706. this._activeMeshes = new BABYLON.SmartArray(256);
  9707. this._globalPosition = BABYLON.Vector3.Zero();
  9708. scene.addCamera(this);
  9709. if (!scene.activeCamera) {
  9710. scene.activeCamera = this;
  9711. }
  9712. }
  9713. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9714. get: function () {
  9715. return Camera._PERSPECTIVE_CAMERA;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9721. get: function () {
  9722. return Camera._ORTHOGRAPHIC_CAMERA;
  9723. },
  9724. enumerable: true,
  9725. configurable: true
  9726. });
  9727. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9728. get: function () {
  9729. return Camera._FOVMODE_VERTICAL_FIXED;
  9730. },
  9731. enumerable: true,
  9732. configurable: true
  9733. });
  9734. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9735. get: function () {
  9736. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9737. },
  9738. enumerable: true,
  9739. configurable: true
  9740. });
  9741. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9742. get: function () {
  9743. return Camera._RIG_MODE_NONE;
  9744. },
  9745. enumerable: true,
  9746. configurable: true
  9747. });
  9748. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9749. get: function () {
  9750. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9751. },
  9752. enumerable: true,
  9753. configurable: true
  9754. });
  9755. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9756. get: function () {
  9757. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9758. },
  9759. enumerable: true,
  9760. configurable: true
  9761. });
  9762. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9763. get: function () {
  9764. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9765. },
  9766. enumerable: true,
  9767. configurable: true
  9768. });
  9769. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9770. get: function () {
  9771. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9777. get: function () {
  9778. return Camera._RIG_MODE_VR;
  9779. },
  9780. enumerable: true,
  9781. configurable: true
  9782. });
  9783. Object.defineProperty(Camera.prototype, "globalPosition", {
  9784. get: function () {
  9785. return this._globalPosition;
  9786. },
  9787. enumerable: true,
  9788. configurable: true
  9789. });
  9790. Camera.prototype.getActiveMeshes = function () {
  9791. return this._activeMeshes;
  9792. };
  9793. Camera.prototype.isActiveMesh = function (mesh) {
  9794. return (this._activeMeshes.indexOf(mesh) !== -1);
  9795. };
  9796. //Cache
  9797. Camera.prototype._initCache = function () {
  9798. _super.prototype._initCache.call(this);
  9799. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9800. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9801. this._cache.mode = undefined;
  9802. this._cache.minZ = undefined;
  9803. this._cache.maxZ = undefined;
  9804. this._cache.fov = undefined;
  9805. this._cache.aspectRatio = undefined;
  9806. this._cache.orthoLeft = undefined;
  9807. this._cache.orthoRight = undefined;
  9808. this._cache.orthoBottom = undefined;
  9809. this._cache.orthoTop = undefined;
  9810. this._cache.renderWidth = undefined;
  9811. this._cache.renderHeight = undefined;
  9812. };
  9813. Camera.prototype._updateCache = function (ignoreParentClass) {
  9814. if (!ignoreParentClass) {
  9815. _super.prototype._updateCache.call(this);
  9816. }
  9817. var engine = this.getEngine();
  9818. this._cache.position.copyFrom(this.position);
  9819. this._cache.upVector.copyFrom(this.upVector);
  9820. this._cache.mode = this.mode;
  9821. this._cache.minZ = this.minZ;
  9822. this._cache.maxZ = this.maxZ;
  9823. this._cache.fov = this.fov;
  9824. this._cache.aspectRatio = engine.getAspectRatio(this);
  9825. this._cache.orthoLeft = this.orthoLeft;
  9826. this._cache.orthoRight = this.orthoRight;
  9827. this._cache.orthoBottom = this.orthoBottom;
  9828. this._cache.orthoTop = this.orthoTop;
  9829. this._cache.renderWidth = engine.getRenderWidth();
  9830. this._cache.renderHeight = engine.getRenderHeight();
  9831. };
  9832. Camera.prototype._updateFromScene = function () {
  9833. this.updateCache();
  9834. this._update();
  9835. };
  9836. // Synchronized
  9837. Camera.prototype._isSynchronized = function () {
  9838. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9839. };
  9840. Camera.prototype._isSynchronizedViewMatrix = function () {
  9841. if (!_super.prototype._isSynchronized.call(this))
  9842. return false;
  9843. return this._cache.position.equals(this.position)
  9844. && this._cache.upVector.equals(this.upVector)
  9845. && this.isSynchronizedWithParent();
  9846. };
  9847. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9848. var check = this._cache.mode === this.mode
  9849. && this._cache.minZ === this.minZ
  9850. && this._cache.maxZ === this.maxZ;
  9851. if (!check) {
  9852. return false;
  9853. }
  9854. var engine = this.getEngine();
  9855. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9856. check = this._cache.fov === this.fov
  9857. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9858. }
  9859. else {
  9860. check = this._cache.orthoLeft === this.orthoLeft
  9861. && this._cache.orthoRight === this.orthoRight
  9862. && this._cache.orthoBottom === this.orthoBottom
  9863. && this._cache.orthoTop === this.orthoTop
  9864. && this._cache.renderWidth === engine.getRenderWidth()
  9865. && this._cache.renderHeight === engine.getRenderHeight();
  9866. }
  9867. return check;
  9868. };
  9869. // Controls
  9870. Camera.prototype.attachControl = function (element) {
  9871. };
  9872. Camera.prototype.detachControl = function (element) {
  9873. };
  9874. Camera.prototype._update = function () {
  9875. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9876. this._updateRigCameras();
  9877. }
  9878. this._checkInputs();
  9879. };
  9880. Camera.prototype._checkInputs = function () {
  9881. };
  9882. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9883. if (insertAt === void 0) { insertAt = null; }
  9884. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9885. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9886. return 0;
  9887. }
  9888. if (insertAt == null || insertAt < 0) {
  9889. this._postProcesses.push(postProcess);
  9890. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9891. return this._postProcesses.length - 1;
  9892. }
  9893. var add = 0;
  9894. var i;
  9895. var start;
  9896. if (this._postProcesses[insertAt]) {
  9897. start = this._postProcesses.length - 1;
  9898. for (i = start; i >= insertAt + 1; --i) {
  9899. this._postProcesses[i + 1] = this._postProcesses[i];
  9900. }
  9901. add = 1;
  9902. }
  9903. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9904. if (this._postProcessesTakenIndices[i] < insertAt) {
  9905. continue;
  9906. }
  9907. start = this._postProcessesTakenIndices.length - 1;
  9908. for (var j = start; j >= i; --j) {
  9909. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9910. }
  9911. this._postProcessesTakenIndices[i] = insertAt;
  9912. break;
  9913. }
  9914. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  9915. this._postProcessesTakenIndices.push(insertAt);
  9916. }
  9917. var result = insertAt + add;
  9918. this._postProcesses[result] = postProcess;
  9919. return result;
  9920. };
  9921. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9922. if (atIndices === void 0) { atIndices = null; }
  9923. var result = [];
  9924. var i;
  9925. var index;
  9926. if (!atIndices) {
  9927. var length = this._postProcesses.length;
  9928. for (i = 0; i < length; i++) {
  9929. if (this._postProcesses[i] !== postProcess) {
  9930. continue;
  9931. }
  9932. delete this._postProcesses[i];
  9933. index = this._postProcessesTakenIndices.indexOf(i);
  9934. this._postProcessesTakenIndices.splice(index, 1);
  9935. }
  9936. }
  9937. else {
  9938. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9939. for (i = 0; i < atIndices.length; i++) {
  9940. var foundPostProcess = this._postProcesses[atIndices[i]];
  9941. if (foundPostProcess !== postProcess) {
  9942. result.push(i);
  9943. continue;
  9944. }
  9945. delete this._postProcesses[atIndices[i]];
  9946. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9947. this._postProcessesTakenIndices.splice(index, 1);
  9948. }
  9949. }
  9950. return result;
  9951. };
  9952. Camera.prototype.getWorldMatrix = function () {
  9953. if (!this._worldMatrix) {
  9954. this._worldMatrix = BABYLON.Matrix.Identity();
  9955. }
  9956. var viewMatrix = this.getViewMatrix();
  9957. viewMatrix.invertToRef(this._worldMatrix);
  9958. return this._worldMatrix;
  9959. };
  9960. Camera.prototype._getViewMatrix = function () {
  9961. return BABYLON.Matrix.Identity();
  9962. };
  9963. Camera.prototype.getViewMatrix = function (force) {
  9964. this._computedViewMatrix = this._computeViewMatrix(force);
  9965. if (!force && this._isSynchronizedViewMatrix()) {
  9966. return this._computedViewMatrix;
  9967. }
  9968. if (!this.parent || !this.parent.getWorldMatrix) {
  9969. this._globalPosition.copyFrom(this.position);
  9970. }
  9971. else {
  9972. if (!this._worldMatrix) {
  9973. this._worldMatrix = BABYLON.Matrix.Identity();
  9974. }
  9975. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9976. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9977. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9978. this._computedViewMatrix.invert();
  9979. this._markSyncedWithParent();
  9980. }
  9981. this._currentRenderId = this.getScene().getRenderId();
  9982. return this._computedViewMatrix;
  9983. };
  9984. Camera.prototype._computeViewMatrix = function (force) {
  9985. if (!force && this._isSynchronizedViewMatrix()) {
  9986. return this._computedViewMatrix;
  9987. }
  9988. this._computedViewMatrix = this._getViewMatrix();
  9989. this._currentRenderId = this.getScene().getRenderId();
  9990. return this._computedViewMatrix;
  9991. };
  9992. Camera.prototype.getProjectionMatrix = function (force) {
  9993. if (!force && this._isSynchronizedProjectionMatrix()) {
  9994. return this._projectionMatrix;
  9995. }
  9996. var engine = this.getEngine();
  9997. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9998. if (this.minZ <= 0) {
  9999. this.minZ = 0.1;
  10000. }
  10001. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10002. return this._projectionMatrix;
  10003. }
  10004. var halfWidth = engine.getRenderWidth() / 2.0;
  10005. var halfHeight = engine.getRenderHeight() / 2.0;
  10006. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10007. return this._projectionMatrix;
  10008. };
  10009. Camera.prototype.dispose = function () {
  10010. // Animations
  10011. this.getScene().stopAnimation(this);
  10012. // Remove from scene
  10013. this.getScene().removeCamera(this);
  10014. while (this._rigCameras.length > 0) {
  10015. this._rigCameras.pop().dispose();
  10016. }
  10017. // Postprocesses
  10018. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10019. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10020. }
  10021. };
  10022. // ---- Camera rigs section ----
  10023. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10024. while (this._rigCameras.length > 0) {
  10025. this._rigCameras.pop().dispose();
  10026. }
  10027. this.cameraRigMode = mode;
  10028. this._cameraRigParams = {};
  10029. switch (this.cameraRigMode) {
  10030. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10031. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10032. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10033. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10034. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10035. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10036. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10037. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10038. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10039. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10040. break;
  10041. }
  10042. var postProcesses = new Array();
  10043. switch (this.cameraRigMode) {
  10044. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10045. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10046. this._rigCameras[0].isIntermediate = true;
  10047. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10048. postProcesses[1].onApply = function (effect) {
  10049. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10050. };
  10051. break;
  10052. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10053. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10054. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10055. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10056. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10057. var secondCamIndex = 1 - firstCamIndex;
  10058. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10059. this._rigCameras[firstCamIndex].isIntermediate = true;
  10060. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10061. break;
  10062. case Camera.RIG_MODE_VR:
  10063. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10064. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10065. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10066. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10067. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10068. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10069. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10070. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10071. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10072. if (metrics.compensateDistortion) {
  10073. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10074. }
  10075. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10076. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10077. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10078. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10079. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10080. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10081. if (metrics.compensateDistortion) {
  10082. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10083. }
  10084. break;
  10085. }
  10086. this._update();
  10087. };
  10088. Camera.prototype._getVRProjectionMatrix = function () {
  10089. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10090. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10091. return this._projectionMatrix;
  10092. };
  10093. Camera.prototype.setCameraRigParameter = function (name, value) {
  10094. this._cameraRigParams[name] = value;
  10095. //provisionnally:
  10096. if (name === "interaxialDistance") {
  10097. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10098. }
  10099. };
  10100. /**
  10101. * May needs to be overridden by children so sub has required properties to be copied
  10102. */
  10103. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10104. return null;
  10105. };
  10106. /**
  10107. * May needs to be overridden by children
  10108. */
  10109. Camera.prototype._updateRigCameras = function () {
  10110. for (var i = 0; i < this._rigCameras.length; i++) {
  10111. this._rigCameras[i].minZ = this.minZ;
  10112. this._rigCameras[i].maxZ = this.maxZ;
  10113. this._rigCameras[i].fov = this.fov;
  10114. }
  10115. // only update viewport when ANAGLYPH
  10116. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10117. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10118. }
  10119. };
  10120. // Statics
  10121. Camera._PERSPECTIVE_CAMERA = 0;
  10122. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10123. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10124. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10125. Camera._RIG_MODE_NONE = 0;
  10126. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10127. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10128. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10129. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10130. Camera._RIG_MODE_VR = 20;
  10131. return Camera;
  10132. })(BABYLON.Node);
  10133. BABYLON.Camera = Camera;
  10134. })(BABYLON || (BABYLON = {}));
  10135. var BABYLON;
  10136. (function (BABYLON) {
  10137. var TargetCamera = (function (_super) {
  10138. __extends(TargetCamera, _super);
  10139. function TargetCamera(name, position, scene) {
  10140. _super.call(this, name, position, scene);
  10141. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10142. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10143. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10144. this.speed = 2.0;
  10145. this.noRotationConstraint = false;
  10146. this.lockedTarget = null;
  10147. this._currentTarget = BABYLON.Vector3.Zero();
  10148. this._viewMatrix = BABYLON.Matrix.Zero();
  10149. this._camMatrix = BABYLON.Matrix.Zero();
  10150. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10151. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10152. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10153. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10154. this._lookAtTemp = BABYLON.Matrix.Zero();
  10155. this._tempMatrix = BABYLON.Matrix.Zero();
  10156. }
  10157. TargetCamera.prototype.getFrontPosition = function (distance) {
  10158. var direction = this.getTarget().subtract(this.position);
  10159. direction.normalize();
  10160. direction.scaleInPlace(distance);
  10161. return this.globalPosition.add(direction);
  10162. };
  10163. TargetCamera.prototype._getLockedTargetPosition = function () {
  10164. if (!this.lockedTarget) {
  10165. return null;
  10166. }
  10167. return this.lockedTarget.position || this.lockedTarget;
  10168. };
  10169. // Cache
  10170. TargetCamera.prototype._initCache = function () {
  10171. _super.prototype._initCache.call(this);
  10172. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10173. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10174. };
  10175. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10176. if (!ignoreParentClass) {
  10177. _super.prototype._updateCache.call(this);
  10178. }
  10179. var lockedTargetPosition = this._getLockedTargetPosition();
  10180. if (!lockedTargetPosition) {
  10181. this._cache.lockedTarget = null;
  10182. }
  10183. else {
  10184. if (!this._cache.lockedTarget) {
  10185. this._cache.lockedTarget = lockedTargetPosition.clone();
  10186. }
  10187. else {
  10188. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10189. }
  10190. }
  10191. this._cache.rotation.copyFrom(this.rotation);
  10192. };
  10193. // Synchronized
  10194. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10195. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10196. return false;
  10197. }
  10198. var lockedTargetPosition = this._getLockedTargetPosition();
  10199. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10200. && this._cache.rotation.equals(this.rotation);
  10201. };
  10202. // Methods
  10203. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10204. var engine = this.getEngine();
  10205. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10206. };
  10207. // Target
  10208. TargetCamera.prototype.setTarget = function (target) {
  10209. this.upVector.normalize();
  10210. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10211. this._camMatrix.invert();
  10212. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10213. var vDir = target.subtract(this.position);
  10214. if (vDir.x >= 0.0) {
  10215. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10216. }
  10217. else {
  10218. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10219. }
  10220. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10221. if (isNaN(this.rotation.x)) {
  10222. this.rotation.x = 0;
  10223. }
  10224. if (isNaN(this.rotation.y)) {
  10225. this.rotation.y = 0;
  10226. }
  10227. if (isNaN(this.rotation.z)) {
  10228. this.rotation.z = 0;
  10229. }
  10230. };
  10231. TargetCamera.prototype.getTarget = function () {
  10232. return this._currentTarget;
  10233. };
  10234. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10235. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10236. };
  10237. TargetCamera.prototype._updatePosition = function () {
  10238. this.position.addInPlace(this.cameraDirection);
  10239. };
  10240. TargetCamera.prototype._checkInputs = function () {
  10241. var needToMove = this._decideIfNeedsToMove();
  10242. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10243. // Move
  10244. if (needToMove) {
  10245. this._updatePosition();
  10246. }
  10247. // Rotate
  10248. if (needToRotate) {
  10249. this.rotation.x += this.cameraRotation.x;
  10250. this.rotation.y += this.cameraRotation.y;
  10251. if (!this.noRotationConstraint) {
  10252. var limit = (Math.PI / 2) * 0.95;
  10253. if (this.rotation.x > limit)
  10254. this.rotation.x = limit;
  10255. if (this.rotation.x < -limit)
  10256. this.rotation.x = -limit;
  10257. }
  10258. }
  10259. // Inertia
  10260. if (needToMove) {
  10261. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10262. this.cameraDirection.x = 0;
  10263. }
  10264. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10265. this.cameraDirection.y = 0;
  10266. }
  10267. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10268. this.cameraDirection.z = 0;
  10269. }
  10270. this.cameraDirection.scaleInPlace(this.inertia);
  10271. }
  10272. if (needToRotate) {
  10273. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10274. this.cameraRotation.x = 0;
  10275. }
  10276. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10277. this.cameraRotation.y = 0;
  10278. }
  10279. this.cameraRotation.scaleInPlace(this.inertia);
  10280. }
  10281. _super.prototype._checkInputs.call(this);
  10282. };
  10283. TargetCamera.prototype._getViewMatrix = function () {
  10284. if (!this.lockedTarget) {
  10285. // Compute
  10286. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10287. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10288. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10289. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10290. this._lookAtTemp.invert();
  10291. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10292. }
  10293. else {
  10294. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10295. }
  10296. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10297. // Computing target and final matrix
  10298. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10299. }
  10300. else {
  10301. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10302. }
  10303. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10304. return this._viewMatrix;
  10305. };
  10306. TargetCamera.prototype._getVRViewMatrix = function () {
  10307. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10308. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10309. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10310. // Computing target and final matrix
  10311. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10312. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10313. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10314. return this._viewMatrix;
  10315. };
  10316. /**
  10317. * @override
  10318. * Override Camera.createRigCamera
  10319. */
  10320. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10321. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10322. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10323. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10324. rigCamera._cameraRigParams = {};
  10325. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10326. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10327. }
  10328. return rigCamera;
  10329. }
  10330. return null;
  10331. };
  10332. /**
  10333. * @override
  10334. * Override Camera._updateRigCameras
  10335. */
  10336. TargetCamera.prototype._updateRigCameras = function () {
  10337. switch (this.cameraRigMode) {
  10338. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10339. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10340. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10341. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10342. case BABYLON.Camera.RIG_MODE_VR:
  10343. var camLeft = this._rigCameras[0];
  10344. var camRight = this._rigCameras[1];
  10345. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10346. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10347. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10348. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10349. camLeft.position.copyFrom(this.position);
  10350. camRight.position.copyFrom(this.position);
  10351. }
  10352. else {
  10353. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10354. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10355. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10356. camLeft.setTarget(this.getTarget());
  10357. camRight.setTarget(this.getTarget());
  10358. }
  10359. break;
  10360. }
  10361. _super.prototype._updateRigCameras.call(this);
  10362. };
  10363. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10364. if (!this._rigCamTransformMatrix) {
  10365. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10366. }
  10367. var target = this.getTarget();
  10368. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10369. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10370. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10371. };
  10372. return TargetCamera;
  10373. })(BABYLON.Camera);
  10374. BABYLON.TargetCamera = TargetCamera;
  10375. })(BABYLON || (BABYLON = {}));
  10376. var BABYLON;
  10377. (function (BABYLON) {
  10378. var FreeCamera = (function (_super) {
  10379. __extends(FreeCamera, _super);
  10380. function FreeCamera(name, position, scene) {
  10381. var _this = this;
  10382. _super.call(this, name, position, scene);
  10383. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10384. this.keysUp = [38];
  10385. this.keysDown = [40];
  10386. this.keysLeft = [37];
  10387. this.keysRight = [39];
  10388. this.checkCollisions = false;
  10389. this.applyGravity = false;
  10390. this.angularSensibility = 2000.0;
  10391. this._keys = [];
  10392. this._collider = new BABYLON.Collider();
  10393. this._needMoveForGravity = false;
  10394. this._oldPosition = BABYLON.Vector3.Zero();
  10395. this._diffPosition = BABYLON.Vector3.Zero();
  10396. this._newPosition = BABYLON.Vector3.Zero();
  10397. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10398. if (collidedMesh === void 0) { collidedMesh = null; }
  10399. //TODO move this to the collision coordinator!
  10400. if (_this.getScene().workerCollisions)
  10401. newPosition.multiplyInPlace(_this._collider.radius);
  10402. var updatePosition = function (newPos) {
  10403. _this._newPosition.copyFrom(newPos);
  10404. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10405. var oldPosition = _this.position.clone();
  10406. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10407. _this.position.addInPlace(_this._diffPosition);
  10408. if (_this.onCollide && collidedMesh) {
  10409. _this.onCollide(collidedMesh);
  10410. }
  10411. }
  10412. };
  10413. updatePosition(newPosition);
  10414. };
  10415. }
  10416. // Controls
  10417. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10418. var _this = this;
  10419. var previousPosition;
  10420. var engine = this.getEngine();
  10421. if (this._attachedElement) {
  10422. return;
  10423. }
  10424. this._attachedElement = element;
  10425. if (this._onMouseDown === undefined) {
  10426. this._onMouseDown = function (evt) {
  10427. previousPosition = {
  10428. x: evt.clientX,
  10429. y: evt.clientY
  10430. };
  10431. if (!noPreventDefault) {
  10432. evt.preventDefault();
  10433. }
  10434. };
  10435. this._onMouseUp = function (evt) {
  10436. previousPosition = null;
  10437. if (!noPreventDefault) {
  10438. evt.preventDefault();
  10439. }
  10440. };
  10441. this._onMouseOut = function (evt) {
  10442. previousPosition = null;
  10443. _this._keys = [];
  10444. if (!noPreventDefault) {
  10445. evt.preventDefault();
  10446. }
  10447. };
  10448. this._onMouseMove = function (evt) {
  10449. if (!previousPosition && !engine.isPointerLock) {
  10450. return;
  10451. }
  10452. var offsetX;
  10453. var offsetY;
  10454. if (!engine.isPointerLock) {
  10455. offsetX = evt.clientX - previousPosition.x;
  10456. offsetY = evt.clientY - previousPosition.y;
  10457. }
  10458. else {
  10459. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10460. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10461. }
  10462. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10463. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10464. previousPosition = {
  10465. x: evt.clientX,
  10466. y: evt.clientY
  10467. };
  10468. if (!noPreventDefault) {
  10469. evt.preventDefault();
  10470. }
  10471. };
  10472. this._onKeyDown = function (evt) {
  10473. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10474. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10475. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10476. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10477. var index = _this._keys.indexOf(evt.keyCode);
  10478. if (index === -1) {
  10479. _this._keys.push(evt.keyCode);
  10480. }
  10481. if (!noPreventDefault) {
  10482. evt.preventDefault();
  10483. }
  10484. }
  10485. };
  10486. this._onKeyUp = function (evt) {
  10487. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10488. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10489. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10490. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10491. var index = _this._keys.indexOf(evt.keyCode);
  10492. if (index >= 0) {
  10493. _this._keys.splice(index, 1);
  10494. }
  10495. if (!noPreventDefault) {
  10496. evt.preventDefault();
  10497. }
  10498. }
  10499. };
  10500. this._onLostFocus = function () {
  10501. _this._keys = [];
  10502. };
  10503. this._reset = function () {
  10504. _this._keys = [];
  10505. previousPosition = null;
  10506. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10507. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10508. };
  10509. }
  10510. element.addEventListener("mousedown", this._onMouseDown, false);
  10511. element.addEventListener("mouseup", this._onMouseUp, false);
  10512. element.addEventListener("mouseout", this._onMouseOut, false);
  10513. element.addEventListener("mousemove", this._onMouseMove, false);
  10514. BABYLON.Tools.RegisterTopRootEvents([
  10515. { name: "keydown", handler: this._onKeyDown },
  10516. { name: "keyup", handler: this._onKeyUp },
  10517. { name: "blur", handler: this._onLostFocus }
  10518. ]);
  10519. };
  10520. FreeCamera.prototype.detachControl = function (element) {
  10521. if (this._attachedElement != element) {
  10522. return;
  10523. }
  10524. element.removeEventListener("mousedown", this._onMouseDown);
  10525. element.removeEventListener("mouseup", this._onMouseUp);
  10526. element.removeEventListener("mouseout", this._onMouseOut);
  10527. element.removeEventListener("mousemove", this._onMouseMove);
  10528. BABYLON.Tools.UnregisterTopRootEvents([
  10529. { name: "keydown", handler: this._onKeyDown },
  10530. { name: "keyup", handler: this._onKeyUp },
  10531. { name: "blur", handler: this._onLostFocus }
  10532. ]);
  10533. this._attachedElement = null;
  10534. if (this._reset) {
  10535. this._reset();
  10536. }
  10537. };
  10538. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10539. var globalPosition;
  10540. if (this.parent) {
  10541. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10542. }
  10543. else {
  10544. globalPosition = this.position;
  10545. }
  10546. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10547. this._collider.radius = this.ellipsoid;
  10548. //no need for clone, as long as gravity is not on.
  10549. var actualVelocity = velocity;
  10550. //add gravity to the velocity to prevent the dual-collision checking
  10551. if (this.applyGravity) {
  10552. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10553. actualVelocity = velocity.add(this.getScene().gravity);
  10554. }
  10555. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10556. };
  10557. FreeCamera.prototype._checkInputs = function () {
  10558. if (!this._localDirection) {
  10559. this._localDirection = BABYLON.Vector3.Zero();
  10560. this._transformedDirection = BABYLON.Vector3.Zero();
  10561. }
  10562. // Keyboard
  10563. for (var index = 0; index < this._keys.length; index++) {
  10564. var keyCode = this._keys[index];
  10565. var speed = this._computeLocalCameraSpeed();
  10566. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10567. this._localDirection.copyFromFloats(-speed, 0, 0);
  10568. }
  10569. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10570. this._localDirection.copyFromFloats(0, 0, speed);
  10571. }
  10572. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10573. this._localDirection.copyFromFloats(speed, 0, 0);
  10574. }
  10575. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10576. this._localDirection.copyFromFloats(0, 0, -speed);
  10577. }
  10578. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10579. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10580. this.cameraDirection.addInPlace(this._transformedDirection);
  10581. }
  10582. _super.prototype._checkInputs.call(this);
  10583. };
  10584. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10585. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10586. };
  10587. FreeCamera.prototype._updatePosition = function () {
  10588. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10589. this._collideWithWorld(this.cameraDirection);
  10590. }
  10591. else {
  10592. this.position.addInPlace(this.cameraDirection);
  10593. }
  10594. };
  10595. return FreeCamera;
  10596. })(BABYLON.TargetCamera);
  10597. BABYLON.FreeCamera = FreeCamera;
  10598. })(BABYLON || (BABYLON = {}));
  10599. var BABYLON;
  10600. (function (BABYLON) {
  10601. var FollowCamera = (function (_super) {
  10602. __extends(FollowCamera, _super);
  10603. function FollowCamera(name, position, scene) {
  10604. _super.call(this, name, position, scene);
  10605. this.radius = 12;
  10606. this.rotationOffset = 0;
  10607. this.heightOffset = 4;
  10608. this.cameraAcceleration = 0.05;
  10609. this.maxCameraSpeed = 20;
  10610. }
  10611. FollowCamera.prototype.getRadians = function (degrees) {
  10612. return degrees * Math.PI / 180;
  10613. };
  10614. FollowCamera.prototype.follow = function (cameraTarget) {
  10615. if (!cameraTarget)
  10616. return;
  10617. var yRotation;
  10618. if (cameraTarget.rotationQuaternion) {
  10619. var rotMatrix = new BABYLON.Matrix();
  10620. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10621. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10622. }
  10623. else {
  10624. yRotation = cameraTarget.rotation.y;
  10625. }
  10626. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10627. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10628. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10629. var dx = targetX - this.position.x;
  10630. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10631. var dz = (targetZ) - this.position.z;
  10632. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10633. var vy = dy * this.cameraAcceleration;
  10634. var vz = dz * this.cameraAcceleration * 2;
  10635. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10636. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10637. }
  10638. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10639. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10640. }
  10641. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10642. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10643. }
  10644. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10645. this.setTarget(cameraTarget.position);
  10646. };
  10647. FollowCamera.prototype._checkInputs = function () {
  10648. _super.prototype._checkInputs.call(this);
  10649. this.follow(this.target);
  10650. };
  10651. return FollowCamera;
  10652. })(BABYLON.TargetCamera);
  10653. BABYLON.FollowCamera = FollowCamera;
  10654. var ArcFollowCamera = (function (_super) {
  10655. __extends(ArcFollowCamera, _super);
  10656. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10657. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10658. this.alpha = alpha;
  10659. this.beta = beta;
  10660. this.radius = radius;
  10661. this.target = target;
  10662. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10663. this.follow();
  10664. }
  10665. ArcFollowCamera.prototype.follow = function () {
  10666. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10667. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10668. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10669. this.position = this.target.position.add(this._cartesianCoordinates);
  10670. this.setTarget(this.target.position);
  10671. };
  10672. ArcFollowCamera.prototype._checkInputs = function () {
  10673. _super.prototype._checkInputs.call(this);
  10674. this.follow();
  10675. };
  10676. return ArcFollowCamera;
  10677. })(BABYLON.TargetCamera);
  10678. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10679. })(BABYLON || (BABYLON = {}));
  10680. var BABYLON;
  10681. (function (BABYLON) {
  10682. // We're mainly based on the logic defined into the FreeCamera code
  10683. var TouchCamera = (function (_super) {
  10684. __extends(TouchCamera, _super);
  10685. function TouchCamera(name, position, scene) {
  10686. _super.call(this, name, position, scene);
  10687. this._offsetX = null;
  10688. this._offsetY = null;
  10689. this._pointerCount = 0;
  10690. this._pointerPressed = [];
  10691. this.angularSensibility = 200000.0;
  10692. this.moveSensibility = 500.0;
  10693. }
  10694. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10695. var _this = this;
  10696. var previousPosition;
  10697. if (this._attachedCanvas) {
  10698. return;
  10699. }
  10700. this._attachedCanvas = canvas;
  10701. if (this._onPointerDown === undefined) {
  10702. this._onPointerDown = function (evt) {
  10703. if (!noPreventDefault) {
  10704. evt.preventDefault();
  10705. }
  10706. _this._pointerPressed.push(evt.pointerId);
  10707. if (_this._pointerPressed.length !== 1) {
  10708. return;
  10709. }
  10710. previousPosition = {
  10711. x: evt.clientX,
  10712. y: evt.clientY
  10713. };
  10714. };
  10715. this._onPointerUp = function (evt) {
  10716. if (!noPreventDefault) {
  10717. evt.preventDefault();
  10718. }
  10719. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10720. if (index === -1) {
  10721. return;
  10722. }
  10723. _this._pointerPressed.splice(index, 1);
  10724. if (index != 0) {
  10725. return;
  10726. }
  10727. previousPosition = null;
  10728. _this._offsetX = null;
  10729. _this._offsetY = null;
  10730. };
  10731. this._onPointerMove = function (evt) {
  10732. if (!noPreventDefault) {
  10733. evt.preventDefault();
  10734. }
  10735. if (!previousPosition) {
  10736. return;
  10737. }
  10738. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10739. if (index != 0) {
  10740. return;
  10741. }
  10742. _this._offsetX = evt.clientX - previousPosition.x;
  10743. _this._offsetY = -(evt.clientY - previousPosition.y);
  10744. };
  10745. this._onLostFocus = function () {
  10746. _this._offsetX = null;
  10747. _this._offsetY = null;
  10748. };
  10749. }
  10750. canvas.addEventListener("pointerdown", this._onPointerDown);
  10751. canvas.addEventListener("pointerup", this._onPointerUp);
  10752. canvas.addEventListener("pointerout", this._onPointerUp);
  10753. canvas.addEventListener("pointermove", this._onPointerMove);
  10754. BABYLON.Tools.RegisterTopRootEvents([
  10755. { name: "blur", handler: this._onLostFocus }
  10756. ]);
  10757. };
  10758. TouchCamera.prototype.detachControl = function (canvas) {
  10759. if (this._attachedCanvas != canvas) {
  10760. return;
  10761. }
  10762. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10763. canvas.removeEventListener("pointerup", this._onPointerUp);
  10764. canvas.removeEventListener("pointerout", this._onPointerUp);
  10765. canvas.removeEventListener("pointermove", this._onPointerMove);
  10766. BABYLON.Tools.UnregisterTopRootEvents([
  10767. { name: "blur", handler: this._onLostFocus }
  10768. ]);
  10769. this._attachedCanvas = null;
  10770. };
  10771. TouchCamera.prototype._checkInputs = function () {
  10772. if (this._offsetX) {
  10773. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10774. if (this._pointerPressed.length > 1) {
  10775. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10776. }
  10777. else {
  10778. var speed = this._computeLocalCameraSpeed();
  10779. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10780. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10781. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10782. }
  10783. }
  10784. _super.prototype._checkInputs.call(this);
  10785. };
  10786. return TouchCamera;
  10787. })(BABYLON.FreeCamera);
  10788. BABYLON.TouchCamera = TouchCamera;
  10789. })(BABYLON || (BABYLON = {}));
  10790. var BABYLON;
  10791. (function (BABYLON) {
  10792. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10793. var ArcRotateCamera = (function (_super) {
  10794. __extends(ArcRotateCamera, _super);
  10795. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10796. var _this = this;
  10797. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10798. this.alpha = alpha;
  10799. this.beta = beta;
  10800. this.radius = radius;
  10801. this.target = target;
  10802. this.inertialAlphaOffset = 0;
  10803. this.inertialBetaOffset = 0;
  10804. this.inertialRadiusOffset = 0;
  10805. this.lowerAlphaLimit = null;
  10806. this.upperAlphaLimit = null;
  10807. this.lowerBetaLimit = 0.01;
  10808. this.upperBetaLimit = Math.PI;
  10809. this.lowerRadiusLimit = null;
  10810. this.upperRadiusLimit = null;
  10811. this.angularSensibilityX = 1000.0;
  10812. this.angularSensibilityY = 1000.0;
  10813. this.wheelPrecision = 3.0;
  10814. this.pinchPrecision = 2.0;
  10815. this.panningSensibility = 50.0;
  10816. this.inertialPanningX = 0;
  10817. this.inertialPanningY = 0;
  10818. this.keysUp = [38];
  10819. this.keysDown = [40];
  10820. this.keysLeft = [37];
  10821. this.keysRight = [39];
  10822. this.zoomOnFactor = 1;
  10823. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10824. this.pinchInwards = true;
  10825. this.allowUpsideDown = true;
  10826. this._keys = [];
  10827. this._viewMatrix = new BABYLON.Matrix();
  10828. this._isRightClick = false;
  10829. this._isCtrlPushed = false;
  10830. this.checkCollisions = false;
  10831. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10832. this._collider = new BABYLON.Collider();
  10833. this._previousPosition = BABYLON.Vector3.Zero();
  10834. this._collisionVelocity = BABYLON.Vector3.Zero();
  10835. this._newPosition = BABYLON.Vector3.Zero();
  10836. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10837. if (collidedMesh === void 0) { collidedMesh = null; }
  10838. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10839. newPosition.multiplyInPlace(_this._collider.radius);
  10840. }
  10841. if (!collidedMesh) {
  10842. _this._previousPosition.copyFrom(_this.position);
  10843. }
  10844. else {
  10845. _this.setPosition(_this.position);
  10846. if (_this.onCollide) {
  10847. _this.onCollide(collidedMesh);
  10848. }
  10849. }
  10850. // Recompute because of constraints
  10851. var cosa = Math.cos(_this.alpha);
  10852. var sina = Math.sin(_this.alpha);
  10853. var cosb = Math.cos(_this.beta);
  10854. var sinb = Math.sin(_this.beta);
  10855. var target = _this._getTargetPosition();
  10856. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10857. _this.position.copyFrom(_this._newPosition);
  10858. var up = _this.upVector;
  10859. if (_this.allowUpsideDown && _this.beta < 0) {
  10860. var up = up.clone();
  10861. up = up.negate();
  10862. }
  10863. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10864. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10865. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10866. _this._collisionTriggered = false;
  10867. };
  10868. if (!this.target) {
  10869. this.target = BABYLON.Vector3.Zero();
  10870. }
  10871. this.getViewMatrix();
  10872. }
  10873. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  10874. //deprecated angularSensibility support
  10875. get: function () {
  10876. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10877. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  10878. },
  10879. //deprecated angularSensibility support
  10880. set: function (value) {
  10881. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10882. this.angularSensibilityX = value;
  10883. this.angularSensibilityY = value;
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. ArcRotateCamera.prototype._getTargetPosition = function () {
  10889. return this.target.position || this.target;
  10890. };
  10891. // Cache
  10892. ArcRotateCamera.prototype._initCache = function () {
  10893. _super.prototype._initCache.call(this);
  10894. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10895. this._cache.alpha = undefined;
  10896. this._cache.beta = undefined;
  10897. this._cache.radius = undefined;
  10898. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  10899. };
  10900. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10901. if (!ignoreParentClass) {
  10902. _super.prototype._updateCache.call(this);
  10903. }
  10904. this._cache.target.copyFrom(this._getTargetPosition());
  10905. this._cache.alpha = this.alpha;
  10906. this._cache.beta = this.beta;
  10907. this._cache.radius = this.radius;
  10908. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  10909. };
  10910. // Synchronized
  10911. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10912. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10913. return false;
  10914. return this._cache.target.equals(this._getTargetPosition())
  10915. && this._cache.alpha === this.alpha
  10916. && this._cache.beta === this.beta
  10917. && this._cache.radius === this.radius
  10918. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10919. };
  10920. // Methods
  10921. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  10922. var _this = this;
  10923. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  10924. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10925. var previousPinchDistance = 0;
  10926. var pointers = new BABYLON.SmartCollection();
  10927. if (this._attachedElement) {
  10928. return;
  10929. }
  10930. this._attachedElement = element;
  10931. var engine = this.getEngine();
  10932. if (this._onPointerDown === undefined) {
  10933. this._onPointerDown = function (evt) {
  10934. // Manage panning with right click
  10935. _this._isRightClick = evt.button === 2 ? true : false;
  10936. // manage pointers
  10937. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10938. cacheSoloPointer = pointers.item(evt.pointerId);
  10939. if (!noPreventDefault) {
  10940. evt.preventDefault();
  10941. }
  10942. };
  10943. this._onPointerUp = function (evt) {
  10944. cacheSoloPointer = null;
  10945. previousPinchDistance = 0;
  10946. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  10947. //but emptying completly pointers collection is required to fix a bug on iPhone :
  10948. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  10949. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  10950. pointers.empty();
  10951. if (!noPreventDefault) {
  10952. evt.preventDefault();
  10953. }
  10954. };
  10955. this._onContextMenu = function (evt) {
  10956. evt.preventDefault();
  10957. };
  10958. this._onPointerMove = function (evt) {
  10959. if (!noPreventDefault) {
  10960. evt.preventDefault();
  10961. }
  10962. switch (pointers.count) {
  10963. case 1:
  10964. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  10965. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  10966. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  10967. }
  10968. else {
  10969. var offsetX = evt.clientX - cacheSoloPointer.x;
  10970. var offsetY = evt.clientY - cacheSoloPointer.y;
  10971. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10972. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10973. }
  10974. cacheSoloPointer.x = evt.clientX;
  10975. cacheSoloPointer.y = evt.clientY;
  10976. break;
  10977. case 2:
  10978. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10979. pointers.item(evt.pointerId).x = evt.clientX;
  10980. pointers.item(evt.pointerId).y = evt.clientY;
  10981. var direction = _this.pinchInwards ? 1 : -1;
  10982. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10983. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10984. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10985. if (previousPinchDistance === 0) {
  10986. previousPinchDistance = pinchSquaredDistance;
  10987. return;
  10988. }
  10989. if (pinchSquaredDistance !== previousPinchDistance) {
  10990. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  10991. previousPinchDistance = pinchSquaredDistance;
  10992. }
  10993. break;
  10994. default:
  10995. if (pointers.item(evt.pointerId)) {
  10996. pointers.item(evt.pointerId).x = evt.clientX;
  10997. pointers.item(evt.pointerId).y = evt.clientY;
  10998. }
  10999. }
  11000. };
  11001. this._onMouseMove = function (evt) {
  11002. if (!engine.isPointerLock) {
  11003. return;
  11004. }
  11005. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11006. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11007. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11008. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11009. if (!noPreventDefault) {
  11010. evt.preventDefault();
  11011. }
  11012. };
  11013. this._wheel = function (event) {
  11014. var delta = 0;
  11015. if (event.wheelDelta) {
  11016. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11017. }
  11018. else if (event.detail) {
  11019. delta = -event.detail / _this.wheelPrecision;
  11020. }
  11021. if (delta)
  11022. _this.inertialRadiusOffset += delta;
  11023. if (event.preventDefault) {
  11024. if (!noPreventDefault) {
  11025. event.preventDefault();
  11026. }
  11027. }
  11028. };
  11029. this._onKeyDown = function (evt) {
  11030. _this._isCtrlPushed = evt.ctrlKey;
  11031. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11032. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11033. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11034. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11035. var index = _this._keys.indexOf(evt.keyCode);
  11036. if (index === -1) {
  11037. _this._keys.push(evt.keyCode);
  11038. }
  11039. if (evt.preventDefault) {
  11040. if (!noPreventDefault) {
  11041. evt.preventDefault();
  11042. }
  11043. }
  11044. }
  11045. };
  11046. this._onKeyUp = function (evt) {
  11047. _this._isCtrlPushed = evt.ctrlKey;
  11048. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11049. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11050. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11051. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11052. var index = _this._keys.indexOf(evt.keyCode);
  11053. if (index >= 0) {
  11054. _this._keys.splice(index, 1);
  11055. }
  11056. if (evt.preventDefault) {
  11057. if (!noPreventDefault) {
  11058. evt.preventDefault();
  11059. }
  11060. }
  11061. }
  11062. };
  11063. this._onLostFocus = function () {
  11064. _this._keys = [];
  11065. pointers.empty();
  11066. previousPinchDistance = 0;
  11067. cacheSoloPointer = null;
  11068. };
  11069. this._onGestureStart = function (e) {
  11070. if (window.MSGesture === undefined) {
  11071. return;
  11072. }
  11073. if (!_this._MSGestureHandler) {
  11074. _this._MSGestureHandler = new MSGesture();
  11075. _this._MSGestureHandler.target = element;
  11076. }
  11077. _this._MSGestureHandler.addPointer(e.pointerId);
  11078. };
  11079. this._onGesture = function (e) {
  11080. _this.radius *= e.scale;
  11081. if (e.preventDefault) {
  11082. if (!noPreventDefault) {
  11083. e.stopPropagation();
  11084. e.preventDefault();
  11085. }
  11086. }
  11087. };
  11088. this._reset = function () {
  11089. _this._keys = [];
  11090. _this.inertialAlphaOffset = 0;
  11091. _this.inertialBetaOffset = 0;
  11092. _this.inertialRadiusOffset = 0;
  11093. pointers.empty();
  11094. previousPinchDistance = 0;
  11095. cacheSoloPointer = null;
  11096. };
  11097. }
  11098. if (!useCtrlForPanning) {
  11099. element.addEventListener("contextmenu", this._onContextMenu, false);
  11100. }
  11101. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11102. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11103. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11104. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11105. element.addEventListener("mousemove", this._onMouseMove, false);
  11106. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11107. element.addEventListener("MSGestureChange", this._onGesture, false);
  11108. element.addEventListener('mousewheel', this._wheel, false);
  11109. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11110. BABYLON.Tools.RegisterTopRootEvents([
  11111. { name: "keydown", handler: this._onKeyDown },
  11112. { name: "keyup", handler: this._onKeyUp },
  11113. { name: "blur", handler: this._onLostFocus }
  11114. ]);
  11115. };
  11116. ArcRotateCamera.prototype.detachControl = function (element) {
  11117. if (this._attachedElement !== element) {
  11118. return;
  11119. }
  11120. element.removeEventListener("contextmenu", this._onContextMenu);
  11121. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11122. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11123. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11124. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11125. element.removeEventListener("mousemove", this._onMouseMove);
  11126. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11127. element.removeEventListener("MSGestureChange", this._onGesture);
  11128. element.removeEventListener('mousewheel', this._wheel);
  11129. element.removeEventListener('DOMMouseScroll', this._wheel);
  11130. BABYLON.Tools.UnregisterTopRootEvents([
  11131. { name: "keydown", handler: this._onKeyDown },
  11132. { name: "keyup", handler: this._onKeyUp },
  11133. { name: "blur", handler: this._onLostFocus }
  11134. ]);
  11135. this._MSGestureHandler = null;
  11136. this._attachedElement = null;
  11137. if (this._reset) {
  11138. this._reset();
  11139. }
  11140. };
  11141. ArcRotateCamera.prototype._checkInputs = function () {
  11142. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11143. if (this._collisionTriggered) {
  11144. return;
  11145. }
  11146. // Keyboard
  11147. for (var index = 0; index < this._keys.length; index++) {
  11148. var keyCode = this._keys[index];
  11149. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11150. this.inertialAlphaOffset -= 0.01;
  11151. }
  11152. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11153. this.inertialBetaOffset -= 0.01;
  11154. }
  11155. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11156. this.inertialAlphaOffset += 0.01;
  11157. }
  11158. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11159. this.inertialBetaOffset += 0.01;
  11160. }
  11161. }
  11162. // Inertia
  11163. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11164. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11165. this.beta += this.inertialBetaOffset;
  11166. this.radius -= this.inertialRadiusOffset;
  11167. this.inertialAlphaOffset *= this.inertia;
  11168. this.inertialBetaOffset *= this.inertia;
  11169. this.inertialRadiusOffset *= this.inertia;
  11170. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11171. this.inertialAlphaOffset = 0;
  11172. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11173. this.inertialBetaOffset = 0;
  11174. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11175. this.inertialRadiusOffset = 0;
  11176. }
  11177. // Panning inertia
  11178. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11179. if (!this._localDirection) {
  11180. this._localDirection = BABYLON.Vector3.Zero();
  11181. this._transformedDirection = BABYLON.Vector3.Zero();
  11182. }
  11183. this.inertialPanningX *= this.inertia;
  11184. this.inertialPanningY *= this.inertia;
  11185. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11186. this.inertialPanningX = 0;
  11187. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11188. this.inertialPanningY = 0;
  11189. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11190. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11191. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11192. this.target.addInPlace(this._transformedDirection);
  11193. }
  11194. // Limits
  11195. this._checkLimits();
  11196. _super.prototype._checkInputs.call(this);
  11197. };
  11198. ArcRotateCamera.prototype._checkLimits = function () {
  11199. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11200. if (this.allowUpsideDown && this.beta > Math.PI) {
  11201. this.beta = this.beta - (2 * Math.PI);
  11202. }
  11203. }
  11204. else {
  11205. if (this.beta < this.lowerBetaLimit) {
  11206. this.beta = this.lowerBetaLimit;
  11207. }
  11208. }
  11209. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11210. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11211. this.beta = this.beta + (2 * Math.PI);
  11212. }
  11213. }
  11214. else {
  11215. if (this.beta > this.upperBetaLimit) {
  11216. this.beta = this.upperBetaLimit;
  11217. }
  11218. }
  11219. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11220. this.alpha = this.lowerAlphaLimit;
  11221. }
  11222. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11223. this.alpha = this.upperAlphaLimit;
  11224. }
  11225. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11226. this.radius = this.lowerRadiusLimit;
  11227. }
  11228. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11229. this.radius = this.upperRadiusLimit;
  11230. }
  11231. };
  11232. ArcRotateCamera.prototype.setPosition = function (position) {
  11233. if (this.position.equals(position)) {
  11234. return;
  11235. }
  11236. var radiusv3 = position.subtract(this._getTargetPosition());
  11237. this.radius = radiusv3.length();
  11238. // Alpha
  11239. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11240. if (radiusv3.z < 0) {
  11241. this.alpha = 2 * Math.PI - this.alpha;
  11242. }
  11243. // Beta
  11244. this.beta = Math.acos(radiusv3.y / this.radius);
  11245. this._checkLimits();
  11246. };
  11247. ArcRotateCamera.prototype.setTarget = function (target) {
  11248. this.target = target;
  11249. };
  11250. ArcRotateCamera.prototype._getViewMatrix = function () {
  11251. // Compute
  11252. var cosa = Math.cos(this.alpha);
  11253. var sina = Math.sin(this.alpha);
  11254. var cosb = Math.cos(this.beta);
  11255. var sinb = Math.sin(this.beta);
  11256. var target = this._getTargetPosition();
  11257. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11258. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11259. this._collider.radius = this.collisionRadius;
  11260. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11261. this._collisionTriggered = true;
  11262. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11263. }
  11264. else {
  11265. this.position.copyFrom(this._newPosition);
  11266. var up = this.upVector;
  11267. if (this.allowUpsideDown && this.beta < 0) {
  11268. var up = up.clone();
  11269. up = up.negate();
  11270. }
  11271. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11272. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11273. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11274. }
  11275. return this._viewMatrix;
  11276. };
  11277. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11278. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11279. meshes = meshes || this.getScene().meshes;
  11280. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11281. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11282. this.radius = distance * this.zoomOnFactor;
  11283. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11284. };
  11285. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11286. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11287. var meshesOrMinMaxVector;
  11288. var distance;
  11289. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11290. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11291. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11292. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11293. }
  11294. else {
  11295. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11296. distance = meshesOrMinMaxVectorAndDistance.distance;
  11297. }
  11298. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11299. if (!doNotUpdateMaxZ) {
  11300. this.maxZ = distance * 2;
  11301. }
  11302. };
  11303. /**
  11304. * @override
  11305. * Override Camera.createRigCamera
  11306. */
  11307. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11308. switch (this.cameraRigMode) {
  11309. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11310. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11311. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11312. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11313. case BABYLON.Camera.RIG_MODE_VR:
  11314. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11315. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11316. }
  11317. };
  11318. /**
  11319. * @override
  11320. * Override Camera._updateRigCameras
  11321. */
  11322. ArcRotateCamera.prototype._updateRigCameras = function () {
  11323. switch (this.cameraRigMode) {
  11324. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11325. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11326. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11327. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11328. case BABYLON.Camera.RIG_MODE_VR:
  11329. var camLeft = this._rigCameras[0];
  11330. var camRight = this._rigCameras[1];
  11331. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11332. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11333. camLeft.beta = camRight.beta = this.beta;
  11334. camLeft.radius = camRight.radius = this.radius;
  11335. break;
  11336. }
  11337. _super.prototype._updateRigCameras.call(this);
  11338. };
  11339. return ArcRotateCamera;
  11340. })(BABYLON.TargetCamera);
  11341. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11342. })(BABYLON || (BABYLON = {}));
  11343. var BABYLON;
  11344. (function (BABYLON) {
  11345. var RenderingManager = (function () {
  11346. function RenderingManager(scene) {
  11347. this._renderingGroups = new Array();
  11348. this._scene = scene;
  11349. }
  11350. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11351. if (this._scene._activeParticleSystems.length === 0) {
  11352. return;
  11353. }
  11354. // Particles
  11355. var activeCamera = this._scene.activeCamera;
  11356. var beforeParticlesDate = BABYLON.Tools.Now;
  11357. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11358. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11359. if (particleSystem.renderingGroupId !== index) {
  11360. continue;
  11361. }
  11362. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11363. continue;
  11364. }
  11365. this._clearDepthBuffer();
  11366. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11367. this._scene._activeParticles += particleSystem.render();
  11368. }
  11369. }
  11370. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11371. };
  11372. RenderingManager.prototype._renderSprites = function (index) {
  11373. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11374. return;
  11375. }
  11376. // Sprites
  11377. var activeCamera = this._scene.activeCamera;
  11378. var beforeSpritessDate = BABYLON.Tools.Now;
  11379. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11380. var spriteManager = this._scene.spriteManagers[id];
  11381. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11382. this._clearDepthBuffer();
  11383. spriteManager.render();
  11384. }
  11385. }
  11386. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11387. };
  11388. RenderingManager.prototype._clearDepthBuffer = function () {
  11389. if (this._depthBufferAlreadyCleaned) {
  11390. return;
  11391. }
  11392. this._scene.getEngine().clear(0, false, true);
  11393. this._depthBufferAlreadyCleaned = true;
  11394. };
  11395. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11396. if (this._currentRenderSprites) {
  11397. this._renderSprites(this._currentIndex);
  11398. }
  11399. if (this._currentRenderParticles) {
  11400. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11401. }
  11402. };
  11403. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11404. this._currentActiveMeshes = activeMeshes;
  11405. this._currentRenderParticles = renderParticles;
  11406. this._currentRenderSprites = renderSprites;
  11407. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11408. this._depthBufferAlreadyCleaned = false;
  11409. var renderingGroup = this._renderingGroups[index];
  11410. var needToStepBack = false;
  11411. this._currentIndex = index;
  11412. if (renderingGroup) {
  11413. this._clearDepthBuffer();
  11414. if (!renderingGroup.onBeforeTransparentRendering) {
  11415. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11416. }
  11417. if (!renderingGroup.render(customRenderFunction)) {
  11418. this._renderingGroups.splice(index, 1);
  11419. needToStepBack = true;
  11420. this._renderSpritesAndParticles();
  11421. }
  11422. }
  11423. else {
  11424. this._renderSpritesAndParticles();
  11425. }
  11426. if (needToStepBack) {
  11427. index--;
  11428. }
  11429. }
  11430. };
  11431. RenderingManager.prototype.reset = function () {
  11432. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11433. if (renderingGroup) {
  11434. renderingGroup.prepare();
  11435. }
  11436. });
  11437. };
  11438. RenderingManager.prototype.dispatch = function (subMesh) {
  11439. var mesh = subMesh.getMesh();
  11440. var renderingGroupId = mesh.renderingGroupId || 0;
  11441. if (!this._renderingGroups[renderingGroupId]) {
  11442. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11443. }
  11444. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11445. };
  11446. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11447. return RenderingManager;
  11448. })();
  11449. BABYLON.RenderingManager = RenderingManager;
  11450. })(BABYLON || (BABYLON = {}));
  11451. var BABYLON;
  11452. (function (BABYLON) {
  11453. var RenderingGroup = (function () {
  11454. function RenderingGroup(index, scene) {
  11455. this.index = index;
  11456. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11457. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11458. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11459. this._scene = scene;
  11460. }
  11461. RenderingGroup.prototype.render = function (customRenderFunction) {
  11462. if (customRenderFunction) {
  11463. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11464. return true;
  11465. }
  11466. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11467. if (this.onBeforeTransparentRendering) {
  11468. this.onBeforeTransparentRendering();
  11469. }
  11470. return false;
  11471. }
  11472. var engine = this._scene.getEngine();
  11473. // Opaque
  11474. var subIndex;
  11475. var submesh;
  11476. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11477. submesh = this._opaqueSubMeshes.data[subIndex];
  11478. submesh.render(false);
  11479. }
  11480. // Alpha test
  11481. engine.setAlphaTesting(true);
  11482. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11483. submesh = this._alphaTestSubMeshes.data[subIndex];
  11484. submesh.render(false);
  11485. }
  11486. engine.setAlphaTesting(false);
  11487. if (this.onBeforeTransparentRendering) {
  11488. this.onBeforeTransparentRendering();
  11489. }
  11490. // Transparent
  11491. if (this._transparentSubMeshes.length) {
  11492. // Sorting
  11493. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11494. submesh = this._transparentSubMeshes.data[subIndex];
  11495. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11496. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11497. }
  11498. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11499. sortedArray.sort(function (a, b) {
  11500. // Alpha index first
  11501. if (a._alphaIndex > b._alphaIndex) {
  11502. return 1;
  11503. }
  11504. if (a._alphaIndex < b._alphaIndex) {
  11505. return -1;
  11506. }
  11507. // Then distance to camera
  11508. if (a._distanceToCamera < b._distanceToCamera) {
  11509. return 1;
  11510. }
  11511. if (a._distanceToCamera > b._distanceToCamera) {
  11512. return -1;
  11513. }
  11514. return 0;
  11515. });
  11516. // Rendering
  11517. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11518. submesh = sortedArray[subIndex];
  11519. submesh.render(true);
  11520. }
  11521. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11522. }
  11523. return true;
  11524. };
  11525. RenderingGroup.prototype.prepare = function () {
  11526. this._opaqueSubMeshes.reset();
  11527. this._transparentSubMeshes.reset();
  11528. this._alphaTestSubMeshes.reset();
  11529. };
  11530. RenderingGroup.prototype.dispatch = function (subMesh) {
  11531. var material = subMesh.getMaterial();
  11532. var mesh = subMesh.getMesh();
  11533. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11534. this._transparentSubMeshes.push(subMesh);
  11535. }
  11536. else if (material.needAlphaTesting()) {
  11537. this._alphaTestSubMeshes.push(subMesh);
  11538. }
  11539. else {
  11540. this._opaqueSubMeshes.push(subMesh); // Opaque
  11541. }
  11542. };
  11543. return RenderingGroup;
  11544. })();
  11545. BABYLON.RenderingGroup = RenderingGroup;
  11546. })(BABYLON || (BABYLON = {}));
  11547. var BABYLON;
  11548. (function (BABYLON) {
  11549. /**
  11550. * Represents a scene to be rendered by the engine.
  11551. * @see http://doc.babylonjs.com/page.php?p=21911
  11552. */
  11553. var Scene = (function () {
  11554. /**
  11555. * @constructor
  11556. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11557. */
  11558. function Scene(engine) {
  11559. // Members
  11560. this.autoClear = true;
  11561. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11562. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11563. this.forceWireframe = false;
  11564. this.forcePointsCloud = false;
  11565. this.forceShowBoundingBoxes = false;
  11566. this.animationsEnabled = true;
  11567. this.constantlyUpdateMeshUnderPointer = false;
  11568. 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
  11569. // Fog
  11570. /**
  11571. * is fog enabled on this scene.
  11572. * @type {boolean}
  11573. */
  11574. this.fogEnabled = true;
  11575. this.fogMode = Scene.FOGMODE_NONE;
  11576. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11577. this.fogDensity = 0.1;
  11578. this.fogStart = 0;
  11579. this.fogEnd = 1000.0;
  11580. // Lights
  11581. /**
  11582. * is shadow enabled on this scene.
  11583. * @type {boolean}
  11584. */
  11585. this.shadowsEnabled = true;
  11586. /**
  11587. * is light enabled on this scene.
  11588. * @type {boolean}
  11589. */
  11590. this.lightsEnabled = true;
  11591. /**
  11592. * All of the lights added to this scene.
  11593. * @see BABYLON.Light
  11594. * @type {BABYLON.Light[]}
  11595. */
  11596. this.lights = new Array();
  11597. // Cameras
  11598. /**
  11599. * All of the cameras added to this scene.
  11600. * @see BABYLON.Camera
  11601. * @type {BABYLON.Camera[]}
  11602. */
  11603. this.cameras = new Array();
  11604. this.activeCameras = new Array();
  11605. // Meshes
  11606. /**
  11607. * All of the (abstract) meshes added to this scene.
  11608. * @see BABYLON.AbstractMesh
  11609. * @type {BABYLON.AbstractMesh[]}
  11610. */
  11611. this.meshes = new Array();
  11612. // Geometries
  11613. this._geometries = new Array();
  11614. this.materials = new Array();
  11615. this.multiMaterials = new Array();
  11616. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11617. // Textures
  11618. this.texturesEnabled = true;
  11619. this.textures = new Array();
  11620. // Particles
  11621. this.particlesEnabled = true;
  11622. this.particleSystems = new Array();
  11623. // Sprites
  11624. this.spritesEnabled = true;
  11625. this.spriteManagers = new Array();
  11626. // Layers
  11627. this.layers = new Array();
  11628. // Skeletons
  11629. this.skeletonsEnabled = true;
  11630. this.skeletons = new Array();
  11631. // Lens flares
  11632. this.lensFlaresEnabled = true;
  11633. this.lensFlareSystems = new Array();
  11634. // Collisions
  11635. this.collisionsEnabled = true;
  11636. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11637. // Postprocesses
  11638. this.postProcessesEnabled = true;
  11639. // Customs render targets
  11640. this.renderTargetsEnabled = true;
  11641. this.dumpNextRenderTargets = false;
  11642. this.customRenderTargets = new Array();
  11643. // Imported meshes
  11644. this.importedMeshesFiles = new Array();
  11645. // Probes
  11646. this.probesEnabled = true;
  11647. this.reflectionProbes = new Array();
  11648. this._actionManagers = new Array();
  11649. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11650. // Procedural textures
  11651. this.proceduralTexturesEnabled = true;
  11652. this._proceduralTextures = new Array();
  11653. this.soundTracks = new Array();
  11654. this._audioEnabled = true;
  11655. this._headphone = false;
  11656. this._totalVertices = 0;
  11657. this._activeIndices = 0;
  11658. this._activeParticles = 0;
  11659. this._lastFrameDuration = 0;
  11660. this._evaluateActiveMeshesDuration = 0;
  11661. this._renderTargetsDuration = 0;
  11662. this._particlesDuration = 0;
  11663. this._renderDuration = 0;
  11664. this._spritesDuration = 0;
  11665. this._animationRatio = 0;
  11666. this._renderId = 0;
  11667. this._executeWhenReadyTimeoutId = -1;
  11668. this._toBeDisposed = new BABYLON.SmartArray(256);
  11669. this._onReadyCallbacks = new Array();
  11670. this._pendingData = []; //ANY
  11671. this._onBeforeRenderCallbacks = new Array();
  11672. this._onAfterRenderCallbacks = new Array();
  11673. this._activeMeshes = new BABYLON.SmartArray(256);
  11674. this._processedMaterials = new BABYLON.SmartArray(256);
  11675. this._renderTargets = new BABYLON.SmartArray(256);
  11676. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11677. this._activeSkeletons = new BABYLON.SmartArray(32);
  11678. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  11679. this._activeBones = 0;
  11680. this._activeAnimatables = new Array();
  11681. this._transformMatrix = BABYLON.Matrix.Zero();
  11682. this._edgesRenderers = new BABYLON.SmartArray(16);
  11683. this._uniqueIdCounter = 0;
  11684. this._engine = engine;
  11685. engine.scenes.push(this);
  11686. this._renderingManager = new BABYLON.RenderingManager(this);
  11687. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11688. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11689. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11690. if (BABYLON.OutlineRenderer) {
  11691. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11692. }
  11693. this.attachControl();
  11694. this._debugLayer = new BABYLON.DebugLayer(this);
  11695. if (BABYLON.SoundTrack) {
  11696. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11697. }
  11698. //simplification queue
  11699. if (BABYLON.SimplificationQueue) {
  11700. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11701. }
  11702. //collision coordinator initialization. For now legacy per default.
  11703. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11704. }
  11705. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11706. get: function () {
  11707. return Scene._FOGMODE_NONE;
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11713. get: function () {
  11714. return Scene._FOGMODE_EXP;
  11715. },
  11716. enumerable: true,
  11717. configurable: true
  11718. });
  11719. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11720. get: function () {
  11721. return Scene._FOGMODE_EXP2;
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11727. get: function () {
  11728. return Scene._FOGMODE_LINEAR;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Scene.prototype, "debugLayer", {
  11734. // Properties
  11735. get: function () {
  11736. return this._debugLayer;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11742. get: function () {
  11743. return this._workerCollisions;
  11744. },
  11745. set: function (enabled) {
  11746. enabled = (enabled && !!Worker);
  11747. this._workerCollisions = enabled;
  11748. if (this.collisionCoordinator) {
  11749. this.collisionCoordinator.destroy();
  11750. }
  11751. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11752. this.collisionCoordinator.init(this);
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  11758. get: function () {
  11759. return this._selectionOctree;
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11765. /**
  11766. * The mesh that is currently under the pointer.
  11767. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11768. */
  11769. get: function () {
  11770. return this._meshUnderPointer;
  11771. },
  11772. enumerable: true,
  11773. configurable: true
  11774. });
  11775. Object.defineProperty(Scene.prototype, "pointerX", {
  11776. /**
  11777. * Current on-screen X position of the pointer
  11778. * @return {number} X position of the pointer
  11779. */
  11780. get: function () {
  11781. return this._pointerX;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(Scene.prototype, "pointerY", {
  11787. /**
  11788. * Current on-screen Y position of the pointer
  11789. * @return {number} Y position of the pointer
  11790. */
  11791. get: function () {
  11792. return this._pointerY;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Scene.prototype.getCachedMaterial = function () {
  11798. return this._cachedMaterial;
  11799. };
  11800. Scene.prototype.getBoundingBoxRenderer = function () {
  11801. return this._boundingBoxRenderer;
  11802. };
  11803. Scene.prototype.getOutlineRenderer = function () {
  11804. return this._outlineRenderer;
  11805. };
  11806. Scene.prototype.getEngine = function () {
  11807. return this._engine;
  11808. };
  11809. Scene.prototype.getTotalVertices = function () {
  11810. return this._totalVertices;
  11811. };
  11812. Scene.prototype.getActiveIndices = function () {
  11813. return this._activeIndices;
  11814. };
  11815. Scene.prototype.getActiveParticles = function () {
  11816. return this._activeParticles;
  11817. };
  11818. Scene.prototype.getActiveBones = function () {
  11819. return this._activeBones;
  11820. };
  11821. // Stats
  11822. Scene.prototype.getLastFrameDuration = function () {
  11823. return this._lastFrameDuration;
  11824. };
  11825. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11826. return this._evaluateActiveMeshesDuration;
  11827. };
  11828. Scene.prototype.getActiveMeshes = function () {
  11829. return this._activeMeshes;
  11830. };
  11831. Scene.prototype.getRenderTargetsDuration = function () {
  11832. return this._renderTargetsDuration;
  11833. };
  11834. Scene.prototype.getRenderDuration = function () {
  11835. return this._renderDuration;
  11836. };
  11837. Scene.prototype.getParticlesDuration = function () {
  11838. return this._particlesDuration;
  11839. };
  11840. Scene.prototype.getSpritesDuration = function () {
  11841. return this._spritesDuration;
  11842. };
  11843. Scene.prototype.getAnimationRatio = function () {
  11844. return this._animationRatio;
  11845. };
  11846. Scene.prototype.getRenderId = function () {
  11847. return this._renderId;
  11848. };
  11849. Scene.prototype.incrementRenderId = function () {
  11850. this._renderId++;
  11851. };
  11852. Scene.prototype._updatePointerPosition = function (evt) {
  11853. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11854. this._pointerX = evt.clientX - canvasRect.left;
  11855. this._pointerY = evt.clientY - canvasRect.top;
  11856. if (this.cameraToUseForPointers) {
  11857. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11858. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11859. }
  11860. };
  11861. // Pointers handling
  11862. Scene.prototype.attachControl = function () {
  11863. var _this = this;
  11864. var spritePredicate = function (sprite) {
  11865. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  11866. };
  11867. this._onPointerMove = function (evt) {
  11868. var canvas = _this._engine.getRenderingCanvas();
  11869. _this._updatePointerPosition(evt);
  11870. // Meshes
  11871. 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);
  11872. if (pickResult.hit && pickResult.pickedMesh) {
  11873. _this._meshUnderPointer = pickResult.pickedMesh;
  11874. _this.setPointerOverMesh(pickResult.pickedMesh);
  11875. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  11876. canvas.style.cursor = "pointer";
  11877. }
  11878. else {
  11879. canvas.style.cursor = "";
  11880. }
  11881. }
  11882. else {
  11883. // Sprites
  11884. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11885. if (pickResult.hit && pickResult.pickedSprite) {
  11886. canvas.style.cursor = "pointer";
  11887. }
  11888. else {
  11889. // Restore pointer
  11890. _this.setPointerOverMesh(null);
  11891. canvas.style.cursor = "";
  11892. _this._meshUnderPointer = null;
  11893. }
  11894. }
  11895. if (_this.onPointerMove) {
  11896. _this.onPointerMove(evt, pickResult);
  11897. }
  11898. };
  11899. this._onPointerDown = function (evt) {
  11900. _this._updatePointerPosition(evt);
  11901. var predicate = null;
  11902. // Meshes
  11903. if (!_this.onPointerDown) {
  11904. predicate = function (mesh) {
  11905. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11906. };
  11907. }
  11908. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11909. if (pickResult.hit && pickResult.pickedMesh) {
  11910. if (pickResult.pickedMesh.actionManager) {
  11911. switch (evt.button) {
  11912. case 0:
  11913. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11914. break;
  11915. case 1:
  11916. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11917. break;
  11918. case 2:
  11919. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11920. break;
  11921. }
  11922. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11923. }
  11924. }
  11925. if (_this.onPointerDown) {
  11926. _this.onPointerDown(evt, pickResult);
  11927. }
  11928. // Sprites
  11929. if (_this.spriteManagers.length > 0) {
  11930. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11931. if (pickResult.hit && pickResult.pickedSprite) {
  11932. if (pickResult.pickedSprite.actionManager) {
  11933. switch (evt.button) {
  11934. case 0:
  11935. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11936. break;
  11937. case 1:
  11938. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11939. break;
  11940. case 2:
  11941. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11942. break;
  11943. }
  11944. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11945. }
  11946. }
  11947. }
  11948. };
  11949. this._onPointerUp = function (evt) {
  11950. var predicate = null;
  11951. _this._updatePointerPosition(evt);
  11952. if (!_this.onPointerUp) {
  11953. predicate = function (mesh) {
  11954. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11955. };
  11956. }
  11957. // Meshes
  11958. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11959. if (pickResult.hit && pickResult.pickedMesh) {
  11960. if (pickResult.pickedMesh.actionManager) {
  11961. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11962. }
  11963. }
  11964. if (_this.onPointerUp) {
  11965. _this.onPointerUp(evt, pickResult);
  11966. }
  11967. // Sprites
  11968. if (_this.spriteManagers.length > 0) {
  11969. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11970. if (pickResult.hit && pickResult.pickedSprite) {
  11971. if (pickResult.pickedSprite.actionManager) {
  11972. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11973. }
  11974. }
  11975. }
  11976. };
  11977. this._onKeyDown = function (evt) {
  11978. if (_this.actionManager) {
  11979. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11980. }
  11981. };
  11982. this._onKeyUp = function (evt) {
  11983. if (_this.actionManager) {
  11984. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11985. }
  11986. };
  11987. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11988. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11989. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11990. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11991. // Wheel
  11992. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  11993. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  11994. BABYLON.Tools.RegisterTopRootEvents([
  11995. { name: "keydown", handler: this._onKeyDown },
  11996. { name: "keyup", handler: this._onKeyUp }
  11997. ]);
  11998. };
  11999. Scene.prototype.detachControl = function () {
  12000. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12001. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12002. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12003. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12004. // Wheel
  12005. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12006. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12007. BABYLON.Tools.UnregisterTopRootEvents([
  12008. { name: "keydown", handler: this._onKeyDown },
  12009. { name: "keyup", handler: this._onKeyUp }
  12010. ]);
  12011. };
  12012. // Ready
  12013. Scene.prototype.isReady = function () {
  12014. if (this._pendingData.length > 0) {
  12015. return false;
  12016. }
  12017. var index;
  12018. for (index = 0; index < this._geometries.length; index++) {
  12019. var geometry = this._geometries[index];
  12020. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12021. return false;
  12022. }
  12023. }
  12024. for (index = 0; index < this.meshes.length; index++) {
  12025. var mesh = this.meshes[index];
  12026. if (!mesh.isReady()) {
  12027. return false;
  12028. }
  12029. var mat = mesh.material;
  12030. if (mat) {
  12031. if (!mat.isReady(mesh)) {
  12032. return false;
  12033. }
  12034. }
  12035. }
  12036. return true;
  12037. };
  12038. Scene.prototype.resetCachedMaterial = function () {
  12039. this._cachedMaterial = null;
  12040. };
  12041. Scene.prototype.registerBeforeRender = function (func) {
  12042. this._onBeforeRenderCallbacks.push(func);
  12043. };
  12044. Scene.prototype.unregisterBeforeRender = function (func) {
  12045. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12046. if (index > -1) {
  12047. this._onBeforeRenderCallbacks.splice(index, 1);
  12048. }
  12049. };
  12050. Scene.prototype.registerAfterRender = function (func) {
  12051. this._onAfterRenderCallbacks.push(func);
  12052. };
  12053. Scene.prototype.unregisterAfterRender = function (func) {
  12054. var index = this._onAfterRenderCallbacks.indexOf(func);
  12055. if (index > -1) {
  12056. this._onAfterRenderCallbacks.splice(index, 1);
  12057. }
  12058. };
  12059. Scene.prototype._addPendingData = function (data) {
  12060. this._pendingData.push(data);
  12061. };
  12062. Scene.prototype._removePendingData = function (data) {
  12063. var index = this._pendingData.indexOf(data);
  12064. if (index !== -1) {
  12065. this._pendingData.splice(index, 1);
  12066. }
  12067. };
  12068. Scene.prototype.getWaitingItemsCount = function () {
  12069. return this._pendingData.length;
  12070. };
  12071. /**
  12072. * Registers a function to be executed when the scene is ready.
  12073. * @param {Function} func - the function to be executed.
  12074. */
  12075. Scene.prototype.executeWhenReady = function (func) {
  12076. var _this = this;
  12077. this._onReadyCallbacks.push(func);
  12078. if (this._executeWhenReadyTimeoutId !== -1) {
  12079. return;
  12080. }
  12081. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12082. _this._checkIsReady();
  12083. }, 150);
  12084. };
  12085. Scene.prototype._checkIsReady = function () {
  12086. var _this = this;
  12087. if (this.isReady()) {
  12088. this._onReadyCallbacks.forEach(function (func) {
  12089. func();
  12090. });
  12091. this._onReadyCallbacks = [];
  12092. this._executeWhenReadyTimeoutId = -1;
  12093. return;
  12094. }
  12095. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12096. _this._checkIsReady();
  12097. }, 150);
  12098. };
  12099. // Animations
  12100. /**
  12101. * Will start the animation sequence of a given target
  12102. * @param target - the target
  12103. * @param {number} from - from which frame should animation start
  12104. * @param {number} to - till which frame should animation run.
  12105. * @param {boolean} [loop] - should the animation loop
  12106. * @param {number} [speedRatio] - the speed in which to run the animation
  12107. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12108. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12109. * @return {BABYLON.Animatable} the animatable object created for this animation
  12110. * @see BABYLON.Animatable
  12111. * @see http://doc.babylonjs.com/page.php?p=22081
  12112. */
  12113. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12114. if (speedRatio === void 0) { speedRatio = 1.0; }
  12115. this.stopAnimation(target);
  12116. if (!animatable) {
  12117. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12118. }
  12119. // Local animations
  12120. if (target.animations) {
  12121. animatable.appendAnimations(target, target.animations);
  12122. }
  12123. // Children animations
  12124. if (target.getAnimatables) {
  12125. var animatables = target.getAnimatables();
  12126. for (var index = 0; index < animatables.length; index++) {
  12127. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12128. }
  12129. }
  12130. return animatable;
  12131. };
  12132. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12133. if (speedRatio === undefined) {
  12134. speedRatio = 1.0;
  12135. }
  12136. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12137. return animatable;
  12138. };
  12139. Scene.prototype.getAnimatableByTarget = function (target) {
  12140. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12141. if (this._activeAnimatables[index].target === target) {
  12142. return this._activeAnimatables[index];
  12143. }
  12144. }
  12145. return null;
  12146. };
  12147. /**
  12148. * Will stop the animation of the given target
  12149. * @param target - the target
  12150. * @see beginAnimation
  12151. */
  12152. Scene.prototype.stopAnimation = function (target) {
  12153. var animatable = this.getAnimatableByTarget(target);
  12154. if (animatable) {
  12155. animatable.stop();
  12156. }
  12157. };
  12158. Scene.prototype._animate = function () {
  12159. if (!this.animationsEnabled) {
  12160. return;
  12161. }
  12162. if (!this._animationStartDate) {
  12163. this._animationStartDate = BABYLON.Tools.Now;
  12164. }
  12165. // Getting time
  12166. var now = BABYLON.Tools.Now;
  12167. var delay = now - this._animationStartDate;
  12168. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12169. this._activeAnimatables[index]._animate(delay);
  12170. }
  12171. };
  12172. // Matrix
  12173. Scene.prototype.getViewMatrix = function () {
  12174. return this._viewMatrix;
  12175. };
  12176. Scene.prototype.getProjectionMatrix = function () {
  12177. return this._projectionMatrix;
  12178. };
  12179. Scene.prototype.getTransformMatrix = function () {
  12180. return this._transformMatrix;
  12181. };
  12182. Scene.prototype.setTransformMatrix = function (view, projection) {
  12183. this._viewMatrix = view;
  12184. this._projectionMatrix = projection;
  12185. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12186. };
  12187. // Methods
  12188. Scene.prototype.addMesh = function (newMesh) {
  12189. newMesh.uniqueId = this._uniqueIdCounter++;
  12190. var position = this.meshes.push(newMesh);
  12191. //notify the collision coordinator
  12192. this.collisionCoordinator.onMeshAdded(newMesh);
  12193. if (this.onNewMeshAdded) {
  12194. this.onNewMeshAdded(newMesh, position, this);
  12195. }
  12196. };
  12197. Scene.prototype.removeMesh = function (toRemove) {
  12198. var index = this.meshes.indexOf(toRemove);
  12199. if (index !== -1) {
  12200. // Remove from the scene if mesh found
  12201. this.meshes.splice(index, 1);
  12202. }
  12203. //notify the collision coordinator
  12204. this.collisionCoordinator.onMeshRemoved(toRemove);
  12205. if (this.onMeshRemoved) {
  12206. this.onMeshRemoved(toRemove);
  12207. }
  12208. return index;
  12209. };
  12210. Scene.prototype.removeSkeleton = function (toRemove) {
  12211. var index = this.skeletons.indexOf(toRemove);
  12212. if (index !== -1) {
  12213. // Remove from the scene if mesh found
  12214. this.skeletons.splice(index, 1);
  12215. }
  12216. return index;
  12217. };
  12218. Scene.prototype.removeLight = function (toRemove) {
  12219. var index = this.lights.indexOf(toRemove);
  12220. if (index !== -1) {
  12221. // Remove from the scene if mesh found
  12222. this.lights.splice(index, 1);
  12223. }
  12224. if (this.onLightRemoved) {
  12225. this.onLightRemoved(toRemove);
  12226. }
  12227. return index;
  12228. };
  12229. Scene.prototype.removeCamera = function (toRemove) {
  12230. var index = this.cameras.indexOf(toRemove);
  12231. if (index !== -1) {
  12232. // Remove from the scene if mesh found
  12233. this.cameras.splice(index, 1);
  12234. }
  12235. // Remove from activeCameras
  12236. var index2 = this.activeCameras.indexOf(toRemove);
  12237. if (index2 !== -1) {
  12238. // Remove from the scene if mesh found
  12239. this.activeCameras.splice(index2, 1);
  12240. }
  12241. // Reset the activeCamera
  12242. if (this.activeCamera === toRemove) {
  12243. if (this.cameras.length > 0) {
  12244. this.activeCamera = this.cameras[0];
  12245. }
  12246. else {
  12247. this.activeCamera = null;
  12248. }
  12249. }
  12250. if (this.onCameraRemoved) {
  12251. this.onCameraRemoved(toRemove);
  12252. }
  12253. return index;
  12254. };
  12255. Scene.prototype.addLight = function (newLight) {
  12256. newLight.uniqueId = this._uniqueIdCounter++;
  12257. var position = this.lights.push(newLight);
  12258. if (this.onNewLightAdded) {
  12259. this.onNewLightAdded(newLight, position, this);
  12260. }
  12261. };
  12262. Scene.prototype.addCamera = function (newCamera) {
  12263. newCamera.uniqueId = this._uniqueIdCounter++;
  12264. var position = this.cameras.push(newCamera);
  12265. if (this.onNewCameraAdded) {
  12266. this.onNewCameraAdded(newCamera, position, this);
  12267. }
  12268. };
  12269. /**
  12270. * sets the active camera of the scene using its ID
  12271. * @param {string} id - the camera's ID
  12272. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12273. * @see activeCamera
  12274. */
  12275. Scene.prototype.setActiveCameraByID = function (id) {
  12276. var camera = this.getCameraByID(id);
  12277. if (camera) {
  12278. this.activeCamera = camera;
  12279. return camera;
  12280. }
  12281. return null;
  12282. };
  12283. /**
  12284. * sets the active camera of the scene using its name
  12285. * @param {string} name - the camera's name
  12286. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12287. * @see activeCamera
  12288. */
  12289. Scene.prototype.setActiveCameraByName = function (name) {
  12290. var camera = this.getCameraByName(name);
  12291. if (camera) {
  12292. this.activeCamera = camera;
  12293. return camera;
  12294. }
  12295. return null;
  12296. };
  12297. /**
  12298. * get a material using its id
  12299. * @param {string} the material's ID
  12300. * @return {BABYLON.Material|null} the material or null if none found.
  12301. */
  12302. Scene.prototype.getMaterialByID = function (id) {
  12303. for (var index = 0; index < this.materials.length; index++) {
  12304. if (this.materials[index].id === id) {
  12305. return this.materials[index];
  12306. }
  12307. }
  12308. return null;
  12309. };
  12310. /**
  12311. * get a material using its name
  12312. * @param {string} the material's name
  12313. * @return {BABYLON.Material|null} the material or null if none found.
  12314. */
  12315. Scene.prototype.getMaterialByName = function (name) {
  12316. for (var index = 0; index < this.materials.length; index++) {
  12317. if (this.materials[index].name === name) {
  12318. return this.materials[index];
  12319. }
  12320. }
  12321. return null;
  12322. };
  12323. Scene.prototype.getLensFlareSystemByName = function (name) {
  12324. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12325. if (this.lensFlareSystems[index].name === name) {
  12326. return this.lensFlareSystems[index];
  12327. }
  12328. }
  12329. return null;
  12330. };
  12331. Scene.prototype.getCameraByID = function (id) {
  12332. for (var index = 0; index < this.cameras.length; index++) {
  12333. if (this.cameras[index].id === id) {
  12334. return this.cameras[index];
  12335. }
  12336. }
  12337. return null;
  12338. };
  12339. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12340. for (var index = 0; index < this.cameras.length; index++) {
  12341. if (this.cameras[index].uniqueId === uniqueId) {
  12342. return this.cameras[index];
  12343. }
  12344. }
  12345. return null;
  12346. };
  12347. /**
  12348. * get a camera using its name
  12349. * @param {string} the camera's name
  12350. * @return {BABYLON.Camera|null} the camera or null if none found.
  12351. */
  12352. Scene.prototype.getCameraByName = function (name) {
  12353. for (var index = 0; index < this.cameras.length; index++) {
  12354. if (this.cameras[index].name === name) {
  12355. return this.cameras[index];
  12356. }
  12357. }
  12358. return null;
  12359. };
  12360. /**
  12361. * get a light node using its name
  12362. * @param {string} the light's name
  12363. * @return {BABYLON.Light|null} the light or null if none found.
  12364. */
  12365. Scene.prototype.getLightByName = function (name) {
  12366. for (var index = 0; index < this.lights.length; index++) {
  12367. if (this.lights[index].name === name) {
  12368. return this.lights[index];
  12369. }
  12370. }
  12371. return null;
  12372. };
  12373. /**
  12374. * get a light node using its ID
  12375. * @param {string} the light's id
  12376. * @return {BABYLON.Light|null} the light or null if none found.
  12377. */
  12378. Scene.prototype.getLightByID = function (id) {
  12379. for (var index = 0; index < this.lights.length; index++) {
  12380. if (this.lights[index].id === id) {
  12381. return this.lights[index];
  12382. }
  12383. }
  12384. return null;
  12385. };
  12386. /**
  12387. * get a light node using its scene-generated unique ID
  12388. * @param {number} the light's unique id
  12389. * @return {BABYLON.Light|null} the light or null if none found.
  12390. */
  12391. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12392. for (var index = 0; index < this.lights.length; index++) {
  12393. if (this.lights[index].uniqueId === uniqueId) {
  12394. return this.lights[index];
  12395. }
  12396. }
  12397. return null;
  12398. };
  12399. /**
  12400. * get a geometry using its ID
  12401. * @param {string} the geometry's id
  12402. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12403. */
  12404. Scene.prototype.getGeometryByID = function (id) {
  12405. for (var index = 0; index < this._geometries.length; index++) {
  12406. if (this._geometries[index].id === id) {
  12407. return this._geometries[index];
  12408. }
  12409. }
  12410. return null;
  12411. };
  12412. /**
  12413. * add a new geometry to this scene.
  12414. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12415. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12416. * @return {boolean} was the geometry added or not
  12417. */
  12418. Scene.prototype.pushGeometry = function (geometry, force) {
  12419. if (!force && this.getGeometryByID(geometry.id)) {
  12420. return false;
  12421. }
  12422. this._geometries.push(geometry);
  12423. //notify the collision coordinator
  12424. this.collisionCoordinator.onGeometryAdded(geometry);
  12425. if (this.onGeometryAdded) {
  12426. this.onGeometryAdded(geometry);
  12427. }
  12428. return true;
  12429. };
  12430. /**
  12431. * Removes an existing geometry
  12432. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12433. * @return {boolean} was the geometry removed or not
  12434. */
  12435. Scene.prototype.removeGeometry = function (geometry) {
  12436. var index = this._geometries.indexOf(geometry);
  12437. if (index > -1) {
  12438. this._geometries.splice(index, 1);
  12439. //notify the collision coordinator
  12440. this.collisionCoordinator.onGeometryDeleted(geometry);
  12441. if (this.onGeometryRemoved) {
  12442. this.onGeometryRemoved(geometry);
  12443. }
  12444. return true;
  12445. }
  12446. return false;
  12447. };
  12448. Scene.prototype.getGeometries = function () {
  12449. return this._geometries;
  12450. };
  12451. /**
  12452. * Get the first added mesh found of a given ID
  12453. * @param {string} id - the id to search for
  12454. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12455. */
  12456. Scene.prototype.getMeshByID = function (id) {
  12457. for (var index = 0; index < this.meshes.length; index++) {
  12458. if (this.meshes[index].id === id) {
  12459. return this.meshes[index];
  12460. }
  12461. }
  12462. return null;
  12463. };
  12464. /**
  12465. * Get a mesh with its auto-generated unique id
  12466. * @param {number} uniqueId - the unique id to search for
  12467. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12468. */
  12469. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12470. for (var index = 0; index < this.meshes.length; index++) {
  12471. if (this.meshes[index].uniqueId === uniqueId) {
  12472. return this.meshes[index];
  12473. }
  12474. }
  12475. return null;
  12476. };
  12477. /**
  12478. * Get a the last added mesh found of a given ID
  12479. * @param {string} id - the id to search for
  12480. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12481. */
  12482. Scene.prototype.getLastMeshByID = function (id) {
  12483. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12484. if (this.meshes[index].id === id) {
  12485. return this.meshes[index];
  12486. }
  12487. }
  12488. return null;
  12489. };
  12490. /**
  12491. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12492. * @param {string} id - the id to search for
  12493. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12494. */
  12495. Scene.prototype.getLastEntryByID = function (id) {
  12496. var index;
  12497. for (index = this.meshes.length - 1; index >= 0; index--) {
  12498. if (this.meshes[index].id === id) {
  12499. return this.meshes[index];
  12500. }
  12501. }
  12502. for (index = this.cameras.length - 1; index >= 0; index--) {
  12503. if (this.cameras[index].id === id) {
  12504. return this.cameras[index];
  12505. }
  12506. }
  12507. for (index = this.lights.length - 1; index >= 0; index--) {
  12508. if (this.lights[index].id === id) {
  12509. return this.lights[index];
  12510. }
  12511. }
  12512. return null;
  12513. };
  12514. Scene.prototype.getNodeByID = function (id) {
  12515. var mesh = this.getMeshByID(id);
  12516. if (mesh) {
  12517. return mesh;
  12518. }
  12519. var light = this.getLightByID(id);
  12520. if (light) {
  12521. return light;
  12522. }
  12523. return this.getCameraByID(id);
  12524. };
  12525. Scene.prototype.getNodeByName = function (name) {
  12526. var mesh = this.getMeshByName(name);
  12527. if (mesh) {
  12528. return mesh;
  12529. }
  12530. var light = this.getLightByName(name);
  12531. if (light) {
  12532. return light;
  12533. }
  12534. return this.getCameraByName(name);
  12535. };
  12536. Scene.prototype.getMeshByName = function (name) {
  12537. for (var index = 0; index < this.meshes.length; index++) {
  12538. if (this.meshes[index].name === name) {
  12539. return this.meshes[index];
  12540. }
  12541. }
  12542. return null;
  12543. };
  12544. Scene.prototype.getSoundByName = function (name) {
  12545. var index;
  12546. if (BABYLON.AudioEngine) {
  12547. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12548. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12549. return this.mainSoundTrack.soundCollection[index];
  12550. }
  12551. }
  12552. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12553. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12554. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12555. return this.soundTracks[sdIndex].soundCollection[index];
  12556. }
  12557. }
  12558. }
  12559. }
  12560. return null;
  12561. };
  12562. Scene.prototype.getLastSkeletonByID = function (id) {
  12563. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12564. if (this.skeletons[index].id === id) {
  12565. return this.skeletons[index];
  12566. }
  12567. }
  12568. return null;
  12569. };
  12570. Scene.prototype.getSkeletonById = function (id) {
  12571. for (var index = 0; index < this.skeletons.length; index++) {
  12572. if (this.skeletons[index].id === id) {
  12573. return this.skeletons[index];
  12574. }
  12575. }
  12576. return null;
  12577. };
  12578. Scene.prototype.getSkeletonByName = function (name) {
  12579. for (var index = 0; index < this.skeletons.length; index++) {
  12580. if (this.skeletons[index].name === name) {
  12581. return this.skeletons[index];
  12582. }
  12583. }
  12584. return null;
  12585. };
  12586. Scene.prototype.isActiveMesh = function (mesh) {
  12587. return (this._activeMeshes.indexOf(mesh) !== -1);
  12588. };
  12589. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12590. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12591. var material = subMesh.getMaterial();
  12592. if (mesh.showSubMeshesBoundingBox) {
  12593. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12594. }
  12595. if (material) {
  12596. // Render targets
  12597. if (material.getRenderTargetTextures) {
  12598. if (this._processedMaterials.indexOf(material) === -1) {
  12599. this._processedMaterials.push(material);
  12600. this._renderTargets.concat(material.getRenderTargetTextures());
  12601. }
  12602. }
  12603. // Dispatch
  12604. this._activeIndices += subMesh.indexCount;
  12605. this._renderingManager.dispatch(subMesh);
  12606. }
  12607. }
  12608. };
  12609. Scene.prototype._evaluateActiveMeshes = function () {
  12610. this.activeCamera._activeMeshes.reset();
  12611. this._activeMeshes.reset();
  12612. this._renderingManager.reset();
  12613. this._processedMaterials.reset();
  12614. this._activeParticleSystems.reset();
  12615. this._activeSkeletons.reset();
  12616. this._softwareSkinnedMeshes.reset();
  12617. this._boundingBoxRenderer.reset();
  12618. this._edgesRenderers.reset();
  12619. if (!this._frustumPlanes) {
  12620. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12621. }
  12622. else {
  12623. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12624. }
  12625. // Meshes
  12626. var meshes;
  12627. var len;
  12628. if (this._selectionOctree) {
  12629. var selection = this._selectionOctree.select(this._frustumPlanes);
  12630. meshes = selection.data;
  12631. len = selection.length;
  12632. }
  12633. else {
  12634. len = this.meshes.length;
  12635. meshes = this.meshes;
  12636. }
  12637. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12638. var mesh = meshes[meshIndex];
  12639. if (mesh.isBlocked) {
  12640. continue;
  12641. }
  12642. this._totalVertices += mesh.getTotalVertices();
  12643. if (!mesh.isReady() || !mesh.isEnabled()) {
  12644. continue;
  12645. }
  12646. mesh.computeWorldMatrix();
  12647. // Intersections
  12648. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12649. this._meshesForIntersections.pushNoDuplicate(mesh);
  12650. }
  12651. // Switch to current LOD
  12652. var meshLOD = mesh.getLOD(this.activeCamera);
  12653. if (!meshLOD) {
  12654. continue;
  12655. }
  12656. mesh._preActivate();
  12657. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12658. this._activeMeshes.push(mesh);
  12659. this.activeCamera._activeMeshes.push(mesh);
  12660. mesh._activate(this._renderId);
  12661. this._activeMesh(meshLOD);
  12662. }
  12663. }
  12664. // Particle systems
  12665. var beforeParticlesDate = BABYLON.Tools.Now;
  12666. if (this.particlesEnabled) {
  12667. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12668. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12669. var particleSystem = this.particleSystems[particleIndex];
  12670. if (!particleSystem.isStarted()) {
  12671. continue;
  12672. }
  12673. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12674. this._activeParticleSystems.push(particleSystem);
  12675. particleSystem.animate();
  12676. }
  12677. }
  12678. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12679. }
  12680. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12681. };
  12682. Scene.prototype._activeMesh = function (mesh) {
  12683. if (mesh.skeleton && this.skeletonsEnabled) {
  12684. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12685. if (!mesh.computeBonesUsingShaders) {
  12686. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  12687. }
  12688. }
  12689. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12690. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12691. }
  12692. if (mesh._edgesRenderer) {
  12693. this._edgesRenderers.push(mesh._edgesRenderer);
  12694. }
  12695. if (mesh && mesh.subMeshes) {
  12696. // Submeshes Octrees
  12697. var len;
  12698. var subMeshes;
  12699. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12700. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12701. len = intersections.length;
  12702. subMeshes = intersections.data;
  12703. }
  12704. else {
  12705. subMeshes = mesh.subMeshes;
  12706. len = subMeshes.length;
  12707. }
  12708. for (var subIndex = 0; subIndex < len; subIndex++) {
  12709. var subMesh = subMeshes[subIndex];
  12710. this._evaluateSubMesh(subMesh, mesh);
  12711. }
  12712. }
  12713. };
  12714. Scene.prototype.updateTransformMatrix = function (force) {
  12715. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12716. };
  12717. Scene.prototype._renderForCamera = function (camera) {
  12718. var engine = this._engine;
  12719. this.activeCamera = camera;
  12720. if (!this.activeCamera)
  12721. throw new Error("Active camera not set");
  12722. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12723. // Viewport
  12724. engine.setViewport(this.activeCamera.viewport);
  12725. // Camera
  12726. this.resetCachedMaterial();
  12727. this._renderId++;
  12728. this.updateTransformMatrix();
  12729. if (this.beforeCameraRender) {
  12730. this.beforeCameraRender(this.activeCamera);
  12731. }
  12732. // Meshes
  12733. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12734. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12735. this._evaluateActiveMeshes();
  12736. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12737. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12738. // Skeletons
  12739. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12740. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12741. skeleton.prepare();
  12742. }
  12743. // Software skinning
  12744. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  12745. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  12746. mesh.applySkeleton(mesh.skeleton);
  12747. }
  12748. // Render targets
  12749. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12750. if (this.renderTargetsEnabled) {
  12751. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12752. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12753. var renderTarget = this._renderTargets.data[renderIndex];
  12754. if (renderTarget._shouldRender()) {
  12755. this._renderId++;
  12756. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12757. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12758. }
  12759. }
  12760. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12761. this._renderId++;
  12762. }
  12763. if (this._renderTargets.length > 0) {
  12764. engine.restoreDefaultFramebuffer();
  12765. }
  12766. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12767. // Prepare Frame
  12768. this.postProcessManager._prepareFrame();
  12769. var beforeRenderDate = BABYLON.Tools.Now;
  12770. // Backgrounds
  12771. var layerIndex;
  12772. var layer;
  12773. if (this.layers.length) {
  12774. engine.setDepthBuffer(false);
  12775. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12776. layer = this.layers[layerIndex];
  12777. if (layer.isBackground) {
  12778. layer.render();
  12779. }
  12780. }
  12781. engine.setDepthBuffer(true);
  12782. }
  12783. // Render
  12784. BABYLON.Tools.StartPerformanceCounter("Main render");
  12785. this._renderingManager.render(null, null, true, true);
  12786. BABYLON.Tools.EndPerformanceCounter("Main render");
  12787. // Bounding boxes
  12788. this._boundingBoxRenderer.render();
  12789. // Edges
  12790. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  12791. this._edgesRenderers.data[edgesRendererIndex].render();
  12792. }
  12793. // Lens flares
  12794. if (this.lensFlaresEnabled) {
  12795. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12796. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12797. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  12798. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  12799. lensFlareSystem.render();
  12800. }
  12801. }
  12802. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12803. }
  12804. // Foregrounds
  12805. if (this.layers.length) {
  12806. engine.setDepthBuffer(false);
  12807. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12808. layer = this.layers[layerIndex];
  12809. if (!layer.isBackground) {
  12810. layer.render();
  12811. }
  12812. }
  12813. engine.setDepthBuffer(true);
  12814. }
  12815. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12816. // Finalize frame
  12817. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12818. // Update camera
  12819. this.activeCamera._updateFromScene();
  12820. // Reset some special arrays
  12821. this._renderTargets.reset();
  12822. if (this.afterCameraRender) {
  12823. this.afterCameraRender(this.activeCamera);
  12824. }
  12825. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12826. };
  12827. Scene.prototype._processSubCameras = function (camera) {
  12828. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  12829. this._renderForCamera(camera);
  12830. return;
  12831. }
  12832. // rig cameras
  12833. for (var index = 0; index < camera._rigCameras.length; index++) {
  12834. this._renderForCamera(camera._rigCameras[index]);
  12835. }
  12836. this.activeCamera = camera;
  12837. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12838. // Update camera
  12839. this.activeCamera._updateFromScene();
  12840. };
  12841. Scene.prototype._checkIntersections = function () {
  12842. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12843. var sourceMesh = this._meshesForIntersections.data[index];
  12844. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12845. var action = sourceMesh.actionManager.actions[actionIndex];
  12846. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12847. var parameters = action.getTriggerParameter();
  12848. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12849. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12850. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12851. if (areIntersecting && currentIntersectionInProgress === -1) {
  12852. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12853. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12854. sourceMesh._intersectionsInProgress.push(otherMesh);
  12855. }
  12856. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12857. sourceMesh._intersectionsInProgress.push(otherMesh);
  12858. }
  12859. }
  12860. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12861. //They intersected, and now they don't.
  12862. //is this trigger an exit trigger? execute an event.
  12863. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12864. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12865. }
  12866. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12867. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12868. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12869. }
  12870. }
  12871. }
  12872. }
  12873. }
  12874. };
  12875. Scene.prototype.render = function () {
  12876. var startDate = BABYLON.Tools.Now;
  12877. this._particlesDuration = 0;
  12878. this._spritesDuration = 0;
  12879. this._activeParticles = 0;
  12880. this._renderDuration = 0;
  12881. this._renderTargetsDuration = 0;
  12882. this._evaluateActiveMeshesDuration = 0;
  12883. this._totalVertices = 0;
  12884. this._activeIndices = 0;
  12885. this._activeBones = 0;
  12886. this.getEngine().resetDrawCalls();
  12887. this._meshesForIntersections.reset();
  12888. this.resetCachedMaterial();
  12889. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12890. // Actions
  12891. if (this.actionManager) {
  12892. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12893. }
  12894. //Simplification Queue
  12895. if (this.simplificationQueue && !this.simplificationQueue.running) {
  12896. this.simplificationQueue.executeNext();
  12897. }
  12898. // Animations
  12899. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12900. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12901. this._animate();
  12902. // Physics
  12903. if (this._physicsEngine) {
  12904. BABYLON.Tools.StartPerformanceCounter("Physics");
  12905. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12906. BABYLON.Tools.EndPerformanceCounter("Physics");
  12907. }
  12908. // Before render
  12909. if (this.beforeRender) {
  12910. this.beforeRender();
  12911. }
  12912. var callbackIndex;
  12913. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12914. this._onBeforeRenderCallbacks[callbackIndex]();
  12915. }
  12916. // Customs render targets
  12917. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12918. var engine = this.getEngine();
  12919. var currentActiveCamera = this.activeCamera;
  12920. if (this.renderTargetsEnabled) {
  12921. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12922. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12923. var renderTarget = this.customRenderTargets[customIndex];
  12924. if (renderTarget._shouldRender()) {
  12925. this._renderId++;
  12926. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12927. if (!this.activeCamera)
  12928. throw new Error("Active camera not set");
  12929. // Viewport
  12930. engine.setViewport(this.activeCamera.viewport);
  12931. // Camera
  12932. this.updateTransformMatrix();
  12933. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12934. }
  12935. }
  12936. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12937. this._renderId++;
  12938. }
  12939. if (this.customRenderTargets.length > 0) {
  12940. engine.restoreDefaultFramebuffer();
  12941. }
  12942. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12943. this.activeCamera = currentActiveCamera;
  12944. // Procedural textures
  12945. if (this.proceduralTexturesEnabled) {
  12946. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12947. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12948. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12949. if (proceduralTexture._shouldRender()) {
  12950. proceduralTexture.render();
  12951. }
  12952. }
  12953. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12954. }
  12955. // Clear
  12956. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12957. // Shadows
  12958. if (this.shadowsEnabled) {
  12959. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12960. var light = this.lights[lightIndex];
  12961. var shadowGenerator = light.getShadowGenerator();
  12962. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12963. this._renderTargets.push(shadowGenerator.getShadowMap());
  12964. }
  12965. }
  12966. }
  12967. // Depth renderer
  12968. if (this._depthRenderer) {
  12969. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12970. }
  12971. // RenderPipeline
  12972. this.postProcessRenderPipelineManager.update();
  12973. // Multi-cameras?
  12974. if (this.activeCameras.length > 0) {
  12975. var currentRenderId = this._renderId;
  12976. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12977. this._renderId = currentRenderId;
  12978. this._processSubCameras(this.activeCameras[cameraIndex]);
  12979. }
  12980. }
  12981. else {
  12982. if (!this.activeCamera) {
  12983. throw new Error("No camera defined");
  12984. }
  12985. this._processSubCameras(this.activeCamera);
  12986. }
  12987. // Intersection checks
  12988. this._checkIntersections();
  12989. // Update the audio listener attached to the camera
  12990. if (BABYLON.AudioEngine) {
  12991. this._updateAudioParameters();
  12992. }
  12993. // After render
  12994. if (this.afterRender) {
  12995. this.afterRender();
  12996. }
  12997. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12998. this._onAfterRenderCallbacks[callbackIndex]();
  12999. }
  13000. // Cleaning
  13001. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13002. this._toBeDisposed.data[index].dispose();
  13003. this._toBeDisposed[index] = null;
  13004. }
  13005. this._toBeDisposed.reset();
  13006. if (this.dumpNextRenderTargets) {
  13007. this.dumpNextRenderTargets = false;
  13008. }
  13009. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13010. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13011. };
  13012. Scene.prototype._updateAudioParameters = function () {
  13013. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13014. return;
  13015. }
  13016. var listeningCamera;
  13017. var audioEngine = BABYLON.Engine.audioEngine;
  13018. if (this.activeCameras.length > 0) {
  13019. listeningCamera = this.activeCameras[0];
  13020. }
  13021. else {
  13022. listeningCamera = this.activeCamera;
  13023. }
  13024. if (listeningCamera && audioEngine.canUseWebAudio) {
  13025. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13026. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13027. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13028. cameraDirection.normalize();
  13029. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13030. var i;
  13031. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13032. var sound = this.mainSoundTrack.soundCollection[i];
  13033. if (sound.useCustomAttenuation) {
  13034. sound.updateDistanceFromListener();
  13035. }
  13036. }
  13037. for (i = 0; i < this.soundTracks.length; i++) {
  13038. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13039. sound = this.soundTracks[i].soundCollection[j];
  13040. if (sound.useCustomAttenuation) {
  13041. sound.updateDistanceFromListener();
  13042. }
  13043. }
  13044. }
  13045. }
  13046. };
  13047. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13048. // Audio
  13049. get: function () {
  13050. return this._audioEnabled;
  13051. },
  13052. set: function (value) {
  13053. this._audioEnabled = value;
  13054. if (BABYLON.AudioEngine) {
  13055. if (this._audioEnabled) {
  13056. this._enableAudio();
  13057. }
  13058. else {
  13059. this._disableAudio();
  13060. }
  13061. }
  13062. },
  13063. enumerable: true,
  13064. configurable: true
  13065. });
  13066. Scene.prototype._disableAudio = function () {
  13067. var i;
  13068. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13069. this.mainSoundTrack.soundCollection[i].pause();
  13070. }
  13071. for (i = 0; i < this.soundTracks.length; i++) {
  13072. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13073. this.soundTracks[i].soundCollection[j].pause();
  13074. }
  13075. }
  13076. };
  13077. Scene.prototype._enableAudio = function () {
  13078. var i;
  13079. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13080. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13081. this.mainSoundTrack.soundCollection[i].play();
  13082. }
  13083. }
  13084. for (i = 0; i < this.soundTracks.length; i++) {
  13085. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13086. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13087. this.soundTracks[i].soundCollection[j].play();
  13088. }
  13089. }
  13090. }
  13091. };
  13092. Object.defineProperty(Scene.prototype, "headphone", {
  13093. get: function () {
  13094. return this._headphone;
  13095. },
  13096. set: function (value) {
  13097. this._headphone = value;
  13098. if (BABYLON.AudioEngine) {
  13099. if (this._headphone) {
  13100. this._switchAudioModeForHeadphones();
  13101. }
  13102. else {
  13103. this._switchAudioModeForNormalSpeakers();
  13104. }
  13105. }
  13106. },
  13107. enumerable: true,
  13108. configurable: true
  13109. });
  13110. Scene.prototype._switchAudioModeForHeadphones = function () {
  13111. this.mainSoundTrack.switchPanningModelToHRTF();
  13112. for (var i = 0; i < this.soundTracks.length; i++) {
  13113. this.soundTracks[i].switchPanningModelToHRTF();
  13114. }
  13115. };
  13116. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13117. this.mainSoundTrack.switchPanningModelToEqualPower();
  13118. for (var i = 0; i < this.soundTracks.length; i++) {
  13119. this.soundTracks[i].switchPanningModelToEqualPower();
  13120. }
  13121. };
  13122. Scene.prototype.enableDepthRenderer = function () {
  13123. if (this._depthRenderer) {
  13124. return this._depthRenderer;
  13125. }
  13126. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13127. return this._depthRenderer;
  13128. };
  13129. Scene.prototype.disableDepthRenderer = function () {
  13130. if (!this._depthRenderer) {
  13131. return;
  13132. }
  13133. this._depthRenderer.dispose();
  13134. this._depthRenderer = null;
  13135. };
  13136. Scene.prototype.dispose = function () {
  13137. this.beforeRender = null;
  13138. this.afterRender = null;
  13139. this.skeletons = [];
  13140. this._boundingBoxRenderer.dispose();
  13141. if (this._depthRenderer) {
  13142. this._depthRenderer.dispose();
  13143. }
  13144. // Debug layer
  13145. this.debugLayer.hide();
  13146. // Events
  13147. if (this.onDispose) {
  13148. this.onDispose();
  13149. }
  13150. this._onBeforeRenderCallbacks = [];
  13151. this._onAfterRenderCallbacks = [];
  13152. this.detachControl();
  13153. // Release sounds & sounds tracks
  13154. if (BABYLON.AudioEngine) {
  13155. this.disposeSounds();
  13156. }
  13157. // Detach cameras
  13158. var canvas = this._engine.getRenderingCanvas();
  13159. var index;
  13160. for (index = 0; index < this.cameras.length; index++) {
  13161. this.cameras[index].detachControl(canvas);
  13162. }
  13163. // Release lights
  13164. while (this.lights.length) {
  13165. this.lights[0].dispose();
  13166. }
  13167. // Release meshes
  13168. while (this.meshes.length) {
  13169. this.meshes[0].dispose(true);
  13170. }
  13171. // Release cameras
  13172. while (this.cameras.length) {
  13173. this.cameras[0].dispose();
  13174. }
  13175. // Release materials
  13176. while (this.materials.length) {
  13177. this.materials[0].dispose();
  13178. }
  13179. // Release particles
  13180. while (this.particleSystems.length) {
  13181. this.particleSystems[0].dispose();
  13182. }
  13183. // Release sprites
  13184. while (this.spriteManagers.length) {
  13185. this.spriteManagers[0].dispose();
  13186. }
  13187. // Release layers
  13188. while (this.layers.length) {
  13189. this.layers[0].dispose();
  13190. }
  13191. // Release textures
  13192. while (this.textures.length) {
  13193. this.textures[0].dispose();
  13194. }
  13195. // Post-processes
  13196. this.postProcessManager.dispose();
  13197. // Physics
  13198. if (this._physicsEngine) {
  13199. this.disablePhysicsEngine();
  13200. }
  13201. // Remove from engine
  13202. index = this._engine.scenes.indexOf(this);
  13203. if (index > -1) {
  13204. this._engine.scenes.splice(index, 1);
  13205. }
  13206. this._engine.wipeCaches();
  13207. };
  13208. // Release sounds & sounds tracks
  13209. Scene.prototype.disposeSounds = function () {
  13210. this.mainSoundTrack.dispose();
  13211. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13212. this.soundTracks[scIndex].dispose();
  13213. }
  13214. };
  13215. // Octrees
  13216. Scene.prototype.getWorldExtends = function () {
  13217. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13218. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13219. for (var index = 0; index < this.meshes.length; index++) {
  13220. var mesh = this.meshes[index];
  13221. mesh.computeWorldMatrix(true);
  13222. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13223. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13224. BABYLON.Tools.CheckExtends(minBox, min, max);
  13225. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13226. }
  13227. return {
  13228. min: min,
  13229. max: max
  13230. };
  13231. };
  13232. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13233. if (maxCapacity === void 0) { maxCapacity = 64; }
  13234. if (maxDepth === void 0) { maxDepth = 2; }
  13235. if (!this._selectionOctree) {
  13236. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13237. }
  13238. var worldExtends = this.getWorldExtends();
  13239. // Update octree
  13240. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13241. return this._selectionOctree;
  13242. };
  13243. // Picking
  13244. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13245. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13246. var engine = this._engine;
  13247. if (!camera) {
  13248. if (!this.activeCamera)
  13249. throw new Error("Active camera not set");
  13250. camera = this.activeCamera;
  13251. }
  13252. var cameraViewport = camera.viewport;
  13253. var viewport = cameraViewport.toGlobal(engine);
  13254. // Moving coordinates to local viewport world
  13255. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13256. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13257. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13258. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13259. };
  13260. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13261. var engine = this._engine;
  13262. if (!camera) {
  13263. if (!this.activeCamera)
  13264. throw new Error("Active camera not set");
  13265. camera = this.activeCamera;
  13266. }
  13267. var cameraViewport = camera.viewport;
  13268. var viewport = cameraViewport.toGlobal(engine);
  13269. var identity = BABYLON.Matrix.Identity();
  13270. // Moving coordinates to local viewport world
  13271. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13272. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13273. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13274. };
  13275. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13276. var pickingInfo = null;
  13277. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13278. var mesh = this.meshes[meshIndex];
  13279. if (predicate) {
  13280. if (!predicate(mesh)) {
  13281. continue;
  13282. }
  13283. }
  13284. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13285. continue;
  13286. }
  13287. var world = mesh.getWorldMatrix();
  13288. var ray = rayFunction(world);
  13289. var result = mesh.intersects(ray, fastCheck);
  13290. if (!result || !result.hit)
  13291. continue;
  13292. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13293. continue;
  13294. pickingInfo = result;
  13295. if (fastCheck) {
  13296. break;
  13297. }
  13298. }
  13299. return pickingInfo || new BABYLON.PickingInfo();
  13300. };
  13301. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13302. var pickingInfo = null;
  13303. camera = camera || this.activeCamera;
  13304. if (this.spriteManagers.length > 0) {
  13305. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13306. var spriteManager = this.spriteManagers[spriteIndex];
  13307. if (!spriteManager.isPickable) {
  13308. continue;
  13309. }
  13310. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13311. if (!result || !result.hit)
  13312. continue;
  13313. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13314. continue;
  13315. pickingInfo = result;
  13316. if (fastCheck) {
  13317. break;
  13318. }
  13319. }
  13320. }
  13321. return pickingInfo || new BABYLON.PickingInfo();
  13322. };
  13323. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13324. var _this = this;
  13325. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13326. /// <param name="x">X position on screen</param>
  13327. /// <param name="y">Y position on screen</param>
  13328. /// <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>
  13329. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13330. /// <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>
  13331. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13332. };
  13333. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13334. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13335. /// <param name="x">X position on screen</param>
  13336. /// <param name="y">Y position on screen</param>
  13337. /// <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>
  13338. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13339. /// <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>
  13340. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13341. };
  13342. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13343. var _this = this;
  13344. return this._internalPick(function (world) {
  13345. if (!_this._pickWithRayInverseMatrix) {
  13346. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13347. }
  13348. world.invertToRef(_this._pickWithRayInverseMatrix);
  13349. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13350. }, predicate, fastCheck);
  13351. };
  13352. Scene.prototype.setPointerOverMesh = function (mesh) {
  13353. if (this._pointerOverMesh === mesh) {
  13354. return;
  13355. }
  13356. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13357. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13358. }
  13359. this._pointerOverMesh = mesh;
  13360. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13361. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13362. }
  13363. };
  13364. Scene.prototype.getPointerOverMesh = function () {
  13365. return this._pointerOverMesh;
  13366. };
  13367. // Physics
  13368. Scene.prototype.getPhysicsEngine = function () {
  13369. return this._physicsEngine;
  13370. };
  13371. /**
  13372. * Enables physics to the current scene
  13373. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13374. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13375. * @return {boolean} was the physics engine initialized
  13376. */
  13377. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13378. if (this._physicsEngine) {
  13379. return true;
  13380. }
  13381. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13382. if (!this._physicsEngine.isSupported()) {
  13383. this._physicsEngine = null;
  13384. return false;
  13385. }
  13386. this._physicsEngine._initialize(gravity);
  13387. return true;
  13388. };
  13389. Scene.prototype.disablePhysicsEngine = function () {
  13390. if (!this._physicsEngine) {
  13391. return;
  13392. }
  13393. this._physicsEngine.dispose();
  13394. this._physicsEngine = undefined;
  13395. };
  13396. Scene.prototype.isPhysicsEnabled = function () {
  13397. return this._physicsEngine !== undefined;
  13398. };
  13399. /**
  13400. * Sets the gravity of the physics engine (and NOT of the scene)
  13401. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13402. */
  13403. Scene.prototype.setGravity = function (gravity) {
  13404. if (!this._physicsEngine) {
  13405. return;
  13406. }
  13407. this._physicsEngine._setGravity(gravity);
  13408. };
  13409. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13410. if (parts.parts) {
  13411. options = parts;
  13412. parts = parts.parts;
  13413. }
  13414. if (!this._physicsEngine) {
  13415. return null;
  13416. }
  13417. for (var index = 0; index < parts.length; index++) {
  13418. var mesh = parts[index].mesh;
  13419. mesh._physicImpostor = parts[index].impostor;
  13420. mesh._physicsMass = options.mass / parts.length;
  13421. mesh._physicsFriction = options.friction;
  13422. mesh._physicRestitution = options.restitution;
  13423. }
  13424. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13425. };
  13426. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13427. for (var index = 0; index < compound.parts.length; index++) {
  13428. var mesh = compound.parts[index].mesh;
  13429. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13430. this._physicsEngine._unregisterMesh(mesh);
  13431. }
  13432. };
  13433. // Misc.
  13434. Scene.prototype.createDefaultCameraOrLight = function () {
  13435. // Light
  13436. if (this.lights.length === 0) {
  13437. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13438. }
  13439. // Camera
  13440. if (!this.activeCamera) {
  13441. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13442. // Compute position
  13443. var worldExtends = this.getWorldExtends();
  13444. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13445. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13446. camera.setTarget(worldCenter);
  13447. this.activeCamera = camera;
  13448. }
  13449. };
  13450. // Tags
  13451. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13452. if (tagsQuery === undefined) {
  13453. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13454. return list;
  13455. }
  13456. var listByTags = [];
  13457. forEach = forEach || (function (item) { return; });
  13458. for (var i in list) {
  13459. var item = list[i];
  13460. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13461. listByTags.push(item);
  13462. forEach(item);
  13463. }
  13464. }
  13465. return listByTags;
  13466. };
  13467. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13468. return this._getByTags(this.meshes, tagsQuery, forEach);
  13469. };
  13470. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13471. return this._getByTags(this.cameras, tagsQuery, forEach);
  13472. };
  13473. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13474. return this._getByTags(this.lights, tagsQuery, forEach);
  13475. };
  13476. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13477. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13478. };
  13479. // Statics
  13480. Scene._FOGMODE_NONE = 0;
  13481. Scene._FOGMODE_EXP = 1;
  13482. Scene._FOGMODE_EXP2 = 2;
  13483. Scene._FOGMODE_LINEAR = 3;
  13484. Scene.MinDeltaTime = 1.0;
  13485. Scene.MaxDeltaTime = 1000.0;
  13486. return Scene;
  13487. })();
  13488. BABYLON.Scene = Scene;
  13489. })(BABYLON || (BABYLON = {}));
  13490. var BABYLON;
  13491. (function (BABYLON) {
  13492. var VertexBuffer = (function () {
  13493. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13494. if (engine instanceof BABYLON.Mesh) {
  13495. this._engine = engine.getScene().getEngine();
  13496. }
  13497. else {
  13498. this._engine = engine;
  13499. }
  13500. this._updatable = updatable;
  13501. this._data = data;
  13502. if (!postponeInternalCreation) {
  13503. this.create();
  13504. }
  13505. this._kind = kind;
  13506. if (stride) {
  13507. this._strideSize = stride;
  13508. return;
  13509. }
  13510. // Deduce stride from kind
  13511. switch (kind) {
  13512. case VertexBuffer.PositionKind:
  13513. this._strideSize = 3;
  13514. break;
  13515. case VertexBuffer.NormalKind:
  13516. this._strideSize = 3;
  13517. break;
  13518. case VertexBuffer.UVKind:
  13519. case VertexBuffer.UV2Kind:
  13520. case VertexBuffer.UV3Kind:
  13521. case VertexBuffer.UV4Kind:
  13522. case VertexBuffer.UV5Kind:
  13523. case VertexBuffer.UV6Kind:
  13524. this._strideSize = 2;
  13525. break;
  13526. case VertexBuffer.ColorKind:
  13527. this._strideSize = 4;
  13528. break;
  13529. case VertexBuffer.MatricesIndicesKind:
  13530. case VertexBuffer.MatricesIndicesExtraKind:
  13531. this._strideSize = 4;
  13532. break;
  13533. case VertexBuffer.MatricesWeightsKind:
  13534. case VertexBuffer.MatricesWeightsExtraKind:
  13535. this._strideSize = 4;
  13536. break;
  13537. }
  13538. }
  13539. // Properties
  13540. VertexBuffer.prototype.isUpdatable = function () {
  13541. return this._updatable;
  13542. };
  13543. VertexBuffer.prototype.getData = function () {
  13544. return this._data;
  13545. };
  13546. VertexBuffer.prototype.getBuffer = function () {
  13547. return this._buffer;
  13548. };
  13549. VertexBuffer.prototype.getStrideSize = function () {
  13550. return this._strideSize;
  13551. };
  13552. // Methods
  13553. VertexBuffer.prototype.create = function (data) {
  13554. if (!data && this._buffer) {
  13555. return; // nothing to do
  13556. }
  13557. data = data || this._data;
  13558. if (!this._buffer) {
  13559. if (this._updatable) {
  13560. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13561. }
  13562. else {
  13563. this._buffer = this._engine.createVertexBuffer(data);
  13564. }
  13565. }
  13566. if (this._updatable) {
  13567. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13568. this._data = data;
  13569. }
  13570. };
  13571. VertexBuffer.prototype.update = function (data) {
  13572. this.create(data);
  13573. };
  13574. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13575. if (!this._buffer) {
  13576. return;
  13577. }
  13578. if (this._updatable) {
  13579. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13580. this._data = null;
  13581. }
  13582. };
  13583. VertexBuffer.prototype.dispose = function () {
  13584. if (!this._buffer) {
  13585. return;
  13586. }
  13587. if (this._engine._releaseBuffer(this._buffer)) {
  13588. this._buffer = null;
  13589. }
  13590. };
  13591. Object.defineProperty(VertexBuffer, "PositionKind", {
  13592. get: function () {
  13593. return VertexBuffer._PositionKind;
  13594. },
  13595. enumerable: true,
  13596. configurable: true
  13597. });
  13598. Object.defineProperty(VertexBuffer, "NormalKind", {
  13599. get: function () {
  13600. return VertexBuffer._NormalKind;
  13601. },
  13602. enumerable: true,
  13603. configurable: true
  13604. });
  13605. Object.defineProperty(VertexBuffer, "UVKind", {
  13606. get: function () {
  13607. return VertexBuffer._UVKind;
  13608. },
  13609. enumerable: true,
  13610. configurable: true
  13611. });
  13612. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13613. get: function () {
  13614. return VertexBuffer._UV2Kind;
  13615. },
  13616. enumerable: true,
  13617. configurable: true
  13618. });
  13619. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13620. get: function () {
  13621. return VertexBuffer._UV3Kind;
  13622. },
  13623. enumerable: true,
  13624. configurable: true
  13625. });
  13626. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13627. get: function () {
  13628. return VertexBuffer._UV4Kind;
  13629. },
  13630. enumerable: true,
  13631. configurable: true
  13632. });
  13633. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13634. get: function () {
  13635. return VertexBuffer._UV5Kind;
  13636. },
  13637. enumerable: true,
  13638. configurable: true
  13639. });
  13640. Object.defineProperty(VertexBuffer, "UV6Kind", {
  13641. get: function () {
  13642. return VertexBuffer._UV6Kind;
  13643. },
  13644. enumerable: true,
  13645. configurable: true
  13646. });
  13647. Object.defineProperty(VertexBuffer, "ColorKind", {
  13648. get: function () {
  13649. return VertexBuffer._ColorKind;
  13650. },
  13651. enumerable: true,
  13652. configurable: true
  13653. });
  13654. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13655. get: function () {
  13656. return VertexBuffer._MatricesIndicesKind;
  13657. },
  13658. enumerable: true,
  13659. configurable: true
  13660. });
  13661. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13662. get: function () {
  13663. return VertexBuffer._MatricesWeightsKind;
  13664. },
  13665. enumerable: true,
  13666. configurable: true
  13667. });
  13668. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  13669. get: function () {
  13670. return VertexBuffer._MatricesIndicesExtraKind;
  13671. },
  13672. enumerable: true,
  13673. configurable: true
  13674. });
  13675. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  13676. get: function () {
  13677. return VertexBuffer._MatricesWeightsExtraKind;
  13678. },
  13679. enumerable: true,
  13680. configurable: true
  13681. });
  13682. // Enums
  13683. VertexBuffer._PositionKind = "position";
  13684. VertexBuffer._NormalKind = "normal";
  13685. VertexBuffer._UVKind = "uv";
  13686. VertexBuffer._UV2Kind = "uv2";
  13687. VertexBuffer._UV3Kind = "uv3";
  13688. VertexBuffer._UV4Kind = "uv4";
  13689. VertexBuffer._UV5Kind = "uv5";
  13690. VertexBuffer._UV6Kind = "uv6";
  13691. VertexBuffer._ColorKind = "color";
  13692. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13693. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13694. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  13695. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  13696. return VertexBuffer;
  13697. })();
  13698. BABYLON.VertexBuffer = VertexBuffer;
  13699. })(BABYLON || (BABYLON = {}));
  13700. var BABYLON;
  13701. (function (BABYLON) {
  13702. /**
  13703. * Creates an instance based on a source mesh.
  13704. */
  13705. var InstancedMesh = (function (_super) {
  13706. __extends(InstancedMesh, _super);
  13707. function InstancedMesh(name, source) {
  13708. _super.call(this, name, source.getScene());
  13709. source.instances.push(this);
  13710. this._sourceMesh = source;
  13711. this.position.copyFrom(source.position);
  13712. this.rotation.copyFrom(source.rotation);
  13713. this.scaling.copyFrom(source.scaling);
  13714. if (source.rotationQuaternion) {
  13715. this.rotationQuaternion = source.rotationQuaternion.clone();
  13716. }
  13717. this.infiniteDistance = source.infiniteDistance;
  13718. this.setPivotMatrix(source.getPivotMatrix());
  13719. this.refreshBoundingInfo();
  13720. this._syncSubMeshes();
  13721. }
  13722. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13723. // Methods
  13724. get: function () {
  13725. return this._sourceMesh.receiveShadows;
  13726. },
  13727. enumerable: true,
  13728. configurable: true
  13729. });
  13730. Object.defineProperty(InstancedMesh.prototype, "material", {
  13731. get: function () {
  13732. return this._sourceMesh.material;
  13733. },
  13734. enumerable: true,
  13735. configurable: true
  13736. });
  13737. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13738. get: function () {
  13739. return this._sourceMesh.visibility;
  13740. },
  13741. enumerable: true,
  13742. configurable: true
  13743. });
  13744. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13745. get: function () {
  13746. return this._sourceMesh.skeleton;
  13747. },
  13748. enumerable: true,
  13749. configurable: true
  13750. });
  13751. InstancedMesh.prototype.getTotalVertices = function () {
  13752. return this._sourceMesh.getTotalVertices();
  13753. };
  13754. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13755. get: function () {
  13756. return this._sourceMesh;
  13757. },
  13758. enumerable: true,
  13759. configurable: true
  13760. });
  13761. InstancedMesh.prototype.getVerticesData = function (kind) {
  13762. return this._sourceMesh.getVerticesData(kind);
  13763. };
  13764. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13765. return this._sourceMesh.isVerticesDataPresent(kind);
  13766. };
  13767. InstancedMesh.prototype.getIndices = function () {
  13768. return this._sourceMesh.getIndices();
  13769. };
  13770. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13771. get: function () {
  13772. return this._sourceMesh._positions;
  13773. },
  13774. enumerable: true,
  13775. configurable: true
  13776. });
  13777. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13778. var meshBB = this._sourceMesh.getBoundingInfo();
  13779. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  13780. this._updateBoundingInfo();
  13781. };
  13782. InstancedMesh.prototype._preActivate = function () {
  13783. if (this._currentLOD) {
  13784. this._currentLOD._preActivate();
  13785. }
  13786. };
  13787. InstancedMesh.prototype._activate = function (renderId) {
  13788. if (this._currentLOD) {
  13789. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13790. }
  13791. };
  13792. InstancedMesh.prototype.getLOD = function (camera) {
  13793. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13794. if (this._currentLOD === this.sourceMesh) {
  13795. return this;
  13796. }
  13797. return this._currentLOD;
  13798. };
  13799. InstancedMesh.prototype._syncSubMeshes = function () {
  13800. this.releaseSubMeshes();
  13801. if (this._sourceMesh.subMeshes) {
  13802. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13803. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13804. }
  13805. }
  13806. };
  13807. InstancedMesh.prototype._generatePointsArray = function () {
  13808. return this._sourceMesh._generatePointsArray();
  13809. };
  13810. // Clone
  13811. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13812. var result = this._sourceMesh.createInstance(name);
  13813. // Deep copy
  13814. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13815. // Bounding info
  13816. this.refreshBoundingInfo();
  13817. // Parent
  13818. if (newParent) {
  13819. result.parent = newParent;
  13820. }
  13821. if (!doNotCloneChildren) {
  13822. // Children
  13823. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13824. var mesh = this.getScene().meshes[index];
  13825. if (mesh.parent === this) {
  13826. mesh.clone(mesh.name, result);
  13827. }
  13828. }
  13829. }
  13830. result.computeWorldMatrix(true);
  13831. return result;
  13832. };
  13833. // Dispoe
  13834. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13835. // Remove from mesh
  13836. var index = this._sourceMesh.instances.indexOf(this);
  13837. this._sourceMesh.instances.splice(index, 1);
  13838. _super.prototype.dispose.call(this, doNotRecurse);
  13839. };
  13840. return InstancedMesh;
  13841. })(BABYLON.AbstractMesh);
  13842. BABYLON.InstancedMesh = InstancedMesh;
  13843. })(BABYLON || (BABYLON = {}));
  13844. var BABYLON;
  13845. (function (BABYLON) {
  13846. var _InstancesBatch = (function () {
  13847. function _InstancesBatch() {
  13848. this.mustReturn = false;
  13849. this.visibleInstances = new Array();
  13850. this.renderSelf = new Array();
  13851. }
  13852. return _InstancesBatch;
  13853. })();
  13854. BABYLON._InstancesBatch = _InstancesBatch;
  13855. var Mesh = (function (_super) {
  13856. __extends(Mesh, _super);
  13857. /**
  13858. * @constructor
  13859. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13860. * @param {Scene} scene - The scene to add this mesh to.
  13861. * @param {Node} parent - The parent of this mesh, if it has one
  13862. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13863. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13864. * When false, achieved by calling a clone(), also passing False.
  13865. * This will make creation of children, recursive.
  13866. */
  13867. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13868. if (parent === void 0) { parent = null; }
  13869. _super.call(this, name, scene);
  13870. // Members
  13871. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13872. this.instances = new Array();
  13873. this._LODLevels = new Array();
  13874. this._onBeforeRenderCallbacks = new Array();
  13875. this._onAfterRenderCallbacks = new Array();
  13876. this._visibleInstances = {};
  13877. this._renderIdForInstances = new Array();
  13878. this._batchCache = new _InstancesBatch();
  13879. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13880. this._sideOrientation = Mesh._DEFAULTSIDE;
  13881. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13882. if (source) {
  13883. // Geometry
  13884. if (source._geometry) {
  13885. source._geometry.applyToMesh(this);
  13886. }
  13887. // Deep copy
  13888. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13889. this.id = name + "." + source.id;
  13890. // Material
  13891. this.material = source.material;
  13892. var index;
  13893. if (!doNotCloneChildren) {
  13894. // Children
  13895. for (index = 0; index < scene.meshes.length; index++) {
  13896. var mesh = scene.meshes[index];
  13897. if (mesh.parent === source) {
  13898. // doNotCloneChildren is always going to be False
  13899. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13900. }
  13901. }
  13902. }
  13903. // Particles
  13904. for (index = 0; index < scene.particleSystems.length; index++) {
  13905. var system = scene.particleSystems[index];
  13906. if (system.emitter === source) {
  13907. system.clone(system.name, this);
  13908. }
  13909. }
  13910. this.computeWorldMatrix(true);
  13911. }
  13912. // Parent
  13913. if (parent !== null) {
  13914. this.parent = parent;
  13915. }
  13916. }
  13917. Object.defineProperty(Mesh, "FRONTSIDE", {
  13918. get: function () {
  13919. return Mesh._FRONTSIDE;
  13920. },
  13921. enumerable: true,
  13922. configurable: true
  13923. });
  13924. Object.defineProperty(Mesh, "BACKSIDE", {
  13925. get: function () {
  13926. return Mesh._BACKSIDE;
  13927. },
  13928. enumerable: true,
  13929. configurable: true
  13930. });
  13931. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13932. get: function () {
  13933. return Mesh._DOUBLESIDE;
  13934. },
  13935. enumerable: true,
  13936. configurable: true
  13937. });
  13938. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13939. get: function () {
  13940. return Mesh._DEFAULTSIDE;
  13941. },
  13942. enumerable: true,
  13943. configurable: true
  13944. });
  13945. Object.defineProperty(Mesh, "NO_CAP", {
  13946. get: function () {
  13947. return Mesh._NO_CAP;
  13948. },
  13949. enumerable: true,
  13950. configurable: true
  13951. });
  13952. Object.defineProperty(Mesh, "CAP_START", {
  13953. get: function () {
  13954. return Mesh._CAP_START;
  13955. },
  13956. enumerable: true,
  13957. configurable: true
  13958. });
  13959. Object.defineProperty(Mesh, "CAP_END", {
  13960. get: function () {
  13961. return Mesh._CAP_END;
  13962. },
  13963. enumerable: true,
  13964. configurable: true
  13965. });
  13966. Object.defineProperty(Mesh, "CAP_ALL", {
  13967. get: function () {
  13968. return Mesh._CAP_ALL;
  13969. },
  13970. enumerable: true,
  13971. configurable: true
  13972. });
  13973. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13974. // Methods
  13975. get: function () {
  13976. return this._LODLevels.length > 0;
  13977. },
  13978. enumerable: true,
  13979. configurable: true
  13980. });
  13981. Mesh.prototype._sortLODLevels = function () {
  13982. this._LODLevels.sort(function (a, b) {
  13983. if (a.distance < b.distance) {
  13984. return 1;
  13985. }
  13986. if (a.distance > b.distance) {
  13987. return -1;
  13988. }
  13989. return 0;
  13990. });
  13991. };
  13992. /**
  13993. * Add a mesh as LOD level triggered at the given distance.
  13994. * @param {number} distance - the distance from the center of the object to show this level
  13995. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13996. * @return {BABYLON.Mesh} this mesh (for chaining)
  13997. */
  13998. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13999. if (mesh && mesh._masterMesh) {
  14000. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14001. return this;
  14002. }
  14003. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14004. this._LODLevels.push(level);
  14005. if (mesh) {
  14006. mesh._masterMesh = this;
  14007. }
  14008. this._sortLODLevels();
  14009. return this;
  14010. };
  14011. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14012. for (var index = 0; index < this._LODLevels.length; index++) {
  14013. var level = this._LODLevels[index];
  14014. if (level.distance === distance) {
  14015. return level.mesh;
  14016. }
  14017. }
  14018. return null;
  14019. };
  14020. /**
  14021. * Remove a mesh from the LOD array
  14022. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14023. * @return {BABYLON.Mesh} this mesh (for chaining)
  14024. */
  14025. Mesh.prototype.removeLODLevel = function (mesh) {
  14026. for (var index = 0; index < this._LODLevels.length; index++) {
  14027. if (this._LODLevels[index].mesh === mesh) {
  14028. this._LODLevels.splice(index, 1);
  14029. if (mesh) {
  14030. mesh._masterMesh = null;
  14031. }
  14032. }
  14033. }
  14034. this._sortLODLevels();
  14035. return this;
  14036. };
  14037. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14038. if (!this._LODLevels || this._LODLevels.length === 0) {
  14039. return this;
  14040. }
  14041. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14042. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14043. if (this.onLODLevelSelection) {
  14044. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14045. }
  14046. return this;
  14047. }
  14048. for (var index = 0; index < this._LODLevels.length; index++) {
  14049. var level = this._LODLevels[index];
  14050. if (level.distance < distanceToCamera) {
  14051. if (level.mesh) {
  14052. level.mesh._preActivate();
  14053. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14054. }
  14055. if (this.onLODLevelSelection) {
  14056. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14057. }
  14058. return level.mesh;
  14059. }
  14060. }
  14061. if (this.onLODLevelSelection) {
  14062. this.onLODLevelSelection(distanceToCamera, this, this);
  14063. }
  14064. return this;
  14065. };
  14066. Object.defineProperty(Mesh.prototype, "geometry", {
  14067. get: function () {
  14068. return this._geometry;
  14069. },
  14070. enumerable: true,
  14071. configurable: true
  14072. });
  14073. Mesh.prototype.getTotalVertices = function () {
  14074. if (!this._geometry) {
  14075. return 0;
  14076. }
  14077. return this._geometry.getTotalVertices();
  14078. };
  14079. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14080. if (!this._geometry) {
  14081. return null;
  14082. }
  14083. return this._geometry.getVerticesData(kind, copyWhenShared);
  14084. };
  14085. Mesh.prototype.getVertexBuffer = function (kind) {
  14086. if (!this._geometry) {
  14087. return undefined;
  14088. }
  14089. return this._geometry.getVertexBuffer(kind);
  14090. };
  14091. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14092. if (!this._geometry) {
  14093. if (this._delayInfo) {
  14094. return this._delayInfo.indexOf(kind) !== -1;
  14095. }
  14096. return false;
  14097. }
  14098. return this._geometry.isVerticesDataPresent(kind);
  14099. };
  14100. Mesh.prototype.getVerticesDataKinds = function () {
  14101. if (!this._geometry) {
  14102. var result = [];
  14103. if (this._delayInfo) {
  14104. for (var kind in this._delayInfo) {
  14105. result.push(kind);
  14106. }
  14107. }
  14108. return result;
  14109. }
  14110. return this._geometry.getVerticesDataKinds();
  14111. };
  14112. Mesh.prototype.getTotalIndices = function () {
  14113. if (!this._geometry) {
  14114. return 0;
  14115. }
  14116. return this._geometry.getTotalIndices();
  14117. };
  14118. Mesh.prototype.getIndices = function (copyWhenShared) {
  14119. if (!this._geometry) {
  14120. return [];
  14121. }
  14122. return this._geometry.getIndices(copyWhenShared);
  14123. };
  14124. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14125. get: function () {
  14126. return this._masterMesh !== null && this._masterMesh !== undefined;
  14127. },
  14128. enumerable: true,
  14129. configurable: true
  14130. });
  14131. Mesh.prototype.isReady = function () {
  14132. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14133. return false;
  14134. }
  14135. return _super.prototype.isReady.call(this);
  14136. };
  14137. Mesh.prototype.isDisposed = function () {
  14138. return this._isDisposed;
  14139. };
  14140. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14141. get: function () {
  14142. return this._sideOrientation;
  14143. },
  14144. set: function (sideO) {
  14145. this._sideOrientation = sideO;
  14146. },
  14147. enumerable: true,
  14148. configurable: true
  14149. });
  14150. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14151. get: function () {
  14152. return this._areNormalsFrozen;
  14153. },
  14154. enumerable: true,
  14155. configurable: true
  14156. });
  14157. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14158. Mesh.prototype.freezeNormals = function () {
  14159. this._areNormalsFrozen = true;
  14160. };
  14161. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14162. Mesh.prototype.unfreezeNormals = function () {
  14163. this._areNormalsFrozen = false;
  14164. };
  14165. // Methods
  14166. Mesh.prototype._preActivate = function () {
  14167. var sceneRenderId = this.getScene().getRenderId();
  14168. if (this._preActivateId === sceneRenderId) {
  14169. return;
  14170. }
  14171. this._preActivateId = sceneRenderId;
  14172. this._visibleInstances = null;
  14173. };
  14174. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14175. if (!this._visibleInstances) {
  14176. this._visibleInstances = {};
  14177. this._visibleInstances.defaultRenderId = renderId;
  14178. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14179. }
  14180. if (!this._visibleInstances[renderId]) {
  14181. this._visibleInstances[renderId] = new Array();
  14182. }
  14183. this._visibleInstances[renderId].push(instance);
  14184. };
  14185. Mesh.prototype.refreshBoundingInfo = function () {
  14186. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14187. if (data) {
  14188. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14189. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14190. }
  14191. if (this.subMeshes) {
  14192. for (var index = 0; index < this.subMeshes.length; index++) {
  14193. this.subMeshes[index].refreshBoundingInfo();
  14194. }
  14195. }
  14196. this._updateBoundingInfo();
  14197. };
  14198. Mesh.prototype._createGlobalSubMesh = function () {
  14199. var totalVertices = this.getTotalVertices();
  14200. if (!totalVertices || !this.getIndices()) {
  14201. return null;
  14202. }
  14203. this.releaseSubMeshes();
  14204. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14205. };
  14206. Mesh.prototype.subdivide = function (count) {
  14207. if (count < 1) {
  14208. return;
  14209. }
  14210. var totalIndices = this.getTotalIndices();
  14211. var subdivisionSize = (totalIndices / count) | 0;
  14212. var offset = 0;
  14213. // Ensure that subdivisionSize is a multiple of 3
  14214. while (subdivisionSize % 3 !== 0) {
  14215. subdivisionSize++;
  14216. }
  14217. this.releaseSubMeshes();
  14218. for (var index = 0; index < count; index++) {
  14219. if (offset >= totalIndices) {
  14220. break;
  14221. }
  14222. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14223. offset += subdivisionSize;
  14224. }
  14225. this.synchronizeInstances();
  14226. };
  14227. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14228. if (!this._geometry) {
  14229. var vertexData = new BABYLON.VertexData();
  14230. vertexData.set(data, kind);
  14231. var scene = this.getScene();
  14232. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14233. }
  14234. else {
  14235. this._geometry.setVerticesData(kind, data, updatable, stride);
  14236. }
  14237. };
  14238. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14239. if (!this._geometry) {
  14240. return;
  14241. }
  14242. if (!makeItUnique) {
  14243. this._geometry.updateVerticesData(kind, data, updateExtends);
  14244. }
  14245. else {
  14246. this.makeGeometryUnique();
  14247. this.updateVerticesData(kind, data, updateExtends, false);
  14248. }
  14249. };
  14250. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14251. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14252. if (!this._geometry) {
  14253. return;
  14254. }
  14255. if (!makeItUnique) {
  14256. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14257. }
  14258. else {
  14259. this.makeGeometryUnique();
  14260. this.updateVerticesDataDirectly(kind, data, offset, false);
  14261. }
  14262. };
  14263. // Mesh positions update function :
  14264. // updates the mesh positions according to the positionFunction returned values.
  14265. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14266. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14267. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14268. if (computeNormals === void 0) { computeNormals = true; }
  14269. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14270. positionFunction(positions);
  14271. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14272. if (computeNormals) {
  14273. var indices = this.getIndices();
  14274. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14275. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14276. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14277. }
  14278. };
  14279. Mesh.prototype.makeGeometryUnique = function () {
  14280. if (!this._geometry) {
  14281. return;
  14282. }
  14283. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14284. geometry.applyToMesh(this);
  14285. };
  14286. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14287. if (!this._geometry) {
  14288. var vertexData = new BABYLON.VertexData();
  14289. vertexData.indices = indices;
  14290. var scene = this.getScene();
  14291. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14292. }
  14293. else {
  14294. this._geometry.setIndices(indices, totalVertices);
  14295. }
  14296. };
  14297. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14298. var engine = this.getScene().getEngine();
  14299. // Wireframe
  14300. var indexToBind;
  14301. switch (fillMode) {
  14302. case BABYLON.Material.PointFillMode:
  14303. indexToBind = null;
  14304. break;
  14305. case BABYLON.Material.WireFrameFillMode:
  14306. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14307. break;
  14308. default:
  14309. case BABYLON.Material.TriangleFillMode:
  14310. indexToBind = this._geometry.getIndexBuffer();
  14311. break;
  14312. }
  14313. // VBOs
  14314. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14315. };
  14316. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14317. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14318. return;
  14319. }
  14320. var engine = this.getScene().getEngine();
  14321. // Draw order
  14322. switch (fillMode) {
  14323. case BABYLON.Material.PointFillMode:
  14324. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14325. break;
  14326. case BABYLON.Material.WireFrameFillMode:
  14327. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14328. break;
  14329. default:
  14330. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14331. }
  14332. };
  14333. Mesh.prototype.registerBeforeRender = function (func) {
  14334. this._onBeforeRenderCallbacks.push(func);
  14335. };
  14336. Mesh.prototype.unregisterBeforeRender = function (func) {
  14337. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14338. if (index > -1) {
  14339. this._onBeforeRenderCallbacks.splice(index, 1);
  14340. }
  14341. };
  14342. Mesh.prototype.registerAfterRender = function (func) {
  14343. this._onAfterRenderCallbacks.push(func);
  14344. };
  14345. Mesh.prototype.unregisterAfterRender = function (func) {
  14346. var index = this._onAfterRenderCallbacks.indexOf(func);
  14347. if (index > -1) {
  14348. this._onAfterRenderCallbacks.splice(index, 1);
  14349. }
  14350. };
  14351. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14352. var scene = this.getScene();
  14353. this._batchCache.mustReturn = false;
  14354. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14355. this._batchCache.visibleInstances[subMeshId] = null;
  14356. if (this._visibleInstances) {
  14357. var currentRenderId = scene.getRenderId();
  14358. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14359. var selfRenderId = this._renderId;
  14360. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14361. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14362. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14363. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14364. }
  14365. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14366. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14367. this._batchCache.mustReturn = true;
  14368. return this._batchCache;
  14369. }
  14370. if (currentRenderId !== selfRenderId) {
  14371. this._batchCache.renderSelf[subMeshId] = false;
  14372. }
  14373. }
  14374. this._renderIdForInstances[subMeshId] = currentRenderId;
  14375. }
  14376. return this._batchCache;
  14377. };
  14378. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14379. var visibleInstances = batch.visibleInstances[subMesh._id];
  14380. var matricesCount = visibleInstances.length + 1;
  14381. var bufferSize = matricesCount * 16 * 4;
  14382. while (this._instancesBufferSize < bufferSize) {
  14383. this._instancesBufferSize *= 2;
  14384. }
  14385. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14386. if (this._worldMatricesInstancesBuffer) {
  14387. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14388. }
  14389. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14390. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14391. }
  14392. var offset = 0;
  14393. var instancesCount = 0;
  14394. var world = this.getWorldMatrix();
  14395. if (batch.renderSelf[subMesh._id]) {
  14396. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14397. offset += 16;
  14398. instancesCount++;
  14399. }
  14400. if (visibleInstances) {
  14401. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14402. var instance = visibleInstances[instanceIndex];
  14403. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14404. offset += 16;
  14405. instancesCount++;
  14406. }
  14407. }
  14408. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14409. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14410. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14411. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14412. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14413. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14414. this._draw(subMesh, fillMode, instancesCount);
  14415. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14416. };
  14417. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14418. var scene = this.getScene();
  14419. var engine = scene.getEngine();
  14420. if (hardwareInstancedRendering) {
  14421. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14422. }
  14423. else {
  14424. if (batch.renderSelf[subMesh._id]) {
  14425. // Draw
  14426. if (onBeforeDraw) {
  14427. onBeforeDraw(false, this.getWorldMatrix());
  14428. }
  14429. this._draw(subMesh, fillMode);
  14430. }
  14431. if (batch.visibleInstances[subMesh._id]) {
  14432. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14433. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14434. // World
  14435. var world = instance.getWorldMatrix();
  14436. if (onBeforeDraw) {
  14437. onBeforeDraw(true, world);
  14438. }
  14439. // Draw
  14440. this._draw(subMesh, fillMode);
  14441. }
  14442. }
  14443. }
  14444. };
  14445. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14446. var scene = this.getScene();
  14447. // Managing instances
  14448. var batch = this._getInstancesRenderList(subMesh._id);
  14449. if (batch.mustReturn) {
  14450. return;
  14451. }
  14452. // Checking geometry state
  14453. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14454. return;
  14455. }
  14456. var callbackIndex;
  14457. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14458. this._onBeforeRenderCallbacks[callbackIndex](this);
  14459. }
  14460. var engine = scene.getEngine();
  14461. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14462. // Material
  14463. var effectiveMaterial = subMesh.getMaterial();
  14464. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14465. return;
  14466. }
  14467. // Outline - step 1
  14468. var savedDepthWrite = engine.getDepthWrite();
  14469. if (this.renderOutline) {
  14470. engine.setDepthWrite(false);
  14471. scene.getOutlineRenderer().render(subMesh, batch);
  14472. engine.setDepthWrite(savedDepthWrite);
  14473. }
  14474. effectiveMaterial._preBind();
  14475. var effect = effectiveMaterial.getEffect();
  14476. // Bind
  14477. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14478. this._bind(subMesh, effect, fillMode);
  14479. var world = this.getWorldMatrix();
  14480. effectiveMaterial.bind(world, this);
  14481. // Alpha mode
  14482. if (enableAlphaMode) {
  14483. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14484. }
  14485. // Draw
  14486. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14487. if (isInstance) {
  14488. effectiveMaterial.bindOnlyWorldMatrix(world);
  14489. }
  14490. });
  14491. // Unbind
  14492. effectiveMaterial.unbind();
  14493. // Outline - step 2
  14494. if (this.renderOutline && savedDepthWrite) {
  14495. engine.setDepthWrite(true);
  14496. engine.setColorWrite(false);
  14497. scene.getOutlineRenderer().render(subMesh, batch);
  14498. engine.setColorWrite(true);
  14499. }
  14500. // Overlay
  14501. if (this.renderOverlay) {
  14502. var currentMode = engine.getAlphaMode();
  14503. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14504. scene.getOutlineRenderer().render(subMesh, batch, true);
  14505. engine.setAlphaMode(currentMode);
  14506. }
  14507. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14508. this._onAfterRenderCallbacks[callbackIndex](this);
  14509. }
  14510. };
  14511. Mesh.prototype.getEmittedParticleSystems = function () {
  14512. var results = new Array();
  14513. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14514. var particleSystem = this.getScene().particleSystems[index];
  14515. if (particleSystem.emitter === this) {
  14516. results.push(particleSystem);
  14517. }
  14518. }
  14519. return results;
  14520. };
  14521. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14522. var results = new Array();
  14523. var descendants = this.getDescendants();
  14524. descendants.push(this);
  14525. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14526. var particleSystem = this.getScene().particleSystems[index];
  14527. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14528. results.push(particleSystem);
  14529. }
  14530. }
  14531. return results;
  14532. };
  14533. Mesh.prototype.getChildren = function () {
  14534. var results = [];
  14535. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14536. var mesh = this.getScene().meshes[index];
  14537. if (mesh.parent === this) {
  14538. results.push(mesh);
  14539. }
  14540. }
  14541. return results;
  14542. };
  14543. Mesh.prototype._checkDelayState = function () {
  14544. var _this = this;
  14545. var that = this;
  14546. var scene = this.getScene();
  14547. if (this._geometry) {
  14548. this._geometry.load(scene);
  14549. }
  14550. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14551. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14552. scene._addPendingData(that);
  14553. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14554. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14555. if (data instanceof ArrayBuffer) {
  14556. _this._delayLoadingFunction(data, _this);
  14557. }
  14558. else {
  14559. _this._delayLoadingFunction(JSON.parse(data), _this);
  14560. }
  14561. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14562. scene._removePendingData(_this);
  14563. }, function () { }, scene.database, getBinaryData);
  14564. }
  14565. };
  14566. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14567. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14568. return false;
  14569. }
  14570. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14571. return false;
  14572. }
  14573. this._checkDelayState();
  14574. return true;
  14575. };
  14576. Mesh.prototype.setMaterialByID = function (id) {
  14577. var materials = this.getScene().materials;
  14578. var index;
  14579. for (index = 0; index < materials.length; index++) {
  14580. if (materials[index].id === id) {
  14581. this.material = materials[index];
  14582. return;
  14583. }
  14584. }
  14585. // Multi
  14586. var multiMaterials = this.getScene().multiMaterials;
  14587. for (index = 0; index < multiMaterials.length; index++) {
  14588. if (multiMaterials[index].id === id) {
  14589. this.material = multiMaterials[index];
  14590. return;
  14591. }
  14592. }
  14593. };
  14594. Mesh.prototype.getAnimatables = function () {
  14595. var results = [];
  14596. if (this.material) {
  14597. results.push(this.material);
  14598. }
  14599. if (this.skeleton) {
  14600. results.push(this.skeleton);
  14601. }
  14602. return results;
  14603. };
  14604. // Geometry
  14605. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14606. // Position
  14607. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14608. return;
  14609. }
  14610. this._resetPointsArrayCache();
  14611. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14612. var temp = [];
  14613. var index;
  14614. for (index = 0; index < data.length; index += 3) {
  14615. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14616. }
  14617. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14618. // Normals
  14619. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14620. return;
  14621. }
  14622. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14623. temp = [];
  14624. for (index = 0; index < data.length; index += 3) {
  14625. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14626. }
  14627. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14628. // flip faces?
  14629. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14630. this.flipFaces();
  14631. }
  14632. };
  14633. // Will apply current transform to mesh and reset world matrix
  14634. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14635. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14636. this.scaling.copyFromFloats(1, 1, 1);
  14637. this.position.copyFromFloats(0, 0, 0);
  14638. this.rotation.copyFromFloats(0, 0, 0);
  14639. //only if quaternion is already set
  14640. if (this.rotationQuaternion) {
  14641. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  14642. }
  14643. this._worldMatrix = BABYLON.Matrix.Identity();
  14644. };
  14645. // Cache
  14646. Mesh.prototype._resetPointsArrayCache = function () {
  14647. this._positions = null;
  14648. };
  14649. Mesh.prototype._generatePointsArray = function () {
  14650. if (this._positions)
  14651. return true;
  14652. this._positions = [];
  14653. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14654. if (!data) {
  14655. return false;
  14656. }
  14657. for (var index = 0; index < data.length; index += 3) {
  14658. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14659. }
  14660. return true;
  14661. };
  14662. // Clone
  14663. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14664. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14665. };
  14666. // Dispose
  14667. Mesh.prototype.dispose = function (doNotRecurse) {
  14668. if (this._geometry) {
  14669. this._geometry.releaseForMesh(this, true);
  14670. }
  14671. // Instances
  14672. if (this._worldMatricesInstancesBuffer) {
  14673. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14674. this._worldMatricesInstancesBuffer = null;
  14675. }
  14676. while (this.instances.length) {
  14677. this.instances[0].dispose();
  14678. }
  14679. _super.prototype.dispose.call(this, doNotRecurse);
  14680. };
  14681. // Geometric tools
  14682. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14683. var _this = this;
  14684. var scene = this.getScene();
  14685. var onload = function (img) {
  14686. // Getting height map data
  14687. var canvas = document.createElement("canvas");
  14688. var context = canvas.getContext("2d");
  14689. var heightMapWidth = img.width;
  14690. var heightMapHeight = img.height;
  14691. canvas.width = heightMapWidth;
  14692. canvas.height = heightMapHeight;
  14693. context.drawImage(img, 0, 0);
  14694. // Create VertexData from map data
  14695. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14696. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14697. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14698. //execute success callback, if set
  14699. if (onSuccess) {
  14700. onSuccess(_this);
  14701. }
  14702. };
  14703. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14704. };
  14705. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14706. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14707. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14708. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14709. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14710. return;
  14711. }
  14712. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14713. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14714. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14715. var position = BABYLON.Vector3.Zero();
  14716. var normal = BABYLON.Vector3.Zero();
  14717. var uv = BABYLON.Vector2.Zero();
  14718. for (var index = 0; index < positions.length; index += 3) {
  14719. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14720. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14721. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14722. // Compute height
  14723. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14724. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14725. var pos = (u + v * heightMapWidth) * 4;
  14726. var r = buffer[pos] / 255.0;
  14727. var g = buffer[pos + 1] / 255.0;
  14728. var b = buffer[pos + 2] / 255.0;
  14729. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14730. normal.normalize();
  14731. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14732. position = position.add(normal);
  14733. position.toArray(positions, index);
  14734. }
  14735. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14736. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14737. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14738. };
  14739. Mesh.prototype.convertToFlatShadedMesh = function () {
  14740. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14741. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14742. var kinds = this.getVerticesDataKinds();
  14743. var vbs = [];
  14744. var data = [];
  14745. var newdata = [];
  14746. var updatableNormals = false;
  14747. var kindIndex;
  14748. var kind;
  14749. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14750. kind = kinds[kindIndex];
  14751. var vertexBuffer = this.getVertexBuffer(kind);
  14752. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14753. updatableNormals = vertexBuffer.isUpdatable();
  14754. kinds.splice(kindIndex, 1);
  14755. kindIndex--;
  14756. continue;
  14757. }
  14758. vbs[kind] = vertexBuffer;
  14759. data[kind] = vbs[kind].getData();
  14760. newdata[kind] = [];
  14761. }
  14762. // Save previous submeshes
  14763. var previousSubmeshes = this.subMeshes.slice(0);
  14764. var indices = this.getIndices();
  14765. var totalIndices = this.getTotalIndices();
  14766. // Generating unique vertices per face
  14767. var index;
  14768. for (index = 0; index < totalIndices; index++) {
  14769. var vertexIndex = indices[index];
  14770. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14771. kind = kinds[kindIndex];
  14772. var stride = vbs[kind].getStrideSize();
  14773. for (var offset = 0; offset < stride; offset++) {
  14774. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14775. }
  14776. }
  14777. }
  14778. // Updating faces & normal
  14779. var normals = [];
  14780. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14781. for (index = 0; index < totalIndices; index += 3) {
  14782. indices[index] = index;
  14783. indices[index + 1] = index + 1;
  14784. indices[index + 2] = index + 2;
  14785. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14786. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14787. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14788. var p1p2 = p1.subtract(p2);
  14789. var p3p2 = p3.subtract(p2);
  14790. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14791. // Store same normals for every vertex
  14792. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14793. normals.push(normal.x);
  14794. normals.push(normal.y);
  14795. normals.push(normal.z);
  14796. }
  14797. }
  14798. this.setIndices(indices);
  14799. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14800. // Updating vertex buffers
  14801. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14802. kind = kinds[kindIndex];
  14803. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14804. }
  14805. // Updating submeshes
  14806. this.releaseSubMeshes();
  14807. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14808. var previousOne = previousSubmeshes[submeshIndex];
  14809. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14810. }
  14811. this.synchronizeInstances();
  14812. };
  14813. // will inverse faces orientations, and invert normals too if specified
  14814. Mesh.prototype.flipFaces = function (flipNormals) {
  14815. if (flipNormals === void 0) { flipNormals = false; }
  14816. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  14817. var i;
  14818. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14819. for (i = 0; i < vertex_data.normals.length; i++) {
  14820. vertex_data.normals[i] *= -1;
  14821. }
  14822. }
  14823. var temp;
  14824. for (i = 0; i < vertex_data.indices.length; i += 3) {
  14825. // reassign indices
  14826. temp = vertex_data.indices[i + 1];
  14827. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  14828. vertex_data.indices[i + 2] = temp;
  14829. }
  14830. vertex_data.applyToMesh(this);
  14831. };
  14832. // Instances
  14833. Mesh.prototype.createInstance = function (name) {
  14834. return new BABYLON.InstancedMesh(name, this);
  14835. };
  14836. Mesh.prototype.synchronizeInstances = function () {
  14837. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14838. var instance = this.instances[instanceIndex];
  14839. instance._syncSubMeshes();
  14840. }
  14841. };
  14842. /**
  14843. * Simplify the mesh according to the given array of settings.
  14844. * Function will return immediately and will simplify async.
  14845. * @param settings a collection of simplification settings.
  14846. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14847. * @param type the type of simplification to run.
  14848. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14849. */
  14850. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14851. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14852. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14853. this.getScene().simplificationQueue.addTask({
  14854. settings: settings,
  14855. parallelProcessing: parallelProcessing,
  14856. mesh: this,
  14857. simplificationType: simplificationType,
  14858. successCallback: successCallback
  14859. });
  14860. };
  14861. /**
  14862. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14863. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14864. * This should be used together with the simplification to avoid disappearing triangles.
  14865. * @param successCallback an optional success callback to be called after the optimization finished.
  14866. */
  14867. Mesh.prototype.optimizeIndices = function (successCallback) {
  14868. var _this = this;
  14869. var indices = this.getIndices();
  14870. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14871. var vectorPositions = [];
  14872. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14873. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14874. }
  14875. var dupes = [];
  14876. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14877. var realPos = vectorPositions.length - 1 - iteration;
  14878. var testedPosition = vectorPositions[realPos];
  14879. for (var j = 0; j < realPos; ++j) {
  14880. var againstPosition = vectorPositions[j];
  14881. if (testedPosition.equals(againstPosition)) {
  14882. dupes[realPos] = j;
  14883. break;
  14884. }
  14885. }
  14886. }, function () {
  14887. for (var i = 0; i < indices.length; ++i) {
  14888. indices[i] = dupes[indices[i]] || indices[i];
  14889. }
  14890. //indices are now reordered
  14891. var originalSubMeshes = _this.subMeshes.slice(0);
  14892. _this.setIndices(indices);
  14893. _this.subMeshes = originalSubMeshes;
  14894. if (successCallback) {
  14895. successCallback(_this);
  14896. }
  14897. });
  14898. };
  14899. // Statics
  14900. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  14901. return BABYLON.MeshBuilder.CreateRibbon(name, {
  14902. pathArray: pathArray,
  14903. closeArray: closeArray,
  14904. closePath: closePath,
  14905. offset: offset,
  14906. updatable: updatable,
  14907. sideOrientation: sideOrientation,
  14908. instance: instance
  14909. }, scene);
  14910. };
  14911. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14912. var options = {
  14913. radius: radius,
  14914. tessellation: tessellation,
  14915. sideOrientation: sideOrientation,
  14916. updatable: updatable
  14917. };
  14918. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  14919. };
  14920. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14921. var options = {
  14922. size: size,
  14923. sideOrientation: sideOrientation,
  14924. updatable: updatable
  14925. };
  14926. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  14927. };
  14928. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14929. var options = {
  14930. segments: segments,
  14931. diameterX: diameter,
  14932. diameterY: diameter,
  14933. diameterZ: diameter,
  14934. sideOrientation: sideOrientation,
  14935. updatable: updatable
  14936. };
  14937. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  14938. };
  14939. // Cylinder and cone
  14940. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14941. var options = {
  14942. height: height,
  14943. diameterTop: diameterTop,
  14944. diameterBottom: diameterBottom,
  14945. tessellation: tessellation,
  14946. subdivisions: subdivisions,
  14947. sideOrientation: sideOrientation,
  14948. updatable: updatable
  14949. };
  14950. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  14951. };
  14952. // Torus (Code from SharpDX.org)
  14953. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14954. var options = {
  14955. diameter: diameter,
  14956. thickness: thickness,
  14957. tessellation: tessellation,
  14958. sideOrientation: sideOrientation,
  14959. updatable: updatable
  14960. };
  14961. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  14962. };
  14963. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14964. var options = {
  14965. radius: radius,
  14966. tube: tube,
  14967. radialSegments: radialSegments,
  14968. tubularSegments: tubularSegments,
  14969. p: p,
  14970. q: q,
  14971. sideOrientation: sideOrientation,
  14972. updatable: updatable
  14973. };
  14974. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  14975. };
  14976. // Lines
  14977. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  14978. var options = {
  14979. points: points,
  14980. updatable: updatable,
  14981. instance: instance
  14982. };
  14983. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  14984. };
  14985. // Dashed Lines
  14986. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  14987. var options = {
  14988. points: points,
  14989. dashSize: dashSize,
  14990. gapSize: gapSize,
  14991. dashNb: dashNb,
  14992. updatable: updatable
  14993. };
  14994. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  14995. };
  14996. // Extrusion
  14997. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  14998. var options = {
  14999. shape: shape,
  15000. path: path,
  15001. scale: scale,
  15002. rotation: rotation,
  15003. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15004. sideOrientation: sideOrientation,
  15005. instance: instance,
  15006. updatable: updatable
  15007. };
  15008. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15009. };
  15010. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15011. var options = {
  15012. shape: shape,
  15013. path: path,
  15014. scaleFunction: scaleFunction,
  15015. rotationFunction: rotationFunction,
  15016. ribbonCloseArray: ribbonCloseArray,
  15017. ribbonClosePath: ribbonClosePath,
  15018. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15019. sideOrientation: sideOrientation,
  15020. instance: instance,
  15021. updatable: updatable
  15022. };
  15023. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15024. };
  15025. // Lathe
  15026. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15027. var options = {
  15028. shape: shape,
  15029. radius: radius,
  15030. tessellation: tessellation,
  15031. sideOrientation: sideOrientation,
  15032. updatable: updatable
  15033. };
  15034. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15035. };
  15036. // Plane & ground
  15037. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15038. var options = {
  15039. size: size,
  15040. width: size,
  15041. height: size,
  15042. sideOrientation: sideOrientation,
  15043. updatable: updatable
  15044. };
  15045. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15046. };
  15047. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15048. var options = {
  15049. width: width,
  15050. height: height,
  15051. subdivisions: subdivisions,
  15052. updatable: updatable
  15053. };
  15054. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15055. };
  15056. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15057. var options = {
  15058. xmin: xmin,
  15059. zmin: zmin,
  15060. xmax: xmax,
  15061. zmax: zmax,
  15062. subdivisions: subdivisions,
  15063. precision: precision,
  15064. updatable: updatable
  15065. };
  15066. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15067. };
  15068. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15069. var options = {
  15070. width: width,
  15071. height: height,
  15072. subdivisions: subdivisions,
  15073. minHeight: minHeight,
  15074. maxHeight: maxHeight,
  15075. updatable: updatable,
  15076. onReady: onReady
  15077. };
  15078. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15079. };
  15080. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15081. var options = {
  15082. path: path,
  15083. radius: radius,
  15084. tessellation: tessellation,
  15085. radiusFunction: radiusFunction,
  15086. arc: 1,
  15087. cap: cap,
  15088. updatable: updatable,
  15089. sideOrientation: sideOrientation,
  15090. instance: instance
  15091. };
  15092. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15093. };
  15094. Mesh.CreatePolyhedron = function (name, options, scene) {
  15095. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15096. };
  15097. Mesh.CreateIcoSphere = function (name, options, scene) {
  15098. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15099. };
  15100. // Decals
  15101. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15102. var options = {
  15103. position: position,
  15104. normal: normal,
  15105. size: size,
  15106. angle: angle
  15107. };
  15108. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15109. };
  15110. // Skeletons
  15111. /**
  15112. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15113. */
  15114. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15115. var source;
  15116. if (!this._sourcePositions) {
  15117. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15118. this._sourcePositions = new Float32Array(source);
  15119. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15120. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15121. }
  15122. }
  15123. return this._sourcePositions;
  15124. };
  15125. /**
  15126. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15127. */
  15128. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15129. var source;
  15130. if (!this._sourceNormals) {
  15131. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15132. this._sourceNormals = new Float32Array(source);
  15133. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15134. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15135. }
  15136. }
  15137. return this._sourceNormals;
  15138. };
  15139. /**
  15140. * Update the vertex buffers by applying transformation from the bones
  15141. * @param {skeleton} skeleton to apply
  15142. */
  15143. Mesh.prototype.applySkeleton = function (skeleton) {
  15144. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15145. return this;
  15146. }
  15147. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15148. return this;
  15149. }
  15150. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15151. return this;
  15152. }
  15153. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15154. return this;
  15155. }
  15156. if (!this._sourcePositions) {
  15157. this.setPositionsForCPUSkinning();
  15158. }
  15159. if (!this._sourceNormals) {
  15160. this.setNormalsForCPUSkinning();
  15161. }
  15162. // positionsData checks for not being Float32Array will only pass at most once
  15163. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15164. if (!(positionsData instanceof Float32Array)) {
  15165. positionsData = new Float32Array(positionsData);
  15166. }
  15167. // normalsData checks for not being Float32Array will only pass at most once
  15168. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15169. if (!(normalsData instanceof Float32Array)) {
  15170. normalsData = new Float32Array(normalsData);
  15171. }
  15172. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15173. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15174. var needExtras = this.numBoneInfluencers > 4;
  15175. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15176. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15177. var skeletonMatrices = skeleton.getTransformMatrices();
  15178. var tempVector3 = BABYLON.Vector3.Zero();
  15179. var finalMatrix = new BABYLON.Matrix();
  15180. var tempMatrix = new BABYLON.Matrix();
  15181. var matWeightIdx = 0;
  15182. var inf;
  15183. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15184. var weight;
  15185. for (inf = 0; inf < 4; inf++) {
  15186. weight = matricesWeightsData[matWeightIdx + inf];
  15187. if (weight > 0) {
  15188. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15189. finalMatrix.addToSelf(tempMatrix);
  15190. }
  15191. else
  15192. break;
  15193. }
  15194. if (needExtras) {
  15195. for (inf = 0; inf < 4; inf++) {
  15196. weight = matricesWeightsExtraData[matWeightIdx + inf];
  15197. if (weight > 0) {
  15198. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15199. finalMatrix.addToSelf(tempMatrix);
  15200. }
  15201. else
  15202. break;
  15203. }
  15204. }
  15205. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15206. tempVector3.toArray(positionsData, index);
  15207. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15208. tempVector3.toArray(normalsData, index);
  15209. finalMatrix.reset();
  15210. }
  15211. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15212. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15213. return this;
  15214. };
  15215. // Tools
  15216. Mesh.MinMax = function (meshes) {
  15217. var minVector = null;
  15218. var maxVector = null;
  15219. for (var i in meshes) {
  15220. var mesh = meshes[i];
  15221. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15222. if (!minVector) {
  15223. minVector = boundingBox.minimumWorld;
  15224. maxVector = boundingBox.maximumWorld;
  15225. continue;
  15226. }
  15227. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15228. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15229. }
  15230. return {
  15231. min: minVector,
  15232. max: maxVector
  15233. };
  15234. };
  15235. Mesh.Center = function (meshesOrMinMaxVector) {
  15236. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15237. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15238. };
  15239. /**
  15240. * Merge the array of meshes into a single mesh for performance reasons.
  15241. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15242. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15243. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15244. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15245. */
  15246. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15247. if (disposeSource === void 0) { disposeSource = true; }
  15248. var index;
  15249. if (!allow32BitsIndices) {
  15250. var totalVertices = 0;
  15251. // Counting vertices
  15252. for (index = 0; index < meshes.length; index++) {
  15253. if (meshes[index]) {
  15254. totalVertices += meshes[index].getTotalVertices();
  15255. if (totalVertices > 65536) {
  15256. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15257. return null;
  15258. }
  15259. }
  15260. }
  15261. }
  15262. // Merge
  15263. var vertexData;
  15264. var otherVertexData;
  15265. var source;
  15266. for (index = 0; index < meshes.length; index++) {
  15267. if (meshes[index]) {
  15268. meshes[index].computeWorldMatrix(true);
  15269. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15270. otherVertexData.transform(meshes[index].getWorldMatrix());
  15271. if (vertexData) {
  15272. vertexData.merge(otherVertexData);
  15273. }
  15274. else {
  15275. vertexData = otherVertexData;
  15276. source = meshes[index];
  15277. }
  15278. }
  15279. }
  15280. if (!meshSubclass) {
  15281. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15282. }
  15283. vertexData.applyToMesh(meshSubclass);
  15284. // Setting properties
  15285. meshSubclass.material = source.material;
  15286. meshSubclass.checkCollisions = source.checkCollisions;
  15287. // Cleaning
  15288. if (disposeSource) {
  15289. for (index = 0; index < meshes.length; index++) {
  15290. if (meshes[index]) {
  15291. meshes[index].dispose();
  15292. }
  15293. }
  15294. }
  15295. return meshSubclass;
  15296. };
  15297. // Consts
  15298. Mesh._FRONTSIDE = 0;
  15299. Mesh._BACKSIDE = 1;
  15300. Mesh._DOUBLESIDE = 2;
  15301. Mesh._DEFAULTSIDE = 0;
  15302. Mesh._NO_CAP = 0;
  15303. Mesh._CAP_START = 1;
  15304. Mesh._CAP_END = 2;
  15305. Mesh._CAP_ALL = 3;
  15306. return Mesh;
  15307. })(BABYLON.AbstractMesh);
  15308. BABYLON.Mesh = Mesh;
  15309. })(BABYLON || (BABYLON = {}));
  15310. var BABYLON;
  15311. (function (BABYLON) {
  15312. var SubMesh = (function () {
  15313. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15314. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15315. this.materialIndex = materialIndex;
  15316. this.verticesStart = verticesStart;
  15317. this.verticesCount = verticesCount;
  15318. this.indexStart = indexStart;
  15319. this.indexCount = indexCount;
  15320. this._renderId = 0;
  15321. this._mesh = mesh;
  15322. this._renderingMesh = renderingMesh || mesh;
  15323. mesh.subMeshes.push(this);
  15324. this._trianglePlanes = [];
  15325. this._id = mesh.subMeshes.length - 1;
  15326. if (createBoundingBox) {
  15327. this.refreshBoundingInfo();
  15328. mesh.computeWorldMatrix(true);
  15329. }
  15330. }
  15331. SubMesh.prototype.getBoundingInfo = function () {
  15332. return this._boundingInfo;
  15333. };
  15334. SubMesh.prototype.getMesh = function () {
  15335. return this._mesh;
  15336. };
  15337. SubMesh.prototype.getRenderingMesh = function () {
  15338. return this._renderingMesh;
  15339. };
  15340. SubMesh.prototype.getMaterial = function () {
  15341. var rootMaterial = this._renderingMesh.material;
  15342. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15343. var multiMaterial = rootMaterial;
  15344. return multiMaterial.getSubMaterial(this.materialIndex);
  15345. }
  15346. if (!rootMaterial) {
  15347. return this._mesh.getScene().defaultMaterial;
  15348. }
  15349. return rootMaterial;
  15350. };
  15351. // Methods
  15352. SubMesh.prototype.refreshBoundingInfo = function () {
  15353. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15354. if (!data) {
  15355. this._boundingInfo = this._mesh._boundingInfo;
  15356. return;
  15357. }
  15358. var indices = this._renderingMesh.getIndices();
  15359. var extend;
  15360. //is this the only submesh?
  15361. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15362. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15363. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15364. }
  15365. else {
  15366. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15367. }
  15368. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15369. };
  15370. SubMesh.prototype._checkCollision = function (collider) {
  15371. return this._boundingInfo._checkCollision(collider);
  15372. };
  15373. SubMesh.prototype.updateBoundingInfo = function (world) {
  15374. if (!this._boundingInfo) {
  15375. this.refreshBoundingInfo();
  15376. }
  15377. this._boundingInfo._update(world);
  15378. };
  15379. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15380. return this._boundingInfo.isInFrustum(frustumPlanes);
  15381. };
  15382. SubMesh.prototype.render = function (enableAlphaMode) {
  15383. this._renderingMesh.render(this, enableAlphaMode);
  15384. };
  15385. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15386. if (!this._linesIndexBuffer) {
  15387. var linesIndices = [];
  15388. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15389. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15390. }
  15391. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15392. this.linesIndexCount = linesIndices.length;
  15393. }
  15394. return this._linesIndexBuffer;
  15395. };
  15396. SubMesh.prototype.canIntersects = function (ray) {
  15397. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15398. };
  15399. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15400. var intersectInfo = null;
  15401. // Triangles test
  15402. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15403. var p0 = positions[indices[index]];
  15404. var p1 = positions[indices[index + 1]];
  15405. var p2 = positions[indices[index + 2]];
  15406. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15407. if (currentIntersectInfo) {
  15408. if (currentIntersectInfo.distance < 0) {
  15409. continue;
  15410. }
  15411. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15412. intersectInfo = currentIntersectInfo;
  15413. intersectInfo.faceId = index / 3;
  15414. if (fastCheck) {
  15415. break;
  15416. }
  15417. }
  15418. }
  15419. }
  15420. return intersectInfo;
  15421. };
  15422. // Clone
  15423. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15424. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15425. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15426. return result;
  15427. };
  15428. // Dispose
  15429. SubMesh.prototype.dispose = function () {
  15430. if (this._linesIndexBuffer) {
  15431. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15432. this._linesIndexBuffer = null;
  15433. }
  15434. // Remove from mesh
  15435. var index = this._mesh.subMeshes.indexOf(this);
  15436. this._mesh.subMeshes.splice(index, 1);
  15437. };
  15438. // Statics
  15439. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15440. var minVertexIndex = Number.MAX_VALUE;
  15441. var maxVertexIndex = -Number.MAX_VALUE;
  15442. renderingMesh = renderingMesh || mesh;
  15443. var indices = renderingMesh.getIndices();
  15444. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15445. var vertexIndex = indices[index];
  15446. if (vertexIndex < minVertexIndex)
  15447. minVertexIndex = vertexIndex;
  15448. if (vertexIndex > maxVertexIndex)
  15449. maxVertexIndex = vertexIndex;
  15450. }
  15451. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15452. };
  15453. return SubMesh;
  15454. })();
  15455. BABYLON.SubMesh = SubMesh;
  15456. })(BABYLON || (BABYLON = {}));
  15457. var BABYLON;
  15458. (function (BABYLON) {
  15459. var MeshBuilder = (function () {
  15460. function MeshBuilder() {
  15461. }
  15462. MeshBuilder.CreateBox = function (name, options, scene) {
  15463. var box = new BABYLON.Mesh(name, scene);
  15464. var vertexData = BABYLON.VertexData.CreateBox(options);
  15465. vertexData.applyToMesh(box, options.updatable);
  15466. return box;
  15467. };
  15468. MeshBuilder.CreateSphere = function (name, options, scene) {
  15469. var sphere = new BABYLON.Mesh(name, scene);
  15470. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15471. vertexData.applyToMesh(sphere, options.updatable);
  15472. return sphere;
  15473. };
  15474. MeshBuilder.CreateDisc = function (name, options, scene) {
  15475. var disc = new BABYLON.Mesh(name, scene);
  15476. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15477. vertexData.applyToMesh(disc, options.updatable);
  15478. return disc;
  15479. };
  15480. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  15481. var sphere = new BABYLON.Mesh(name, scene);
  15482. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  15483. vertexData.applyToMesh(sphere, options.updatable);
  15484. return sphere;
  15485. };
  15486. ;
  15487. MeshBuilder.CreateRibbon = function (name, options, scene) {
  15488. var pathArray = options.pathArray;
  15489. var closeArray = options.closeArray;
  15490. var closePath = options.closePath;
  15491. var offset = options.offset;
  15492. var sideOrientation = options.sideOrientation;
  15493. var instance = options.instance;
  15494. var updatable = options.updatable;
  15495. if (instance) {
  15496. // positionFunction : ribbon case
  15497. // only pathArray and sideOrientation parameters are taken into account for positions update
  15498. var positionFunction = function (positions) {
  15499. var minlg = pathArray[0].length;
  15500. var i = 0;
  15501. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15502. for (var si = 1; si <= ns; si++) {
  15503. for (var p = 0; p < pathArray.length; p++) {
  15504. var path = pathArray[p];
  15505. var l = path.length;
  15506. minlg = (minlg < l) ? minlg : l;
  15507. var j = 0;
  15508. while (j < minlg) {
  15509. positions[i] = path[j].x;
  15510. positions[i + 1] = path[j].y;
  15511. positions[i + 2] = path[j].z;
  15512. j++;
  15513. i += 3;
  15514. }
  15515. if (instance._closePath) {
  15516. positions[i] = path[0].x;
  15517. positions[i + 1] = path[0].y;
  15518. positions[i + 2] = path[0].z;
  15519. i += 3;
  15520. }
  15521. }
  15522. }
  15523. };
  15524. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15525. positionFunction(positions);
  15526. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15527. if (!(instance.areNormalsFrozen)) {
  15528. var indices = instance.getIndices();
  15529. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15530. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15531. if (instance._closePath) {
  15532. var indexFirst = 0;
  15533. var indexLast = 0;
  15534. for (var p = 0; p < pathArray.length; p++) {
  15535. indexFirst = instance._idx[p] * 3;
  15536. if (p + 1 < pathArray.length) {
  15537. indexLast = (instance._idx[p + 1] - 1) * 3;
  15538. }
  15539. else {
  15540. indexLast = normals.length - 3;
  15541. }
  15542. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15543. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15544. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15545. normals[indexLast] = normals[indexFirst];
  15546. normals[indexLast + 1] = normals[indexFirst + 1];
  15547. normals[indexLast + 2] = normals[indexFirst + 2];
  15548. }
  15549. }
  15550. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15551. }
  15552. return instance;
  15553. }
  15554. else {
  15555. var ribbon = new BABYLON.Mesh(name, scene);
  15556. ribbon.sideOrientation = sideOrientation;
  15557. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15558. if (closePath) {
  15559. ribbon._idx = vertexData._idx;
  15560. }
  15561. ribbon._closePath = closePath;
  15562. ribbon._closeArray = closeArray;
  15563. vertexData.applyToMesh(ribbon, updatable);
  15564. return ribbon;
  15565. }
  15566. };
  15567. MeshBuilder.CreateCylinder = function (name, options, scene) {
  15568. var cylinder = new BABYLON.Mesh(name, scene);
  15569. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15570. vertexData.applyToMesh(cylinder, options.updatable);
  15571. return cylinder;
  15572. };
  15573. MeshBuilder.CreateTorus = function (name, options, scene) {
  15574. var torus = new BABYLON.Mesh(name, scene);
  15575. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15576. vertexData.applyToMesh(torus, options.updatable);
  15577. return torus;
  15578. };
  15579. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  15580. var torusKnot = new BABYLON.Mesh(name, scene);
  15581. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15582. vertexData.applyToMesh(torusKnot, options.updatable);
  15583. return torusKnot;
  15584. };
  15585. MeshBuilder.CreateLines = function (name, options, scene) {
  15586. var instance = options.instance;
  15587. var points = options.points;
  15588. if (instance) {
  15589. var positionFunction = function (positions) {
  15590. var i = 0;
  15591. for (var p = 0; p < points.length; p++) {
  15592. positions[i] = points[p].x;
  15593. positions[i + 1] = points[p].y;
  15594. positions[i + 2] = points[p].z;
  15595. i += 3;
  15596. }
  15597. };
  15598. instance.updateMeshPositions(positionFunction, false);
  15599. return instance;
  15600. }
  15601. // lines creation
  15602. var lines = new BABYLON.LinesMesh(name, scene);
  15603. var vertexData = BABYLON.VertexData.CreateLines(options);
  15604. vertexData.applyToMesh(lines, options.updatable);
  15605. return lines;
  15606. };
  15607. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  15608. var points = options.points;
  15609. var instance = options.instance;
  15610. var gapSize = options.gapSize;
  15611. var dashNb = options.dashNb;
  15612. var dashSize = options.dashSize;
  15613. if (instance) {
  15614. var positionFunction = function (positions) {
  15615. var curvect = BABYLON.Vector3.Zero();
  15616. var nbSeg = positions.length / 6;
  15617. var lg = 0;
  15618. var nb = 0;
  15619. var shft = 0;
  15620. var dashshft = 0;
  15621. var curshft = 0;
  15622. var p = 0;
  15623. var i = 0;
  15624. var j = 0;
  15625. for (i = 0; i < points.length - 1; i++) {
  15626. points[i + 1].subtractToRef(points[i], curvect);
  15627. lg += curvect.length();
  15628. }
  15629. shft = lg / nbSeg;
  15630. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15631. for (i = 0; i < points.length - 1; i++) {
  15632. points[i + 1].subtractToRef(points[i], curvect);
  15633. nb = Math.floor(curvect.length() / shft);
  15634. curvect.normalize();
  15635. j = 0;
  15636. while (j < nb && p < positions.length) {
  15637. curshft = shft * j;
  15638. positions[p] = points[i].x + curshft * curvect.x;
  15639. positions[p + 1] = points[i].y + curshft * curvect.y;
  15640. positions[p + 2] = points[i].z + curshft * curvect.z;
  15641. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15642. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15643. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15644. p += 6;
  15645. j++;
  15646. }
  15647. }
  15648. while (p < positions.length) {
  15649. positions[p] = points[i].x;
  15650. positions[p + 1] = points[i].y;
  15651. positions[p + 2] = points[i].z;
  15652. p += 3;
  15653. }
  15654. };
  15655. instance.updateMeshPositions(positionFunction, false);
  15656. return instance;
  15657. }
  15658. // dashed lines creation
  15659. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15660. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15661. vertexData.applyToMesh(dashedLines, options.updatable);
  15662. dashedLines.dashSize = dashSize;
  15663. dashedLines.gapSize = gapSize;
  15664. return dashedLines;
  15665. };
  15666. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  15667. var path = options.path;
  15668. var shape = options.shape;
  15669. var scale = options.scale || 1;
  15670. var rotation = options.rotation || 0;
  15671. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15672. var updatable = options.updatable;
  15673. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15674. var instance = options.instance;
  15675. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15676. };
  15677. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  15678. var path = options.path;
  15679. var shape = options.shape;
  15680. var scaleFunction = options.scaleFunction || (function () { return 1; });
  15681. var rotationFunction = options.rotationFunction || (function () { return 0; });
  15682. var ribbonCloseArray = options.ribbonCloseArray || false;
  15683. var ribbonClosePath = options.ribbonClosePath || false;
  15684. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15685. var updatable = options.updatable;
  15686. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15687. var instance = options.instance;
  15688. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  15689. };
  15690. MeshBuilder.CreateLathe = function (name, options, scene) {
  15691. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  15692. var closed = (options.closed === undefined) ? true : options.closed;
  15693. var shape = options.shape;
  15694. var radius = options.radius || 1;
  15695. var tessellation = options.tessellation || 64;
  15696. var updatable = options.updatable;
  15697. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15698. var pi2 = Math.PI * 2;
  15699. var shapeLathe = new Array();
  15700. // first rotatable point
  15701. var i = 0;
  15702. while (shape[i].x === 0) {
  15703. i++;
  15704. }
  15705. var pt = shape[i];
  15706. for (i = 0; i < shape.length; i++) {
  15707. shapeLathe.push(shape[i].subtract(pt));
  15708. }
  15709. // circle path
  15710. var step = pi2 / tessellation * arc;
  15711. var rotated;
  15712. var path = new Array();
  15713. ;
  15714. for (i = 0; i <= tessellation; i++) {
  15715. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15716. path.push(rotated);
  15717. }
  15718. if (closed) {
  15719. path.push(path[0]);
  15720. }
  15721. // extrusion
  15722. var scaleFunction = function () { return 1; };
  15723. var rotateFunction = function () { return 0; };
  15724. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  15725. return lathe;
  15726. };
  15727. MeshBuilder.CreatePlane = function (name, options, scene) {
  15728. var plane = new BABYLON.Mesh(name, scene);
  15729. var vertexData = BABYLON.VertexData.CreatePlane(options);
  15730. vertexData.applyToMesh(plane, options.updatable);
  15731. if (options.sourcePlane) {
  15732. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  15733. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  15734. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  15735. plane.rotate(vectorProduct, product);
  15736. }
  15737. return plane;
  15738. };
  15739. MeshBuilder.CreateGround = function (name, options, scene) {
  15740. var ground = new BABYLON.GroundMesh(name, scene);
  15741. ground._setReady(false);
  15742. ground._subdivisions = options.subdivisions || 1;
  15743. var vertexData = BABYLON.VertexData.CreateGround(options);
  15744. vertexData.applyToMesh(ground, options.updatable);
  15745. ground._setReady(true);
  15746. return ground;
  15747. };
  15748. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  15749. var tiledGround = new BABYLON.Mesh(name, scene);
  15750. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  15751. vertexData.applyToMesh(tiledGround, options.updatable);
  15752. return tiledGround;
  15753. };
  15754. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  15755. var width = options.width || 10;
  15756. var height = options.height || 10;
  15757. var subdivisions = options.subdivisions || 1;
  15758. var minHeight = options.minHeight;
  15759. var maxHeight = options.maxHeight || 10;
  15760. var updatable = options.updatable;
  15761. var onReady = options.onReady;
  15762. var ground = new BABYLON.GroundMesh(name, scene);
  15763. ground._subdivisions = subdivisions;
  15764. ground._setReady(false);
  15765. var onload = function (img) {
  15766. // Getting height map data
  15767. var canvas = document.createElement("canvas");
  15768. var context = canvas.getContext("2d");
  15769. var bufferWidth = img.width;
  15770. var bufferHeight = img.height;
  15771. canvas.width = bufferWidth;
  15772. canvas.height = bufferHeight;
  15773. context.drawImage(img, 0, 0);
  15774. // Create VertexData from map data
  15775. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15776. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  15777. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  15778. width: width, height: height,
  15779. subdivisions: subdivisions,
  15780. minHeight: minHeight, maxHeight: maxHeight,
  15781. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  15782. });
  15783. vertexData.applyToMesh(ground, updatable);
  15784. ground._setReady(true);
  15785. //execute ready callback, if set
  15786. if (onReady) {
  15787. onReady(ground);
  15788. }
  15789. };
  15790. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15791. return ground;
  15792. };
  15793. MeshBuilder.CreateTube = function (name, options, scene) {
  15794. var path = options.path;
  15795. var radius = options.radius || 1;
  15796. var tessellation = options.tessellation || 64;
  15797. var radiusFunction = options.radiusFunction;
  15798. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  15799. var updatable = options.updatable;
  15800. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15801. var instance = options.instance;
  15802. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  15803. // tube geometry
  15804. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  15805. var tangents = path3D.getTangents();
  15806. var normals = path3D.getNormals();
  15807. var distances = path3D.getDistances();
  15808. var pi2 = Math.PI * 2;
  15809. var step = pi2 / tessellation * arc;
  15810. var returnRadius = function () { return radius; };
  15811. var radiusFunctionFinal = radiusFunction || returnRadius;
  15812. var circlePath;
  15813. var rad;
  15814. var normal;
  15815. var rotated;
  15816. var rotationMatrix = BABYLON.Matrix.Zero();
  15817. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15818. for (var i = 0; i < path.length; i++) {
  15819. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15820. circlePath = Array(); // current circle array
  15821. normal = normals[i]; // current normal
  15822. for (var t = 0; t < tessellation; t++) {
  15823. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  15824. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15825. circlePath.push(rotated);
  15826. }
  15827. circlePaths[index] = circlePath;
  15828. index++;
  15829. }
  15830. // cap
  15831. var capPath = function (nbPoints, pathIndex) {
  15832. var pointCap = Array();
  15833. for (var i = 0; i < nbPoints; i++) {
  15834. pointCap.push(path[pathIndex]);
  15835. }
  15836. return pointCap;
  15837. };
  15838. switch (cap) {
  15839. case BABYLON.Mesh.NO_CAP:
  15840. break;
  15841. case BABYLON.Mesh.CAP_START:
  15842. circlePaths[0] = capPath(tessellation, 0);
  15843. circlePaths[1] = circlePaths[2].slice(0);
  15844. break;
  15845. case BABYLON.Mesh.CAP_END:
  15846. circlePaths[index] = circlePaths[index - 1].slice(0);
  15847. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15848. break;
  15849. case BABYLON.Mesh.CAP_ALL:
  15850. circlePaths[0] = capPath(tessellation, 0);
  15851. circlePaths[1] = circlePaths[2].slice(0);
  15852. circlePaths[index] = circlePaths[index - 1].slice(0);
  15853. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15854. break;
  15855. default:
  15856. break;
  15857. }
  15858. return circlePaths;
  15859. };
  15860. var path3D;
  15861. var pathArray;
  15862. if (instance) {
  15863. var arc = options.arc || instance.arc;
  15864. path3D = (instance.path3D).update(path);
  15865. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  15866. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  15867. instance.path3D = path3D;
  15868. instance.pathArray = pathArray;
  15869. instance.arc = arc;
  15870. return instance;
  15871. }
  15872. // tube creation
  15873. path3D = new BABYLON.Path3D(path);
  15874. var newPathArray = new Array();
  15875. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15876. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  15877. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  15878. tube.pathArray = pathArray;
  15879. tube.path3D = path3D;
  15880. tube.tessellation = tessellation;
  15881. tube.cap = cap;
  15882. tube.arc = options.arc;
  15883. return tube;
  15884. };
  15885. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  15886. var polyhedron = new BABYLON.Mesh(name, scene);
  15887. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  15888. vertexData.applyToMesh(polyhedron, options.updatable);
  15889. return polyhedron;
  15890. };
  15891. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  15892. var indices = sourceMesh.getIndices();
  15893. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15894. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15895. var position = options.position || BABYLON.Vector3.Zero();
  15896. var normal = options.normal || BABYLON.Vector3.Up();
  15897. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  15898. var angle = options.angle || 0;
  15899. // Getting correct rotation
  15900. if (!normal) {
  15901. var target = new BABYLON.Vector3(0, 0, 1);
  15902. var camera = sourceMesh.getScene().activeCamera;
  15903. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15904. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15905. }
  15906. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15907. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15908. var pitch = Math.atan2(normal.y, len);
  15909. // Matrix
  15910. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15911. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15912. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15913. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15914. var vertexData = new BABYLON.VertexData();
  15915. vertexData.indices = [];
  15916. vertexData.positions = [];
  15917. vertexData.normals = [];
  15918. vertexData.uvs = [];
  15919. var currentVertexDataIndex = 0;
  15920. var extractDecalVector3 = function (indexId) {
  15921. var vertexId = indices[indexId];
  15922. var result = new BABYLON.PositionNormalVertex();
  15923. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15924. // Send vector to decal local world
  15925. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15926. // Get normal
  15927. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15928. return result;
  15929. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15930. var clip = function (vertices, axis) {
  15931. if (vertices.length === 0) {
  15932. return vertices;
  15933. }
  15934. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15935. var clipVertices = function (v0, v1) {
  15936. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15937. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15938. };
  15939. var result = new Array();
  15940. for (var index = 0; index < vertices.length; index += 3) {
  15941. var v1Out;
  15942. var v2Out;
  15943. var v3Out;
  15944. var total = 0;
  15945. var nV1, nV2, nV3, nV4;
  15946. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15947. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15948. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15949. v1Out = d1 > 0;
  15950. v2Out = d2 > 0;
  15951. v3Out = d3 > 0;
  15952. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15953. switch (total) {
  15954. case 0:
  15955. result.push(vertices[index]);
  15956. result.push(vertices[index + 1]);
  15957. result.push(vertices[index + 2]);
  15958. break;
  15959. case 1:
  15960. if (v1Out) {
  15961. nV1 = vertices[index + 1];
  15962. nV2 = vertices[index + 2];
  15963. nV3 = clipVertices(vertices[index], nV1);
  15964. nV4 = clipVertices(vertices[index], nV2);
  15965. }
  15966. if (v2Out) {
  15967. nV1 = vertices[index];
  15968. nV2 = vertices[index + 2];
  15969. nV3 = clipVertices(vertices[index + 1], nV1);
  15970. nV4 = clipVertices(vertices[index + 1], nV2);
  15971. result.push(nV3);
  15972. result.push(nV2.clone());
  15973. result.push(nV1.clone());
  15974. result.push(nV2.clone());
  15975. result.push(nV3.clone());
  15976. result.push(nV4);
  15977. break;
  15978. }
  15979. if (v3Out) {
  15980. nV1 = vertices[index];
  15981. nV2 = vertices[index + 1];
  15982. nV3 = clipVertices(vertices[index + 2], nV1);
  15983. nV4 = clipVertices(vertices[index + 2], nV2);
  15984. }
  15985. result.push(nV1.clone());
  15986. result.push(nV2.clone());
  15987. result.push(nV3);
  15988. result.push(nV4);
  15989. result.push(nV3.clone());
  15990. result.push(nV2.clone());
  15991. break;
  15992. case 2:
  15993. if (!v1Out) {
  15994. nV1 = vertices[index].clone();
  15995. nV2 = clipVertices(nV1, vertices[index + 1]);
  15996. nV3 = clipVertices(nV1, vertices[index + 2]);
  15997. result.push(nV1);
  15998. result.push(nV2);
  15999. result.push(nV3);
  16000. }
  16001. if (!v2Out) {
  16002. nV1 = vertices[index + 1].clone();
  16003. nV2 = clipVertices(nV1, vertices[index + 2]);
  16004. nV3 = clipVertices(nV1, vertices[index]);
  16005. result.push(nV1);
  16006. result.push(nV2);
  16007. result.push(nV3);
  16008. }
  16009. if (!v3Out) {
  16010. nV1 = vertices[index + 2].clone();
  16011. nV2 = clipVertices(nV1, vertices[index]);
  16012. nV3 = clipVertices(nV1, vertices[index + 1]);
  16013. result.push(nV1);
  16014. result.push(nV2);
  16015. result.push(nV3);
  16016. }
  16017. break;
  16018. case 3:
  16019. break;
  16020. }
  16021. }
  16022. return result;
  16023. };
  16024. for (var index = 0; index < indices.length; index += 3) {
  16025. var faceVertices = new Array();
  16026. faceVertices.push(extractDecalVector3(index));
  16027. faceVertices.push(extractDecalVector3(index + 1));
  16028. faceVertices.push(extractDecalVector3(index + 2));
  16029. // Clip
  16030. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16031. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16032. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16033. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16034. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16035. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16036. if (faceVertices.length === 0) {
  16037. continue;
  16038. }
  16039. // Add UVs and get back to world
  16040. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16041. var vertex = faceVertices[vIndex];
  16042. vertexData.indices.push(currentVertexDataIndex);
  16043. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16044. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16045. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16046. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16047. currentVertexDataIndex++;
  16048. }
  16049. }
  16050. // Return mesh
  16051. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16052. vertexData.applyToMesh(decal);
  16053. decal.position = position.clone();
  16054. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16055. return decal;
  16056. };
  16057. // Privates
  16058. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16059. // extrusion geometry
  16060. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16061. var tangents = path3D.getTangents();
  16062. var normals = path3D.getNormals();
  16063. var binormals = path3D.getBinormals();
  16064. var distances = path3D.getDistances();
  16065. var angle = 0;
  16066. var returnScale = function () { return scale; };
  16067. var returnRotation = function () { return rotation; };
  16068. var rotate = custom ? rotateFunction : returnRotation;
  16069. var scl = custom ? scaleFunction : returnScale;
  16070. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16071. var rotationMatrix = BABYLON.Matrix.Zero();
  16072. for (var i = 0; i < curve.length; i++) {
  16073. var shapePath = new Array();
  16074. var angleStep = rotate(i, distances[i]);
  16075. var scaleRatio = scl(i, distances[i]);
  16076. for (var p = 0; p < shape.length; p++) {
  16077. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16078. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16079. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16080. shapePath.push(rotated);
  16081. }
  16082. shapePaths[index] = shapePath;
  16083. angle += angleStep;
  16084. index++;
  16085. }
  16086. // cap
  16087. var capPath = function (shapePath) {
  16088. var pointCap = Array();
  16089. var barycenter = BABYLON.Vector3.Zero();
  16090. var i;
  16091. for (i = 0; i < shapePath.length; i++) {
  16092. barycenter.addInPlace(shapePath[i]);
  16093. }
  16094. barycenter.scaleInPlace(1 / shapePath.length);
  16095. for (i = 0; i < shapePath.length; i++) {
  16096. pointCap.push(barycenter);
  16097. }
  16098. return pointCap;
  16099. };
  16100. switch (cap) {
  16101. case BABYLON.Mesh.NO_CAP:
  16102. break;
  16103. case BABYLON.Mesh.CAP_START:
  16104. shapePaths[0] = capPath(shapePaths[2]);
  16105. shapePaths[1] = shapePaths[2].slice(0);
  16106. break;
  16107. case BABYLON.Mesh.CAP_END:
  16108. shapePaths[index] = shapePaths[index - 1];
  16109. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16110. break;
  16111. case BABYLON.Mesh.CAP_ALL:
  16112. shapePaths[0] = capPath(shapePaths[2]);
  16113. shapePaths[1] = shapePaths[2].slice(0);
  16114. shapePaths[index] = shapePaths[index - 1];
  16115. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16116. break;
  16117. default:
  16118. break;
  16119. }
  16120. return shapePaths;
  16121. };
  16122. var path3D;
  16123. var pathArray;
  16124. if (instance) {
  16125. path3D = (instance.path3D).update(curve);
  16126. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16127. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16128. return instance;
  16129. }
  16130. // extruded shape creation
  16131. path3D = new BABYLON.Path3D(curve);
  16132. var newShapePaths = new Array();
  16133. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16134. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16135. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16136. extrudedGeneric.pathArray = pathArray;
  16137. extrudedGeneric.path3D = path3D;
  16138. extrudedGeneric.cap = cap;
  16139. return extrudedGeneric;
  16140. };
  16141. return MeshBuilder;
  16142. })();
  16143. BABYLON.MeshBuilder = MeshBuilder;
  16144. })(BABYLON || (BABYLON = {}));
  16145. var BABYLON;
  16146. (function (BABYLON) {
  16147. var BaseTexture = (function () {
  16148. function BaseTexture(scene) {
  16149. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16150. this.hasAlpha = false;
  16151. this.getAlphaFromRGB = false;
  16152. this.level = 1;
  16153. this.isCube = false;
  16154. this.isRenderTarget = false;
  16155. this.animations = new Array();
  16156. this.coordinatesIndex = 0;
  16157. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16158. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16159. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16160. this.anisotropicFilteringLevel = 4;
  16161. this._scene = scene;
  16162. this._scene.textures.push(this);
  16163. }
  16164. BaseTexture.prototype.getScene = function () {
  16165. return this._scene;
  16166. };
  16167. BaseTexture.prototype.getTextureMatrix = function () {
  16168. return null;
  16169. };
  16170. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16171. return null;
  16172. };
  16173. BaseTexture.prototype.getInternalTexture = function () {
  16174. return this._texture;
  16175. };
  16176. BaseTexture.prototype.isReady = function () {
  16177. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16178. return true;
  16179. }
  16180. if (this._texture) {
  16181. return this._texture.isReady;
  16182. }
  16183. return false;
  16184. };
  16185. BaseTexture.prototype.getSize = function () {
  16186. if (this._texture._width) {
  16187. return { width: this._texture._width, height: this._texture._height };
  16188. }
  16189. if (this._texture._size) {
  16190. return { width: this._texture._size, height: this._texture._size };
  16191. }
  16192. return { width: 0, height: 0 };
  16193. };
  16194. BaseTexture.prototype.getBaseSize = function () {
  16195. if (!this.isReady())
  16196. return { width: 0, height: 0 };
  16197. if (this._texture._size) {
  16198. return { width: this._texture._size, height: this._texture._size };
  16199. }
  16200. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16201. };
  16202. BaseTexture.prototype.scale = function (ratio) {
  16203. };
  16204. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16205. get: function () {
  16206. return false;
  16207. },
  16208. enumerable: true,
  16209. configurable: true
  16210. });
  16211. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16212. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16213. for (var index = 0; index < texturesCache.length; index++) {
  16214. var texturesCacheEntry = texturesCache[index];
  16215. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16216. texturesCache.splice(index, 1);
  16217. return;
  16218. }
  16219. }
  16220. };
  16221. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16222. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16223. for (var index = 0; index < texturesCache.length; index++) {
  16224. var texturesCacheEntry = texturesCache[index];
  16225. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16226. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16227. texturesCacheEntry.references++;
  16228. return texturesCacheEntry;
  16229. }
  16230. }
  16231. }
  16232. return null;
  16233. };
  16234. BaseTexture.prototype.delayLoad = function () {
  16235. };
  16236. BaseTexture.prototype.clone = function () {
  16237. return null;
  16238. };
  16239. BaseTexture.prototype.releaseInternalTexture = function () {
  16240. if (this._texture) {
  16241. this._scene.getEngine().releaseInternalTexture(this._texture);
  16242. delete this._texture;
  16243. }
  16244. };
  16245. BaseTexture.prototype.dispose = function () {
  16246. // Animations
  16247. this.getScene().stopAnimation(this);
  16248. // Remove from scene
  16249. var index = this._scene.textures.indexOf(this);
  16250. if (index >= 0) {
  16251. this._scene.textures.splice(index, 1);
  16252. }
  16253. if (this._texture === undefined) {
  16254. return;
  16255. }
  16256. // Callback
  16257. if (this.onDispose) {
  16258. this.onDispose();
  16259. }
  16260. };
  16261. return BaseTexture;
  16262. })();
  16263. BABYLON.BaseTexture = BaseTexture;
  16264. })(BABYLON || (BABYLON = {}));
  16265. var BABYLON;
  16266. (function (BABYLON) {
  16267. var Texture = (function (_super) {
  16268. __extends(Texture, _super);
  16269. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16270. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16271. if (onLoad === void 0) { onLoad = null; }
  16272. if (onError === void 0) { onError = null; }
  16273. if (buffer === void 0) { buffer = null; }
  16274. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16275. _super.call(this, scene);
  16276. this.uOffset = 0;
  16277. this.vOffset = 0;
  16278. this.uScale = 1.0;
  16279. this.vScale = 1.0;
  16280. this.uAng = 0;
  16281. this.vAng = 0;
  16282. this.wAng = 0;
  16283. this.name = url;
  16284. this.url = url;
  16285. this._noMipmap = noMipmap;
  16286. this._invertY = invertY;
  16287. this._samplingMode = samplingMode;
  16288. this._buffer = buffer;
  16289. this._deleteBuffer = deleteBuffer;
  16290. if (!url) {
  16291. return;
  16292. }
  16293. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16294. if (!this._texture) {
  16295. if (!scene.useDelayedTextureLoading) {
  16296. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16297. if (deleteBuffer) {
  16298. delete this._buffer;
  16299. }
  16300. }
  16301. else {
  16302. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16303. }
  16304. }
  16305. else {
  16306. BABYLON.Tools.SetImmediate(function () {
  16307. if (onLoad) {
  16308. onLoad();
  16309. }
  16310. });
  16311. }
  16312. }
  16313. Texture.prototype.delayLoad = function () {
  16314. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16315. return;
  16316. }
  16317. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16318. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16319. if (!this._texture) {
  16320. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16321. if (this._deleteBuffer) {
  16322. delete this._buffer;
  16323. }
  16324. }
  16325. };
  16326. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16327. if (!this._texture) {
  16328. return;
  16329. }
  16330. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16331. };
  16332. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16333. x *= this.uScale;
  16334. y *= this.vScale;
  16335. x -= 0.5 * this.uScale;
  16336. y -= 0.5 * this.vScale;
  16337. z -= 0.5;
  16338. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16339. t.x += 0.5 * this.uScale + this.uOffset;
  16340. t.y += 0.5 * this.vScale + this.vOffset;
  16341. t.z += 0.5;
  16342. };
  16343. Texture.prototype.getTextureMatrix = function () {
  16344. if (this.uOffset === this._cachedUOffset &&
  16345. this.vOffset === this._cachedVOffset &&
  16346. this.uScale === this._cachedUScale &&
  16347. this.vScale === this._cachedVScale &&
  16348. this.uAng === this._cachedUAng &&
  16349. this.vAng === this._cachedVAng &&
  16350. this.wAng === this._cachedWAng) {
  16351. return this._cachedTextureMatrix;
  16352. }
  16353. this._cachedUOffset = this.uOffset;
  16354. this._cachedVOffset = this.vOffset;
  16355. this._cachedUScale = this.uScale;
  16356. this._cachedVScale = this.vScale;
  16357. this._cachedUAng = this.uAng;
  16358. this._cachedVAng = this.vAng;
  16359. this._cachedWAng = this.wAng;
  16360. if (!this._cachedTextureMatrix) {
  16361. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16362. this._rowGenerationMatrix = new BABYLON.Matrix();
  16363. this._t0 = BABYLON.Vector3.Zero();
  16364. this._t1 = BABYLON.Vector3.Zero();
  16365. this._t2 = BABYLON.Vector3.Zero();
  16366. }
  16367. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16368. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16369. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16370. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16371. this._t1.subtractInPlace(this._t0);
  16372. this._t2.subtractInPlace(this._t0);
  16373. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16374. this._cachedTextureMatrix.m[0] = this._t1.x;
  16375. this._cachedTextureMatrix.m[1] = this._t1.y;
  16376. this._cachedTextureMatrix.m[2] = this._t1.z;
  16377. this._cachedTextureMatrix.m[4] = this._t2.x;
  16378. this._cachedTextureMatrix.m[5] = this._t2.y;
  16379. this._cachedTextureMatrix.m[6] = this._t2.z;
  16380. this._cachedTextureMatrix.m[8] = this._t0.x;
  16381. this._cachedTextureMatrix.m[9] = this._t0.y;
  16382. this._cachedTextureMatrix.m[10] = this._t0.z;
  16383. return this._cachedTextureMatrix;
  16384. };
  16385. Texture.prototype.getReflectionTextureMatrix = function () {
  16386. if (this.uOffset === this._cachedUOffset &&
  16387. this.vOffset === this._cachedVOffset &&
  16388. this.uScale === this._cachedUScale &&
  16389. this.vScale === this._cachedVScale &&
  16390. this.coordinatesMode === this._cachedCoordinatesMode) {
  16391. return this._cachedTextureMatrix;
  16392. }
  16393. if (!this._cachedTextureMatrix) {
  16394. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16395. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16396. }
  16397. this._cachedCoordinatesMode = this.coordinatesMode;
  16398. switch (this.coordinatesMode) {
  16399. case Texture.PLANAR_MODE:
  16400. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16401. this._cachedTextureMatrix[0] = this.uScale;
  16402. this._cachedTextureMatrix[5] = this.vScale;
  16403. this._cachedTextureMatrix[12] = this.uOffset;
  16404. this._cachedTextureMatrix[13] = this.vOffset;
  16405. break;
  16406. case Texture.PROJECTION_MODE:
  16407. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16408. this._projectionModeMatrix.m[0] = 0.5;
  16409. this._projectionModeMatrix.m[5] = -0.5;
  16410. this._projectionModeMatrix.m[10] = 0.0;
  16411. this._projectionModeMatrix.m[12] = 0.5;
  16412. this._projectionModeMatrix.m[13] = 0.5;
  16413. this._projectionModeMatrix.m[14] = 1.0;
  16414. this._projectionModeMatrix.m[15] = 1.0;
  16415. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16416. break;
  16417. default:
  16418. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16419. break;
  16420. }
  16421. return this._cachedTextureMatrix;
  16422. };
  16423. Texture.prototype.clone = function () {
  16424. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16425. // Base texture
  16426. newTexture.hasAlpha = this.hasAlpha;
  16427. newTexture.level = this.level;
  16428. newTexture.wrapU = this.wrapU;
  16429. newTexture.wrapV = this.wrapV;
  16430. newTexture.coordinatesIndex = this.coordinatesIndex;
  16431. newTexture.coordinatesMode = this.coordinatesMode;
  16432. // Texture
  16433. newTexture.uOffset = this.uOffset;
  16434. newTexture.vOffset = this.vOffset;
  16435. newTexture.uScale = this.uScale;
  16436. newTexture.vScale = this.vScale;
  16437. newTexture.uAng = this.uAng;
  16438. newTexture.vAng = this.vAng;
  16439. newTexture.wAng = this.wAng;
  16440. return newTexture;
  16441. };
  16442. // Statics
  16443. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16444. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16445. if (onLoad === void 0) { onLoad = null; }
  16446. if (onError === void 0) { onError = null; }
  16447. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16448. };
  16449. // Constants
  16450. Texture.NEAREST_SAMPLINGMODE = 1;
  16451. Texture.BILINEAR_SAMPLINGMODE = 2;
  16452. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16453. Texture.EXPLICIT_MODE = 0;
  16454. Texture.SPHERICAL_MODE = 1;
  16455. Texture.PLANAR_MODE = 2;
  16456. Texture.CUBIC_MODE = 3;
  16457. Texture.PROJECTION_MODE = 4;
  16458. Texture.SKYBOX_MODE = 5;
  16459. Texture.INVCUBIC_MODE = 6;
  16460. Texture.EQUIRECTANGULAR_MODE = 7;
  16461. Texture.CLAMP_ADDRESSMODE = 0;
  16462. Texture.WRAP_ADDRESSMODE = 1;
  16463. Texture.MIRROR_ADDRESSMODE = 2;
  16464. return Texture;
  16465. })(BABYLON.BaseTexture);
  16466. BABYLON.Texture = Texture;
  16467. })(BABYLON || (BABYLON = {}));
  16468. var BABYLON;
  16469. (function (BABYLON) {
  16470. var CubeTexture = (function (_super) {
  16471. __extends(CubeTexture, _super);
  16472. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16473. _super.call(this, scene);
  16474. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16475. this.name = rootUrl;
  16476. this.url = rootUrl;
  16477. this._noMipmap = noMipmap;
  16478. this.hasAlpha = false;
  16479. if (!rootUrl) {
  16480. return;
  16481. }
  16482. this._texture = this._getFromCache(rootUrl, noMipmap);
  16483. if (!extensions) {
  16484. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16485. }
  16486. this._extensions = extensions;
  16487. if (!this._texture) {
  16488. if (!scene.useDelayedTextureLoading) {
  16489. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16490. }
  16491. else {
  16492. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16493. }
  16494. }
  16495. this.isCube = true;
  16496. this._textureMatrix = BABYLON.Matrix.Identity();
  16497. }
  16498. CubeTexture.prototype.clone = function () {
  16499. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16500. // Base texture
  16501. newTexture.level = this.level;
  16502. newTexture.wrapU = this.wrapU;
  16503. newTexture.wrapV = this.wrapV;
  16504. newTexture.coordinatesIndex = this.coordinatesIndex;
  16505. newTexture.coordinatesMode = this.coordinatesMode;
  16506. return newTexture;
  16507. };
  16508. // Methods
  16509. CubeTexture.prototype.delayLoad = function () {
  16510. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16511. return;
  16512. }
  16513. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16514. this._texture = this._getFromCache(this.url, this._noMipmap);
  16515. if (!this._texture) {
  16516. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16517. }
  16518. };
  16519. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16520. return this._textureMatrix;
  16521. };
  16522. return CubeTexture;
  16523. })(BABYLON.BaseTexture);
  16524. BABYLON.CubeTexture = CubeTexture;
  16525. })(BABYLON || (BABYLON = {}));
  16526. var BABYLON;
  16527. (function (BABYLON) {
  16528. var RenderTargetTexture = (function (_super) {
  16529. __extends(RenderTargetTexture, _super);
  16530. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  16531. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16532. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16533. if (isCube === void 0) { isCube = false; }
  16534. _super.call(this, null, scene, !generateMipMaps);
  16535. this.isCube = isCube;
  16536. this.renderList = new Array();
  16537. this.renderParticles = true;
  16538. this.renderSprites = false;
  16539. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16540. this._currentRefreshId = -1;
  16541. this._refreshRate = 1;
  16542. this.name = name;
  16543. this.isRenderTarget = true;
  16544. this._size = size;
  16545. this._generateMipMaps = generateMipMaps;
  16546. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16547. if (isCube) {
  16548. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  16549. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  16550. this._textureMatrix = BABYLON.Matrix.Identity();
  16551. }
  16552. else {
  16553. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16554. }
  16555. // Rendering groups
  16556. this._renderingManager = new BABYLON.RenderingManager(scene);
  16557. }
  16558. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  16559. get: function () {
  16560. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  16561. },
  16562. enumerable: true,
  16563. configurable: true
  16564. });
  16565. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  16566. get: function () {
  16567. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  16568. },
  16569. enumerable: true,
  16570. configurable: true
  16571. });
  16572. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  16573. get: function () {
  16574. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  16575. },
  16576. enumerable: true,
  16577. configurable: true
  16578. });
  16579. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16580. this._currentRefreshId = -1;
  16581. };
  16582. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16583. get: function () {
  16584. return this._refreshRate;
  16585. },
  16586. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16587. set: function (value) {
  16588. this._refreshRate = value;
  16589. this.resetRefreshCounter();
  16590. },
  16591. enumerable: true,
  16592. configurable: true
  16593. });
  16594. RenderTargetTexture.prototype._shouldRender = function () {
  16595. if (this._currentRefreshId === -1) {
  16596. this._currentRefreshId = 1;
  16597. return true;
  16598. }
  16599. if (this.refreshRate === this._currentRefreshId) {
  16600. this._currentRefreshId = 1;
  16601. return true;
  16602. }
  16603. this._currentRefreshId++;
  16604. return false;
  16605. };
  16606. RenderTargetTexture.prototype.isReady = function () {
  16607. if (!this.getScene().renderTargetsEnabled) {
  16608. return false;
  16609. }
  16610. return _super.prototype.isReady.call(this);
  16611. };
  16612. RenderTargetTexture.prototype.getRenderSize = function () {
  16613. return this._size;
  16614. };
  16615. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16616. get: function () {
  16617. return true;
  16618. },
  16619. enumerable: true,
  16620. configurable: true
  16621. });
  16622. RenderTargetTexture.prototype.scale = function (ratio) {
  16623. var newSize = this._size * ratio;
  16624. this.resize(newSize, this._generateMipMaps);
  16625. };
  16626. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  16627. if (this.isCube) {
  16628. return this._textureMatrix;
  16629. }
  16630. return _super.prototype.getReflectionTextureMatrix.call(this);
  16631. };
  16632. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16633. this.releaseInternalTexture();
  16634. if (this.isCube) {
  16635. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  16636. }
  16637. else {
  16638. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16639. }
  16640. };
  16641. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16642. var scene = this.getScene();
  16643. if (this._waitingRenderList) {
  16644. this.renderList = [];
  16645. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16646. var id = this._waitingRenderList[index];
  16647. this.renderList.push(scene.getMeshByID(id));
  16648. }
  16649. delete this._waitingRenderList;
  16650. }
  16651. if (this.renderList && this.renderList.length === 0) {
  16652. return;
  16653. }
  16654. // Prepare renderingManager
  16655. this._renderingManager.reset();
  16656. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16657. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16658. var mesh = currentRenderList[meshIndex];
  16659. if (mesh) {
  16660. if (!mesh.isReady()) {
  16661. // Reset _currentRefreshId
  16662. this.resetRefreshCounter();
  16663. continue;
  16664. }
  16665. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16666. mesh._activate(scene.getRenderId());
  16667. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16668. var subMesh = mesh.subMeshes[subIndex];
  16669. scene._activeIndices += subMesh.indexCount;
  16670. this._renderingManager.dispatch(subMesh);
  16671. }
  16672. }
  16673. }
  16674. }
  16675. if (this.isCube) {
  16676. for (var face = 0; face < 6; face++) {
  16677. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  16678. }
  16679. }
  16680. else {
  16681. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  16682. }
  16683. if (this.onAfterUnbind) {
  16684. this.onAfterUnbind();
  16685. }
  16686. scene.resetCachedMaterial();
  16687. };
  16688. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  16689. var scene = this.getScene();
  16690. var engine = scene.getEngine();
  16691. // Bind
  16692. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16693. if (this.isCube) {
  16694. engine.bindFramebuffer(this._texture, faceIndex);
  16695. }
  16696. else {
  16697. engine.bindFramebuffer(this._texture);
  16698. }
  16699. }
  16700. if (this.onBeforeRender) {
  16701. this.onBeforeRender(faceIndex);
  16702. }
  16703. // Clear
  16704. if (this.onClear) {
  16705. this.onClear(engine);
  16706. }
  16707. else {
  16708. engine.clear(scene.clearColor, true, true);
  16709. }
  16710. if (!this._doNotChangeAspectRatio) {
  16711. scene.updateTransformMatrix(true);
  16712. }
  16713. // Render
  16714. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16715. if (useCameraPostProcess) {
  16716. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  16717. }
  16718. if (!this._doNotChangeAspectRatio) {
  16719. scene.updateTransformMatrix(true);
  16720. }
  16721. if (this.onAfterRender) {
  16722. this.onAfterRender(faceIndex);
  16723. }
  16724. // Dump ?
  16725. if (dumpForDebug) {
  16726. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16727. }
  16728. // Unbind
  16729. if (!this.isCube || faceIndex === 5) {
  16730. if (this.isCube) {
  16731. if (faceIndex === 5) {
  16732. engine.generateMipMapsForCubemap(this._texture);
  16733. }
  16734. }
  16735. engine.unBindFramebuffer(this._texture, this.isCube);
  16736. }
  16737. };
  16738. RenderTargetTexture.prototype.clone = function () {
  16739. var textureSize = this.getSize();
  16740. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16741. // Base texture
  16742. newTexture.hasAlpha = this.hasAlpha;
  16743. newTexture.level = this.level;
  16744. // RenderTarget Texture
  16745. newTexture.coordinatesMode = this.coordinatesMode;
  16746. newTexture.renderList = this.renderList.slice(0);
  16747. return newTexture;
  16748. };
  16749. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  16750. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  16751. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  16752. return RenderTargetTexture;
  16753. })(BABYLON.Texture);
  16754. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16755. })(BABYLON || (BABYLON = {}));
  16756. var BABYLON;
  16757. (function (BABYLON) {
  16758. var ProceduralTexture = (function (_super) {
  16759. __extends(ProceduralTexture, _super);
  16760. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16761. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16762. _super.call(this, null, scene, !generateMipMaps);
  16763. this.isEnabled = true;
  16764. this._currentRefreshId = -1;
  16765. this._refreshRate = 1;
  16766. this._vertexDeclaration = [2];
  16767. this._vertexStrideSize = 2 * 4;
  16768. this._uniforms = new Array();
  16769. this._samplers = new Array();
  16770. this._textures = new Array();
  16771. this._floats = new Array();
  16772. this._floatsArrays = {};
  16773. this._colors3 = new Array();
  16774. this._colors4 = new Array();
  16775. this._vectors2 = new Array();
  16776. this._vectors3 = new Array();
  16777. this._matrices = new Array();
  16778. this._fallbackTextureUsed = false;
  16779. scene._proceduralTextures.push(this);
  16780. this.name = name;
  16781. this.isRenderTarget = true;
  16782. this._size = size;
  16783. this._generateMipMaps = generateMipMaps;
  16784. this.setFragment(fragment);
  16785. this._fallbackTexture = fallbackTexture;
  16786. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16787. // VBO
  16788. var vertices = [];
  16789. vertices.push(1, 1);
  16790. vertices.push(-1, 1);
  16791. vertices.push(-1, -1);
  16792. vertices.push(1, -1);
  16793. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16794. // Indices
  16795. var indices = [];
  16796. indices.push(0);
  16797. indices.push(1);
  16798. indices.push(2);
  16799. indices.push(0);
  16800. indices.push(2);
  16801. indices.push(3);
  16802. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16803. }
  16804. ProceduralTexture.prototype.reset = function () {
  16805. if (this._effect === undefined) {
  16806. return;
  16807. }
  16808. var engine = this.getScene().getEngine();
  16809. engine._releaseEffect(this._effect);
  16810. };
  16811. ProceduralTexture.prototype.isReady = function () {
  16812. var _this = this;
  16813. var engine = this.getScene().getEngine();
  16814. var shaders;
  16815. if (!this._fragment) {
  16816. return false;
  16817. }
  16818. if (this._fallbackTextureUsed) {
  16819. return true;
  16820. }
  16821. if (this._fragment.fragmentElement !== undefined) {
  16822. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16823. }
  16824. else {
  16825. shaders = { vertex: "procedural", fragment: this._fragment };
  16826. }
  16827. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16828. _this.releaseInternalTexture();
  16829. if (_this._fallbackTexture) {
  16830. _this._texture = _this._fallbackTexture._texture;
  16831. _this._texture.references++;
  16832. }
  16833. _this._fallbackTextureUsed = true;
  16834. });
  16835. return this._effect.isReady();
  16836. };
  16837. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16838. this._currentRefreshId = -1;
  16839. };
  16840. ProceduralTexture.prototype.setFragment = function (fragment) {
  16841. this._fragment = fragment;
  16842. };
  16843. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16844. get: function () {
  16845. return this._refreshRate;
  16846. },
  16847. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16848. set: function (value) {
  16849. this._refreshRate = value;
  16850. this.resetRefreshCounter();
  16851. },
  16852. enumerable: true,
  16853. configurable: true
  16854. });
  16855. ProceduralTexture.prototype._shouldRender = function () {
  16856. if (!this.isEnabled || !this.isReady() || !this._texture) {
  16857. return false;
  16858. }
  16859. if (this._fallbackTextureUsed) {
  16860. return false;
  16861. }
  16862. if (this._currentRefreshId === -1) {
  16863. this._currentRefreshId = 1;
  16864. return true;
  16865. }
  16866. if (this.refreshRate === this._currentRefreshId) {
  16867. this._currentRefreshId = 1;
  16868. return true;
  16869. }
  16870. this._currentRefreshId++;
  16871. return false;
  16872. };
  16873. ProceduralTexture.prototype.getRenderSize = function () {
  16874. return this._size;
  16875. };
  16876. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16877. if (this._fallbackTextureUsed) {
  16878. return;
  16879. }
  16880. this.releaseInternalTexture();
  16881. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16882. };
  16883. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16884. if (this._uniforms.indexOf(uniformName) === -1) {
  16885. this._uniforms.push(uniformName);
  16886. }
  16887. };
  16888. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16889. if (this._samplers.indexOf(name) === -1) {
  16890. this._samplers.push(name);
  16891. }
  16892. this._textures[name] = texture;
  16893. return this;
  16894. };
  16895. ProceduralTexture.prototype.setFloat = function (name, value) {
  16896. this._checkUniform(name);
  16897. this._floats[name] = value;
  16898. return this;
  16899. };
  16900. ProceduralTexture.prototype.setFloats = function (name, value) {
  16901. this._checkUniform(name);
  16902. this._floatsArrays[name] = value;
  16903. return this;
  16904. };
  16905. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16906. this._checkUniform(name);
  16907. this._colors3[name] = value;
  16908. return this;
  16909. };
  16910. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16911. this._checkUniform(name);
  16912. this._colors4[name] = value;
  16913. return this;
  16914. };
  16915. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16916. this._checkUniform(name);
  16917. this._vectors2[name] = value;
  16918. return this;
  16919. };
  16920. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16921. this._checkUniform(name);
  16922. this._vectors3[name] = value;
  16923. return this;
  16924. };
  16925. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16926. this._checkUniform(name);
  16927. this._matrices[name] = value;
  16928. return this;
  16929. };
  16930. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16931. var scene = this.getScene();
  16932. var engine = scene.getEngine();
  16933. engine.bindFramebuffer(this._texture);
  16934. // Clear
  16935. engine.clear(scene.clearColor, true, true);
  16936. // Render
  16937. engine.enableEffect(this._effect);
  16938. engine.setState(false);
  16939. // Texture
  16940. for (var name in this._textures) {
  16941. this._effect.setTexture(name, this._textures[name]);
  16942. }
  16943. // Float
  16944. for (name in this._floats) {
  16945. this._effect.setFloat(name, this._floats[name]);
  16946. }
  16947. // Floats
  16948. for (name in this._floatsArrays) {
  16949. this._effect.setArray(name, this._floatsArrays[name]);
  16950. }
  16951. // Color3
  16952. for (name in this._colors3) {
  16953. this._effect.setColor3(name, this._colors3[name]);
  16954. }
  16955. // Color4
  16956. for (name in this._colors4) {
  16957. var color = this._colors4[name];
  16958. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16959. }
  16960. // Vector2
  16961. for (name in this._vectors2) {
  16962. this._effect.setVector2(name, this._vectors2[name]);
  16963. }
  16964. // Vector3
  16965. for (name in this._vectors3) {
  16966. this._effect.setVector3(name, this._vectors3[name]);
  16967. }
  16968. // Matrix
  16969. for (name in this._matrices) {
  16970. this._effect.setMatrix(name, this._matrices[name]);
  16971. }
  16972. // VBOs
  16973. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16974. // Draw order
  16975. engine.draw(true, 0, 6);
  16976. // Unbind
  16977. engine.unBindFramebuffer(this._texture);
  16978. };
  16979. ProceduralTexture.prototype.clone = function () {
  16980. var textureSize = this.getSize();
  16981. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16982. // Base texture
  16983. newTexture.hasAlpha = this.hasAlpha;
  16984. newTexture.level = this.level;
  16985. // RenderTarget Texture
  16986. newTexture.coordinatesMode = this.coordinatesMode;
  16987. return newTexture;
  16988. };
  16989. ProceduralTexture.prototype.dispose = function () {
  16990. var index = this.getScene()._proceduralTextures.indexOf(this);
  16991. if (index >= 0) {
  16992. this.getScene()._proceduralTextures.splice(index, 1);
  16993. }
  16994. _super.prototype.dispose.call(this);
  16995. };
  16996. return ProceduralTexture;
  16997. })(BABYLON.Texture);
  16998. BABYLON.ProceduralTexture = ProceduralTexture;
  16999. })(BABYLON || (BABYLON = {}));
  17000. var BABYLON;
  17001. (function (BABYLON) {
  17002. var MirrorTexture = (function (_super) {
  17003. __extends(MirrorTexture, _super);
  17004. function MirrorTexture(name, size, scene, generateMipMaps) {
  17005. var _this = this;
  17006. _super.call(this, name, size, scene, generateMipMaps, true);
  17007. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17008. this._transformMatrix = BABYLON.Matrix.Zero();
  17009. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17010. this.onBeforeRender = function () {
  17011. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17012. _this._savedViewMatrix = scene.getViewMatrix();
  17013. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17014. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17015. scene.clipPlane = _this.mirrorPlane;
  17016. scene.getEngine().cullBackFaces = false;
  17017. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17018. };
  17019. this.onAfterRender = function () {
  17020. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17021. scene.getEngine().cullBackFaces = true;
  17022. scene._mirroredCameraPosition = null;
  17023. delete scene.clipPlane;
  17024. };
  17025. }
  17026. MirrorTexture.prototype.clone = function () {
  17027. var textureSize = this.getSize();
  17028. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17029. // Base texture
  17030. newTexture.hasAlpha = this.hasAlpha;
  17031. newTexture.level = this.level;
  17032. // Mirror Texture
  17033. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17034. newTexture.renderList = this.renderList.slice(0);
  17035. return newTexture;
  17036. };
  17037. return MirrorTexture;
  17038. })(BABYLON.RenderTargetTexture);
  17039. BABYLON.MirrorTexture = MirrorTexture;
  17040. })(BABYLON || (BABYLON = {}));
  17041. var BABYLON;
  17042. (function (BABYLON) {
  17043. var DynamicTexture = (function (_super) {
  17044. __extends(DynamicTexture, _super);
  17045. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17046. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17047. _super.call(this, null, scene, !generateMipMaps);
  17048. this.name = name;
  17049. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17050. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17051. this._generateMipMaps = generateMipMaps;
  17052. if (options.getContext) {
  17053. this._canvas = options;
  17054. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17055. }
  17056. else {
  17057. this._canvas = document.createElement("canvas");
  17058. if (options.width) {
  17059. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17060. }
  17061. else {
  17062. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17063. }
  17064. }
  17065. var textureSize = this.getSize();
  17066. this._canvas.width = textureSize.width;
  17067. this._canvas.height = textureSize.height;
  17068. this._context = this._canvas.getContext("2d");
  17069. }
  17070. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17071. get: function () {
  17072. return true;
  17073. },
  17074. enumerable: true,
  17075. configurable: true
  17076. });
  17077. DynamicTexture.prototype.scale = function (ratio) {
  17078. var textureSize = this.getSize();
  17079. textureSize.width *= ratio;
  17080. textureSize.height *= ratio;
  17081. this._canvas.width = textureSize.width;
  17082. this._canvas.height = textureSize.height;
  17083. this.releaseInternalTexture();
  17084. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17085. };
  17086. DynamicTexture.prototype.getContext = function () {
  17087. return this._context;
  17088. };
  17089. DynamicTexture.prototype.clear = function () {
  17090. var size = this.getSize();
  17091. this._context.fillRect(0, 0, size.width, size.height);
  17092. };
  17093. DynamicTexture.prototype.update = function (invertY) {
  17094. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17095. };
  17096. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17097. if (update === void 0) { update = true; }
  17098. var size = this.getSize();
  17099. if (clearColor) {
  17100. this._context.fillStyle = clearColor;
  17101. this._context.fillRect(0, 0, size.width, size.height);
  17102. }
  17103. this._context.font = font;
  17104. if (x === null) {
  17105. var textSize = this._context.measureText(text);
  17106. x = (size.width - textSize.width) / 2;
  17107. }
  17108. this._context.fillStyle = color;
  17109. this._context.fillText(text, x, y);
  17110. if (update) {
  17111. this.update(invertY);
  17112. }
  17113. };
  17114. DynamicTexture.prototype.clone = function () {
  17115. var textureSize = this.getSize();
  17116. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17117. // Base texture
  17118. newTexture.hasAlpha = this.hasAlpha;
  17119. newTexture.level = this.level;
  17120. // Dynamic Texture
  17121. newTexture.wrapU = this.wrapU;
  17122. newTexture.wrapV = this.wrapV;
  17123. return newTexture;
  17124. };
  17125. return DynamicTexture;
  17126. })(BABYLON.Texture);
  17127. BABYLON.DynamicTexture = DynamicTexture;
  17128. })(BABYLON || (BABYLON = {}));
  17129. var BABYLON;
  17130. (function (BABYLON) {
  17131. var VideoTexture = (function (_super) {
  17132. __extends(VideoTexture, _super);
  17133. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17134. var _this = this;
  17135. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17136. if (invertY === void 0) { invertY = false; }
  17137. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17138. _super.call(this, null, scene, !generateMipMaps, invertY);
  17139. this._autoLaunch = true;
  17140. this.name = name;
  17141. this.video = document.createElement("video");
  17142. this.video.autoplay = false;
  17143. this.video.loop = true;
  17144. this.video.addEventListener("canplaythrough", function () {
  17145. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17146. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17147. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17148. }
  17149. else {
  17150. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17151. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17152. generateMipMaps = false;
  17153. }
  17154. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17155. _this._texture.isReady = true;
  17156. });
  17157. urls.forEach(function (url) {
  17158. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17159. var source = document.createElement("source");
  17160. source.src = url;
  17161. _this.video.appendChild(source);
  17162. });
  17163. this._lastUpdate = BABYLON.Tools.Now;
  17164. }
  17165. VideoTexture.prototype.update = function () {
  17166. if (this._autoLaunch) {
  17167. this._autoLaunch = false;
  17168. this.video.play();
  17169. }
  17170. var now = BABYLON.Tools.Now;
  17171. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17172. return false;
  17173. }
  17174. this._lastUpdate = now;
  17175. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17176. return true;
  17177. };
  17178. return VideoTexture;
  17179. })(BABYLON.Texture);
  17180. BABYLON.VideoTexture = VideoTexture;
  17181. })(BABYLON || (BABYLON = {}));
  17182. var BABYLON;
  17183. (function (BABYLON) {
  17184. var CustomProceduralTexture = (function (_super) {
  17185. __extends(CustomProceduralTexture, _super);
  17186. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17187. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17188. this._animate = true;
  17189. this._time = 0;
  17190. this._texturePath = texturePath;
  17191. //Try to load json
  17192. this.loadJson(texturePath);
  17193. this.refreshRate = 1;
  17194. }
  17195. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17196. var _this = this;
  17197. var that = this;
  17198. function noConfigFile() {
  17199. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17200. try {
  17201. that.setFragment(that._texturePath);
  17202. }
  17203. catch (ex) {
  17204. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17205. }
  17206. }
  17207. var configFileUrl = jsonUrl + "/config.json";
  17208. var xhr = new XMLHttpRequest();
  17209. xhr.open("GET", configFileUrl, true);
  17210. xhr.addEventListener("load", function () {
  17211. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17212. try {
  17213. _this._config = JSON.parse(xhr.response);
  17214. _this.updateShaderUniforms();
  17215. _this.updateTextures();
  17216. _this.setFragment(_this._texturePath + "/custom");
  17217. _this._animate = _this._config.animate;
  17218. _this.refreshRate = _this._config.refreshrate;
  17219. }
  17220. catch (ex) {
  17221. noConfigFile();
  17222. }
  17223. }
  17224. else {
  17225. noConfigFile();
  17226. }
  17227. }, false);
  17228. xhr.addEventListener("error", function () {
  17229. noConfigFile();
  17230. }, false);
  17231. try {
  17232. xhr.send();
  17233. }
  17234. catch (ex) {
  17235. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17236. }
  17237. };
  17238. CustomProceduralTexture.prototype.isReady = function () {
  17239. if (!_super.prototype.isReady.call(this)) {
  17240. return false;
  17241. }
  17242. for (var name in this._textures) {
  17243. var texture = this._textures[name];
  17244. if (!texture.isReady()) {
  17245. return false;
  17246. }
  17247. }
  17248. return true;
  17249. };
  17250. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17251. if (this._animate) {
  17252. this._time += this.getScene().getAnimationRatio() * 0.03;
  17253. this.updateShaderUniforms();
  17254. }
  17255. _super.prototype.render.call(this, useCameraPostProcess);
  17256. };
  17257. CustomProceduralTexture.prototype.updateTextures = function () {
  17258. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17259. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17260. }
  17261. };
  17262. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17263. if (this._config) {
  17264. for (var j = 0; j < this._config.uniforms.length; j++) {
  17265. var uniform = this._config.uniforms[j];
  17266. switch (uniform.type) {
  17267. case "float":
  17268. this.setFloat(uniform.name, uniform.value);
  17269. break;
  17270. case "color3":
  17271. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17272. break;
  17273. case "color4":
  17274. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17275. break;
  17276. case "vector2":
  17277. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17278. break;
  17279. case "vector3":
  17280. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17281. break;
  17282. }
  17283. }
  17284. }
  17285. this.setFloat("time", this._time);
  17286. };
  17287. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17288. get: function () {
  17289. return this._animate;
  17290. },
  17291. set: function (value) {
  17292. this._animate = value;
  17293. },
  17294. enumerable: true,
  17295. configurable: true
  17296. });
  17297. return CustomProceduralTexture;
  17298. })(BABYLON.ProceduralTexture);
  17299. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17300. })(BABYLON || (BABYLON = {}));
  17301. var BABYLON;
  17302. (function (BABYLON) {
  17303. var WoodProceduralTexture = (function (_super) {
  17304. __extends(WoodProceduralTexture, _super);
  17305. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17306. _super.call(this, name, size, "woodtexture", scene, fallbackTexture, generateMipMaps);
  17307. this._ampScale = 100.0;
  17308. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17309. this.updateShaderUniforms();
  17310. this.refreshRate = 0;
  17311. }
  17312. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17313. this.setFloat("ampScale", this._ampScale);
  17314. this.setColor3("woodColor", this._woodColor);
  17315. };
  17316. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17317. get: function () {
  17318. return this._ampScale;
  17319. },
  17320. set: function (value) {
  17321. this._ampScale = value;
  17322. this.updateShaderUniforms();
  17323. },
  17324. enumerable: true,
  17325. configurable: true
  17326. });
  17327. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17328. get: function () {
  17329. return this._woodColor;
  17330. },
  17331. set: function (value) {
  17332. this._woodColor = value;
  17333. this.updateShaderUniforms();
  17334. },
  17335. enumerable: true,
  17336. configurable: true
  17337. });
  17338. return WoodProceduralTexture;
  17339. })(BABYLON.ProceduralTexture);
  17340. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17341. var FireProceduralTexture = (function (_super) {
  17342. __extends(FireProceduralTexture, _super);
  17343. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17344. _super.call(this, name, size, "firetexture", scene, fallbackTexture, generateMipMaps);
  17345. this._time = 0.0;
  17346. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17347. this._autoGenerateTime = true;
  17348. this._alphaThreshold = 0.5;
  17349. this._fireColors = FireProceduralTexture.RedFireColors;
  17350. this.updateShaderUniforms();
  17351. this.refreshRate = 1;
  17352. }
  17353. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17354. this.setFloat("time", this._time);
  17355. this.setVector2("speed", this._speed);
  17356. this.setColor3("c1", this._fireColors[0]);
  17357. this.setColor3("c2", this._fireColors[1]);
  17358. this.setColor3("c3", this._fireColors[2]);
  17359. this.setColor3("c4", this._fireColors[3]);
  17360. this.setColor3("c5", this._fireColors[4]);
  17361. this.setColor3("c6", this._fireColors[5]);
  17362. this.setFloat("alphaThreshold", this._alphaThreshold);
  17363. };
  17364. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17365. if (this._autoGenerateTime) {
  17366. this._time += this.getScene().getAnimationRatio() * 0.03;
  17367. this.updateShaderUniforms();
  17368. }
  17369. _super.prototype.render.call(this, useCameraPostProcess);
  17370. };
  17371. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17372. get: function () {
  17373. return [
  17374. new BABYLON.Color3(0.5, 0.0, 1.0),
  17375. new BABYLON.Color3(0.9, 0.0, 1.0),
  17376. new BABYLON.Color3(0.2, 0.0, 1.0),
  17377. new BABYLON.Color3(1.0, 0.9, 1.0),
  17378. new BABYLON.Color3(0.1, 0.1, 1.0),
  17379. new BABYLON.Color3(0.9, 0.9, 1.0)
  17380. ];
  17381. },
  17382. enumerable: true,
  17383. configurable: true
  17384. });
  17385. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17386. get: function () {
  17387. return [
  17388. new BABYLON.Color3(0.5, 1.0, 0.0),
  17389. new BABYLON.Color3(0.5, 1.0, 0.0),
  17390. new BABYLON.Color3(0.3, 0.4, 0.0),
  17391. new BABYLON.Color3(0.5, 1.0, 0.0),
  17392. new BABYLON.Color3(0.2, 0.0, 0.0),
  17393. new BABYLON.Color3(0.5, 1.0, 0.0)
  17394. ];
  17395. },
  17396. enumerable: true,
  17397. configurable: true
  17398. });
  17399. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17400. get: function () {
  17401. return [
  17402. new BABYLON.Color3(0.5, 0.0, 0.1),
  17403. new BABYLON.Color3(0.9, 0.0, 0.0),
  17404. new BABYLON.Color3(0.2, 0.0, 0.0),
  17405. new BABYLON.Color3(1.0, 0.9, 0.0),
  17406. new BABYLON.Color3(0.1, 0.1, 0.1),
  17407. new BABYLON.Color3(0.9, 0.9, 0.9)
  17408. ];
  17409. },
  17410. enumerable: true,
  17411. configurable: true
  17412. });
  17413. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17414. get: function () {
  17415. return [
  17416. new BABYLON.Color3(0.1, 0.0, 0.5),
  17417. new BABYLON.Color3(0.0, 0.0, 0.5),
  17418. new BABYLON.Color3(0.1, 0.0, 0.2),
  17419. new BABYLON.Color3(0.0, 0.0, 1.0),
  17420. new BABYLON.Color3(0.1, 0.2, 0.3),
  17421. new BABYLON.Color3(0.0, 0.2, 0.9)
  17422. ];
  17423. },
  17424. enumerable: true,
  17425. configurable: true
  17426. });
  17427. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17428. get: function () {
  17429. return this._fireColors;
  17430. },
  17431. set: function (value) {
  17432. this._fireColors = value;
  17433. this.updateShaderUniforms();
  17434. },
  17435. enumerable: true,
  17436. configurable: true
  17437. });
  17438. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17439. get: function () {
  17440. return this._time;
  17441. },
  17442. set: function (value) {
  17443. this._time = value;
  17444. this.updateShaderUniforms();
  17445. },
  17446. enumerable: true,
  17447. configurable: true
  17448. });
  17449. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17450. get: function () {
  17451. return this._speed;
  17452. },
  17453. set: function (value) {
  17454. this._speed = value;
  17455. this.updateShaderUniforms();
  17456. },
  17457. enumerable: true,
  17458. configurable: true
  17459. });
  17460. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17461. get: function () {
  17462. return this._alphaThreshold;
  17463. },
  17464. set: function (value) {
  17465. this._alphaThreshold = value;
  17466. this.updateShaderUniforms();
  17467. },
  17468. enumerable: true,
  17469. configurable: true
  17470. });
  17471. return FireProceduralTexture;
  17472. })(BABYLON.ProceduralTexture);
  17473. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17474. var CloudProceduralTexture = (function (_super) {
  17475. __extends(CloudProceduralTexture, _super);
  17476. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17477. _super.call(this, name, size, "cloudtexture", scene, fallbackTexture, generateMipMaps);
  17478. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17479. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17480. this.updateShaderUniforms();
  17481. this.refreshRate = 0;
  17482. }
  17483. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17484. this.setColor4("skyColor", this._skyColor);
  17485. this.setColor4("cloudColor", this._cloudColor);
  17486. };
  17487. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17488. get: function () {
  17489. return this._skyColor;
  17490. },
  17491. set: function (value) {
  17492. this._skyColor = value;
  17493. this.updateShaderUniforms();
  17494. },
  17495. enumerable: true,
  17496. configurable: true
  17497. });
  17498. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17499. get: function () {
  17500. return this._cloudColor;
  17501. },
  17502. set: function (value) {
  17503. this._cloudColor = value;
  17504. this.updateShaderUniforms();
  17505. },
  17506. enumerable: true,
  17507. configurable: true
  17508. });
  17509. return CloudProceduralTexture;
  17510. })(BABYLON.ProceduralTexture);
  17511. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17512. var GrassProceduralTexture = (function (_super) {
  17513. __extends(GrassProceduralTexture, _super);
  17514. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17515. _super.call(this, name, size, "grasstexture", scene, fallbackTexture, generateMipMaps);
  17516. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17517. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17518. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17519. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17520. this._grassColors = [
  17521. new BABYLON.Color3(0.29, 0.38, 0.02),
  17522. new BABYLON.Color3(0.36, 0.49, 0.09),
  17523. new BABYLON.Color3(0.51, 0.6, 0.28)
  17524. ];
  17525. this.updateShaderUniforms();
  17526. this.refreshRate = 0;
  17527. }
  17528. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17529. this.setColor3("herb1Color", this._grassColors[0]);
  17530. this.setColor3("herb2Color", this._grassColors[1]);
  17531. this.setColor3("herb3Color", this._grassColors[2]);
  17532. this.setColor3("groundColor", this._groundColor);
  17533. };
  17534. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17535. get: function () {
  17536. return this._grassColors;
  17537. },
  17538. set: function (value) {
  17539. this._grassColors = value;
  17540. this.updateShaderUniforms();
  17541. },
  17542. enumerable: true,
  17543. configurable: true
  17544. });
  17545. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17546. get: function () {
  17547. return this._groundColor;
  17548. },
  17549. set: function (value) {
  17550. this.groundColor = value;
  17551. this.updateShaderUniforms();
  17552. },
  17553. enumerable: true,
  17554. configurable: true
  17555. });
  17556. return GrassProceduralTexture;
  17557. })(BABYLON.ProceduralTexture);
  17558. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17559. var RoadProceduralTexture = (function (_super) {
  17560. __extends(RoadProceduralTexture, _super);
  17561. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17562. _super.call(this, name, size, "roadtexture", scene, fallbackTexture, generateMipMaps);
  17563. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17564. this.updateShaderUniforms();
  17565. this.refreshRate = 0;
  17566. }
  17567. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17568. this.setColor3("roadColor", this._roadColor);
  17569. };
  17570. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17571. get: function () {
  17572. return this._roadColor;
  17573. },
  17574. set: function (value) {
  17575. this._roadColor = value;
  17576. this.updateShaderUniforms();
  17577. },
  17578. enumerable: true,
  17579. configurable: true
  17580. });
  17581. return RoadProceduralTexture;
  17582. })(BABYLON.ProceduralTexture);
  17583. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17584. var BrickProceduralTexture = (function (_super) {
  17585. __extends(BrickProceduralTexture, _super);
  17586. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17587. _super.call(this, name, size, "bricktexture", scene, fallbackTexture, generateMipMaps);
  17588. this._numberOfBricksHeight = 15;
  17589. this._numberOfBricksWidth = 5;
  17590. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17591. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17592. this.updateShaderUniforms();
  17593. this.refreshRate = 0;
  17594. }
  17595. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17596. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17597. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17598. this.setColor3("brickColor", this._brickColor);
  17599. this.setColor3("jointColor", this._jointColor);
  17600. };
  17601. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17602. get: function () {
  17603. return this._numberOfBricksHeight;
  17604. },
  17605. set: function (value) {
  17606. this._numberOfBricksHeight = value;
  17607. this.updateShaderUniforms();
  17608. },
  17609. enumerable: true,
  17610. configurable: true
  17611. });
  17612. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17613. get: function () {
  17614. return this._numberOfBricksWidth;
  17615. },
  17616. set: function (value) {
  17617. this._numberOfBricksWidth = value;
  17618. this.updateShaderUniforms();
  17619. },
  17620. enumerable: true,
  17621. configurable: true
  17622. });
  17623. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17624. get: function () {
  17625. return this._jointColor;
  17626. },
  17627. set: function (value) {
  17628. this._jointColor = value;
  17629. this.updateShaderUniforms();
  17630. },
  17631. enumerable: true,
  17632. configurable: true
  17633. });
  17634. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17635. get: function () {
  17636. return this._brickColor;
  17637. },
  17638. set: function (value) {
  17639. this._brickColor = value;
  17640. this.updateShaderUniforms();
  17641. },
  17642. enumerable: true,
  17643. configurable: true
  17644. });
  17645. return BrickProceduralTexture;
  17646. })(BABYLON.ProceduralTexture);
  17647. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17648. var MarbleProceduralTexture = (function (_super) {
  17649. __extends(MarbleProceduralTexture, _super);
  17650. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17651. _super.call(this, name, size, "marbletexture", scene, fallbackTexture, generateMipMaps);
  17652. this._numberOfTilesHeight = 3;
  17653. this._numberOfTilesWidth = 3;
  17654. this._amplitude = 9.0;
  17655. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17656. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17657. this.updateShaderUniforms();
  17658. this.refreshRate = 0;
  17659. }
  17660. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17661. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17662. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17663. this.setFloat("amplitude", this._amplitude);
  17664. this.setColor3("marbleColor", this._marbleColor);
  17665. this.setColor3("jointColor", this._jointColor);
  17666. };
  17667. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17668. get: function () {
  17669. return this._numberOfTilesHeight;
  17670. },
  17671. set: function (value) {
  17672. this._numberOfTilesHeight = value;
  17673. this.updateShaderUniforms();
  17674. },
  17675. enumerable: true,
  17676. configurable: true
  17677. });
  17678. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17679. get: function () {
  17680. return this._numberOfTilesWidth;
  17681. },
  17682. set: function (value) {
  17683. this._numberOfTilesWidth = value;
  17684. this.updateShaderUniforms();
  17685. },
  17686. enumerable: true,
  17687. configurable: true
  17688. });
  17689. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17690. get: function () {
  17691. return this._jointColor;
  17692. },
  17693. set: function (value) {
  17694. this._jointColor = value;
  17695. this.updateShaderUniforms();
  17696. },
  17697. enumerable: true,
  17698. configurable: true
  17699. });
  17700. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17701. get: function () {
  17702. return this._marbleColor;
  17703. },
  17704. set: function (value) {
  17705. this._marbleColor = value;
  17706. this.updateShaderUniforms();
  17707. },
  17708. enumerable: true,
  17709. configurable: true
  17710. });
  17711. return MarbleProceduralTexture;
  17712. })(BABYLON.ProceduralTexture);
  17713. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17714. })(BABYLON || (BABYLON = {}));
  17715. var BABYLON;
  17716. (function (BABYLON) {
  17717. var EffectFallbacks = (function () {
  17718. function EffectFallbacks() {
  17719. this._defines = {};
  17720. this._currentRank = 32;
  17721. this._maxRank = -1;
  17722. }
  17723. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17724. if (!this._defines[rank]) {
  17725. if (rank < this._currentRank) {
  17726. this._currentRank = rank;
  17727. }
  17728. if (rank > this._maxRank) {
  17729. this._maxRank = rank;
  17730. }
  17731. this._defines[rank] = new Array();
  17732. }
  17733. this._defines[rank].push(define);
  17734. };
  17735. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  17736. this._meshRank = rank;
  17737. this._mesh = mesh;
  17738. if (rank > this._maxRank) {
  17739. this._maxRank = rank;
  17740. }
  17741. };
  17742. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17743. get: function () {
  17744. return this._currentRank <= this._maxRank;
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17750. var currentFallbacks = this._defines[this._currentRank];
  17751. for (var index = 0; index < currentFallbacks.length; index++) {
  17752. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17753. }
  17754. if (this._mesh && this._currentRank === this._meshRank) {
  17755. this._mesh.computeBonesUsingShaders = false;
  17756. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  17757. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  17758. }
  17759. this._currentRank++;
  17760. return currentDefines;
  17761. };
  17762. return EffectFallbacks;
  17763. })();
  17764. BABYLON.EffectFallbacks = EffectFallbacks;
  17765. var Effect = (function () {
  17766. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17767. var _this = this;
  17768. this._isReady = false;
  17769. this._compilationError = "";
  17770. this._valueCache = [];
  17771. this._engine = engine;
  17772. this.name = baseName;
  17773. this.defines = defines;
  17774. this._uniformsNames = uniformsNames.concat(samplers);
  17775. this._samplers = samplers;
  17776. this._attributesNames = attributesNames;
  17777. this.onError = onError;
  17778. this.onCompiled = onCompiled;
  17779. var vertexSource;
  17780. var fragmentSource;
  17781. if (baseName.vertexElement) {
  17782. vertexSource = document.getElementById(baseName.vertexElement);
  17783. if (!vertexSource) {
  17784. vertexSource = baseName.vertexElement;
  17785. }
  17786. }
  17787. else {
  17788. vertexSource = baseName.vertex || baseName;
  17789. }
  17790. if (baseName.fragmentElement) {
  17791. fragmentSource = document.getElementById(baseName.fragmentElement);
  17792. if (!fragmentSource) {
  17793. fragmentSource = baseName.fragmentElement;
  17794. }
  17795. }
  17796. else {
  17797. fragmentSource = baseName.fragment || baseName;
  17798. }
  17799. this._loadVertexShader(vertexSource, function (vertexCode) {
  17800. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17801. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17802. });
  17803. });
  17804. }
  17805. // Properties
  17806. Effect.prototype.isReady = function () {
  17807. return this._isReady;
  17808. };
  17809. Effect.prototype.getProgram = function () {
  17810. return this._program;
  17811. };
  17812. Effect.prototype.getAttributesNames = function () {
  17813. return this._attributesNames;
  17814. };
  17815. Effect.prototype.getAttributeLocation = function (index) {
  17816. return this._attributes[index];
  17817. };
  17818. Effect.prototype.getAttributeLocationByName = function (name) {
  17819. var index = this._attributesNames.indexOf(name);
  17820. return this._attributes[index];
  17821. };
  17822. Effect.prototype.getAttributesCount = function () {
  17823. return this._attributes.length;
  17824. };
  17825. Effect.prototype.getUniformIndex = function (uniformName) {
  17826. return this._uniformsNames.indexOf(uniformName);
  17827. };
  17828. Effect.prototype.getUniform = function (uniformName) {
  17829. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17830. };
  17831. Effect.prototype.getSamplers = function () {
  17832. return this._samplers;
  17833. };
  17834. Effect.prototype.getCompilationError = function () {
  17835. return this._compilationError;
  17836. };
  17837. // Methods
  17838. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17839. // DOM element ?
  17840. if (vertex instanceof HTMLElement) {
  17841. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17842. callback(vertexCode);
  17843. return;
  17844. }
  17845. // Is in local store ?
  17846. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17847. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17848. return;
  17849. }
  17850. var vertexShaderUrl;
  17851. if (vertex[0] === "." || vertex[0] === "/") {
  17852. vertexShaderUrl = vertex;
  17853. }
  17854. else {
  17855. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17856. }
  17857. // Vertex shader
  17858. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17859. };
  17860. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17861. // DOM element ?
  17862. if (fragment instanceof HTMLElement) {
  17863. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17864. callback(fragmentCode);
  17865. return;
  17866. }
  17867. // Is in local store ?
  17868. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17869. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17870. return;
  17871. }
  17872. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17873. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17874. return;
  17875. }
  17876. var fragmentShaderUrl;
  17877. if (fragment[0] === "." || fragment[0] === "/") {
  17878. fragmentShaderUrl = fragment;
  17879. }
  17880. else {
  17881. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17882. }
  17883. // Fragment shader
  17884. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17885. };
  17886. Effect.prototype._dumpShadersName = function () {
  17887. if (this.name.vertexElement) {
  17888. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17889. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17890. }
  17891. else if (this.name.vertex) {
  17892. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17893. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17894. }
  17895. else {
  17896. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17897. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17898. }
  17899. };
  17900. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17901. try {
  17902. var engine = this._engine;
  17903. if (!engine.getCaps().highPrecisionShaderSupported) {
  17904. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17905. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17906. }
  17907. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17908. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17909. this._attributes = engine.getAttributes(this._program, attributesNames);
  17910. for (var index = 0; index < this._samplers.length; index++) {
  17911. var sampler = this.getUniform(this._samplers[index]);
  17912. if (sampler == null) {
  17913. this._samplers.splice(index, 1);
  17914. index--;
  17915. }
  17916. }
  17917. engine.bindSamplers(this);
  17918. this._isReady = true;
  17919. if (this.onCompiled) {
  17920. this.onCompiled(this);
  17921. }
  17922. }
  17923. catch (e) {
  17924. // Is it a problem with precision?
  17925. if (e.message.indexOf("highp") !== -1) {
  17926. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17927. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17928. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17929. return;
  17930. }
  17931. // Let's go through fallbacks then
  17932. if (fallbacks && fallbacks.isMoreFallbacks) {
  17933. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  17934. this._dumpShadersName();
  17935. defines = fallbacks.reduce(defines);
  17936. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17937. }
  17938. else {
  17939. BABYLON.Tools.Error("Unable to compile effect: ");
  17940. this._dumpShadersName();
  17941. BABYLON.Tools.Error("Defines: " + defines);
  17942. BABYLON.Tools.Error("Error: " + e.message);
  17943. this._compilationError = e.message;
  17944. if (this.onError) {
  17945. this.onError(this, this._compilationError);
  17946. }
  17947. }
  17948. }
  17949. };
  17950. Object.defineProperty(Effect.prototype, "isSupported", {
  17951. get: function () {
  17952. return this._compilationError === "";
  17953. },
  17954. enumerable: true,
  17955. configurable: true
  17956. });
  17957. Effect.prototype._bindTexture = function (channel, texture) {
  17958. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17959. };
  17960. Effect.prototype.setTexture = function (channel, texture) {
  17961. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17962. };
  17963. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17964. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17965. };
  17966. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  17967. if (!this._valueCache[uniformName]) {
  17968. this._valueCache[uniformName] = new BABYLON.Matrix();
  17969. }
  17970. for (var index = 0; index < 16; index++) {
  17971. this._valueCache[uniformName].m[index] = matrix.m[index];
  17972. }
  17973. };
  17974. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17975. if (!this._valueCache[uniformName]) {
  17976. this._valueCache[uniformName] = [x, y];
  17977. return;
  17978. }
  17979. this._valueCache[uniformName][0] = x;
  17980. this._valueCache[uniformName][1] = y;
  17981. };
  17982. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17983. if (!this._valueCache[uniformName]) {
  17984. this._valueCache[uniformName] = [x, y, z];
  17985. return;
  17986. }
  17987. this._valueCache[uniformName][0] = x;
  17988. this._valueCache[uniformName][1] = y;
  17989. this._valueCache[uniformName][2] = z;
  17990. };
  17991. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17992. if (!this._valueCache[uniformName]) {
  17993. this._valueCache[uniformName] = [x, y, z, w];
  17994. return;
  17995. }
  17996. this._valueCache[uniformName][0] = x;
  17997. this._valueCache[uniformName][1] = y;
  17998. this._valueCache[uniformName][2] = z;
  17999. this._valueCache[uniformName][3] = w;
  18000. };
  18001. Effect.prototype.setArray = function (uniformName, array) {
  18002. this._engine.setArray(this.getUniform(uniformName), array);
  18003. return this;
  18004. };
  18005. Effect.prototype.setArray2 = function (uniformName, array) {
  18006. this._engine.setArray2(this.getUniform(uniformName), array);
  18007. return this;
  18008. };
  18009. Effect.prototype.setArray3 = function (uniformName, array) {
  18010. this._engine.setArray3(this.getUniform(uniformName), array);
  18011. return this;
  18012. };
  18013. Effect.prototype.setArray4 = function (uniformName, array) {
  18014. this._engine.setArray4(this.getUniform(uniformName), array);
  18015. return this;
  18016. };
  18017. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18018. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18019. return this;
  18020. };
  18021. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18022. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18023. return this;
  18024. this._cacheMatrix(uniformName, matrix);
  18025. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18026. return this;
  18027. };
  18028. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18029. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18030. return this;
  18031. };
  18032. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18033. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18034. return this;
  18035. };
  18036. Effect.prototype.setFloat = function (uniformName, value) {
  18037. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18038. return this;
  18039. this._valueCache[uniformName] = value;
  18040. this._engine.setFloat(this.getUniform(uniformName), value);
  18041. return this;
  18042. };
  18043. Effect.prototype.setBool = function (uniformName, bool) {
  18044. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18045. return this;
  18046. this._valueCache[uniformName] = bool;
  18047. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18048. return this;
  18049. };
  18050. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18051. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18052. return this;
  18053. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18054. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18055. return this;
  18056. };
  18057. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18058. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18059. return this;
  18060. this._cacheFloat2(uniformName, x, y);
  18061. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18062. return this;
  18063. };
  18064. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18065. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18066. return this;
  18067. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18068. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18069. return this;
  18070. };
  18071. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18072. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18073. return this;
  18074. this._cacheFloat3(uniformName, x, y, z);
  18075. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18076. return this;
  18077. };
  18078. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18079. 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)
  18080. return this;
  18081. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18082. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18083. return this;
  18084. };
  18085. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18086. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18087. return this;
  18088. this._cacheFloat4(uniformName, x, y, z, w);
  18089. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18090. return this;
  18091. };
  18092. Effect.prototype.setColor3 = function (uniformName, color3) {
  18093. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18094. return this;
  18095. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18096. this._engine.setColor3(this.getUniform(uniformName), color3);
  18097. return this;
  18098. };
  18099. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18100. 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)
  18101. return this;
  18102. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18103. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18104. return this;
  18105. };
  18106. // Statics
  18107. Effect.ShadersStore = {};
  18108. return Effect;
  18109. })();
  18110. BABYLON.Effect = Effect;
  18111. })(BABYLON || (BABYLON = {}));
  18112. var BABYLON;
  18113. (function (BABYLON) {
  18114. var MaterialDefines = (function () {
  18115. function MaterialDefines() {
  18116. }
  18117. MaterialDefines.prototype.isEqual = function (other) {
  18118. for (var index = 0; index < this._keys.length; index++) {
  18119. var prop = this._keys[index];
  18120. if (this[prop] !== other[prop]) {
  18121. return false;
  18122. }
  18123. }
  18124. return true;
  18125. };
  18126. MaterialDefines.prototype.cloneTo = function (other) {
  18127. for (var index = 0; index < this._keys.length; index++) {
  18128. var prop = this._keys[index];
  18129. other[prop] = this[prop];
  18130. }
  18131. };
  18132. MaterialDefines.prototype.reset = function () {
  18133. for (var index = 0; index < this._keys.length; index++) {
  18134. var prop = this._keys[index];
  18135. if (typeof (this[prop]) === "number") {
  18136. this[prop] = 0;
  18137. }
  18138. else {
  18139. this[prop] = false;
  18140. }
  18141. }
  18142. };
  18143. MaterialDefines.prototype.toString = function () {
  18144. var result = "";
  18145. for (var index = 0; index < this._keys.length; index++) {
  18146. var prop = this._keys[index];
  18147. if (typeof (this[prop]) === "number") {
  18148. result += "#define " + prop + " " + this[prop] + "\n";
  18149. }
  18150. else if (this[prop]) {
  18151. result += "#define " + prop + "\n";
  18152. }
  18153. }
  18154. return result;
  18155. };
  18156. return MaterialDefines;
  18157. })();
  18158. BABYLON.MaterialDefines = MaterialDefines;
  18159. var Material = (function () {
  18160. function Material(name, scene, doNotAdd) {
  18161. this.name = name;
  18162. this.checkReadyOnEveryCall = false;
  18163. this.checkReadyOnlyOnce = false;
  18164. this.state = "";
  18165. this.alpha = 1.0;
  18166. this.backFaceCulling = true;
  18167. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18168. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18169. this.disableDepthWrite = false;
  18170. this.fogEnabled = true;
  18171. this._wasPreviouslyReady = false;
  18172. this._fillMode = Material.TriangleFillMode;
  18173. this.pointSize = 1.0;
  18174. this.zOffset = 0;
  18175. this.id = name;
  18176. this._scene = scene;
  18177. if (!doNotAdd) {
  18178. scene.materials.push(this);
  18179. }
  18180. }
  18181. Object.defineProperty(Material, "TriangleFillMode", {
  18182. get: function () {
  18183. return Material._TriangleFillMode;
  18184. },
  18185. enumerable: true,
  18186. configurable: true
  18187. });
  18188. Object.defineProperty(Material, "WireFrameFillMode", {
  18189. get: function () {
  18190. return Material._WireFrameFillMode;
  18191. },
  18192. enumerable: true,
  18193. configurable: true
  18194. });
  18195. Object.defineProperty(Material, "PointFillMode", {
  18196. get: function () {
  18197. return Material._PointFillMode;
  18198. },
  18199. enumerable: true,
  18200. configurable: true
  18201. });
  18202. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18203. get: function () {
  18204. return Material._ClockWiseSideOrientation;
  18205. },
  18206. enumerable: true,
  18207. configurable: true
  18208. });
  18209. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18210. get: function () {
  18211. return Material._CounterClockWiseSideOrientation;
  18212. },
  18213. enumerable: true,
  18214. configurable: true
  18215. });
  18216. Object.defineProperty(Material.prototype, "wireframe", {
  18217. get: function () {
  18218. return this._fillMode === Material.WireFrameFillMode;
  18219. },
  18220. set: function (value) {
  18221. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18222. },
  18223. enumerable: true,
  18224. configurable: true
  18225. });
  18226. Object.defineProperty(Material.prototype, "pointsCloud", {
  18227. get: function () {
  18228. return this._fillMode === Material.PointFillMode;
  18229. },
  18230. set: function (value) {
  18231. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18232. },
  18233. enumerable: true,
  18234. configurable: true
  18235. });
  18236. Object.defineProperty(Material.prototype, "fillMode", {
  18237. get: function () {
  18238. return this._fillMode;
  18239. },
  18240. set: function (value) {
  18241. this._fillMode = value;
  18242. },
  18243. enumerable: true,
  18244. configurable: true
  18245. });
  18246. Material.prototype.isReady = function (mesh, useInstances) {
  18247. return true;
  18248. };
  18249. Material.prototype.getEffect = function () {
  18250. return this._effect;
  18251. };
  18252. Material.prototype.getScene = function () {
  18253. return this._scene;
  18254. };
  18255. Material.prototype.needAlphaBlending = function () {
  18256. return (this.alpha < 1.0);
  18257. };
  18258. Material.prototype.needAlphaTesting = function () {
  18259. return false;
  18260. };
  18261. Material.prototype.getAlphaTestTexture = function () {
  18262. return null;
  18263. };
  18264. Material.prototype.trackCreation = function (onCompiled, onError) {
  18265. };
  18266. Material.prototype.markDirty = function () {
  18267. this._wasPreviouslyReady = false;
  18268. };
  18269. Material.prototype._preBind = function () {
  18270. var engine = this._scene.getEngine();
  18271. engine.enableEffect(this._effect);
  18272. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18273. };
  18274. Material.prototype.bind = function (world, mesh) {
  18275. this._scene._cachedMaterial = this;
  18276. if (this.onBind) {
  18277. this.onBind(this, mesh);
  18278. }
  18279. if (this.disableDepthWrite) {
  18280. var engine = this._scene.getEngine();
  18281. this._cachedDepthWriteState = engine.getDepthWrite();
  18282. engine.setDepthWrite(false);
  18283. }
  18284. };
  18285. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18286. };
  18287. Material.prototype.unbind = function () {
  18288. if (this.disableDepthWrite) {
  18289. var engine = this._scene.getEngine();
  18290. engine.setDepthWrite(this._cachedDepthWriteState);
  18291. }
  18292. };
  18293. Material.prototype.clone = function (name) {
  18294. return null;
  18295. };
  18296. Material.prototype.getBindedMeshes = function () {
  18297. var result = new Array();
  18298. for (var index = 0; index < this._scene.meshes.length; index++) {
  18299. var mesh = this._scene.meshes[index];
  18300. if (mesh.material === this) {
  18301. result.push(mesh);
  18302. }
  18303. }
  18304. return result;
  18305. };
  18306. Material.prototype.dispose = function (forceDisposeEffect) {
  18307. // Animations
  18308. this.getScene().stopAnimation(this);
  18309. // Remove from scene
  18310. var index = this._scene.materials.indexOf(this);
  18311. if (index >= 0) {
  18312. this._scene.materials.splice(index, 1);
  18313. }
  18314. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18315. if (forceDisposeEffect && this._effect) {
  18316. this._scene.getEngine()._releaseEffect(this._effect);
  18317. this._effect = null;
  18318. }
  18319. // Remove from meshes
  18320. for (index = 0; index < this._scene.meshes.length; index++) {
  18321. var mesh = this._scene.meshes[index];
  18322. if (mesh.material === this) {
  18323. mesh.material = null;
  18324. }
  18325. }
  18326. // Callback
  18327. if (this.onDispose) {
  18328. this.onDispose();
  18329. }
  18330. };
  18331. Material.prototype.copyTo = function (other) {
  18332. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18333. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18334. other.alpha = this.alpha;
  18335. other.fillMode = this.fillMode;
  18336. other.backFaceCulling = this.backFaceCulling;
  18337. other.fogEnabled = this.fogEnabled;
  18338. other.wireframe = this.wireframe;
  18339. other.zOffset = this.zOffset;
  18340. other.alphaMode = this.alphaMode;
  18341. other.sideOrientation = this.sideOrientation;
  18342. other.disableDepthWrite = this.disableDepthWrite;
  18343. other.pointSize = this.pointSize;
  18344. other.pointsCloud = this.pointsCloud;
  18345. };
  18346. Material._TriangleFillMode = 0;
  18347. Material._WireFrameFillMode = 1;
  18348. Material._PointFillMode = 2;
  18349. Material._ClockWiseSideOrientation = 0;
  18350. Material._CounterClockWiseSideOrientation = 1;
  18351. return Material;
  18352. })();
  18353. BABYLON.Material = Material;
  18354. })(BABYLON || (BABYLON = {}));
  18355. var BABYLON;
  18356. (function (BABYLON) {
  18357. var maxSimultaneousLights = 4;
  18358. var FresnelParameters = (function () {
  18359. function FresnelParameters() {
  18360. this.isEnabled = true;
  18361. this.leftColor = BABYLON.Color3.White();
  18362. this.rightColor = BABYLON.Color3.Black();
  18363. this.bias = 0;
  18364. this.power = 1;
  18365. }
  18366. FresnelParameters.prototype.clone = function () {
  18367. var newFresnelParameters = new FresnelParameters();
  18368. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18369. return new FresnelParameters;
  18370. };
  18371. return FresnelParameters;
  18372. })();
  18373. BABYLON.FresnelParameters = FresnelParameters;
  18374. var StandardMaterialDefines = (function (_super) {
  18375. __extends(StandardMaterialDefines, _super);
  18376. function StandardMaterialDefines() {
  18377. _super.call(this);
  18378. this.DIFFUSE = false;
  18379. this.AMBIENT = false;
  18380. this.OPACITY = false;
  18381. this.OPACITYRGB = false;
  18382. this.REFLECTION = false;
  18383. this.EMISSIVE = false;
  18384. this.SPECULAR = false;
  18385. this.BUMP = false;
  18386. this.SPECULAROVERALPHA = false;
  18387. this.CLIPPLANE = false;
  18388. this.ALPHATEST = false;
  18389. this.ALPHAFROMDIFFUSE = false;
  18390. this.POINTSIZE = false;
  18391. this.FOG = false;
  18392. this.LIGHT0 = false;
  18393. this.LIGHT1 = false;
  18394. this.LIGHT2 = false;
  18395. this.LIGHT3 = false;
  18396. this.SPOTLIGHT0 = false;
  18397. this.SPOTLIGHT1 = false;
  18398. this.SPOTLIGHT2 = false;
  18399. this.SPOTLIGHT3 = false;
  18400. this.HEMILIGHT0 = false;
  18401. this.HEMILIGHT1 = false;
  18402. this.HEMILIGHT2 = false;
  18403. this.HEMILIGHT3 = false;
  18404. this.POINTLIGHT0 = false;
  18405. this.POINTLIGHT1 = false;
  18406. this.POINTLIGHT2 = false;
  18407. this.POINTLIGHT3 = false;
  18408. this.DIRLIGHT0 = false;
  18409. this.DIRLIGHT1 = false;
  18410. this.DIRLIGHT2 = false;
  18411. this.DIRLIGHT3 = false;
  18412. this.SPECULARTERM = false;
  18413. this.SHADOW0 = false;
  18414. this.SHADOW1 = false;
  18415. this.SHADOW2 = false;
  18416. this.SHADOW3 = false;
  18417. this.SHADOWS = false;
  18418. this.SHADOWVSM0 = false;
  18419. this.SHADOWVSM1 = false;
  18420. this.SHADOWVSM2 = false;
  18421. this.SHADOWVSM3 = false;
  18422. this.SHADOWPCF0 = false;
  18423. this.SHADOWPCF1 = false;
  18424. this.SHADOWPCF2 = false;
  18425. this.SHADOWPCF3 = false;
  18426. this.DIFFUSEFRESNEL = false;
  18427. this.OPACITYFRESNEL = false;
  18428. this.REFLECTIONFRESNEL = false;
  18429. this.EMISSIVEFRESNEL = false;
  18430. this.FRESNEL = false;
  18431. this.NORMAL = false;
  18432. this.UV1 = false;
  18433. this.UV2 = false;
  18434. this.VERTEXCOLOR = false;
  18435. this.VERTEXALPHA = false;
  18436. this.NUM_BONE_INFLUENCERS = 0;
  18437. this.BonesPerMesh = 0;
  18438. this.INSTANCES = false;
  18439. this.GLOSSINESS = false;
  18440. this.ROUGHNESS = false;
  18441. this.EMISSIVEASILLUMINATION = false;
  18442. this.LINKEMISSIVEWITHDIFFUSE = false;
  18443. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18444. this.LIGHTMAP = false;
  18445. this.USELIGHTMAPASSHADOWMAP = false;
  18446. this.REFLECTIONMAP_3D = false;
  18447. this.REFLECTIONMAP_SPHERICAL = false;
  18448. this.REFLECTIONMAP_PLANAR = false;
  18449. this.REFLECTIONMAP_CUBIC = false;
  18450. this.REFLECTIONMAP_PROJECTION = false;
  18451. this.REFLECTIONMAP_SKYBOX = false;
  18452. this.REFLECTIONMAP_EXPLICIT = false;
  18453. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18454. this.INVERTCUBICMAP = false;
  18455. this.LOGARITHMICDEPTH = false;
  18456. this._keys = Object.keys(this);
  18457. }
  18458. return StandardMaterialDefines;
  18459. })(BABYLON.MaterialDefines);
  18460. var StandardMaterial = (function (_super) {
  18461. __extends(StandardMaterial, _super);
  18462. function StandardMaterial(name, scene) {
  18463. var _this = this;
  18464. _super.call(this, name, scene);
  18465. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18466. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18467. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18468. this.specularPower = 64;
  18469. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18470. this.useAlphaFromDiffuseTexture = false;
  18471. this.useEmissiveAsIllumination = false;
  18472. this.linkEmissiveWithDiffuse = false;
  18473. this.useReflectionFresnelFromSpecular = false;
  18474. this.useSpecularOverAlpha = true;
  18475. this.disableLighting = false;
  18476. this.roughness = 0;
  18477. this.useLightmapAsShadowmap = false;
  18478. this.useGlossinessFromSpecularMapAlpha = false;
  18479. this._renderTargets = new BABYLON.SmartArray(16);
  18480. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18481. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18482. this._defines = new StandardMaterialDefines();
  18483. this._cachedDefines = new StandardMaterialDefines();
  18484. this._cachedDefines.BonesPerMesh = -1;
  18485. this.getRenderTargetTextures = function () {
  18486. _this._renderTargets.reset();
  18487. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18488. _this._renderTargets.push(_this.reflectionTexture);
  18489. }
  18490. return _this._renderTargets;
  18491. };
  18492. }
  18493. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  18494. get: function () {
  18495. return this._useLogarithmicDepth;
  18496. },
  18497. set: function (value) {
  18498. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  18499. },
  18500. enumerable: true,
  18501. configurable: true
  18502. });
  18503. StandardMaterial.prototype.needAlphaBlending = function () {
  18504. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18505. };
  18506. StandardMaterial.prototype.needAlphaTesting = function () {
  18507. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18508. };
  18509. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18510. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18511. };
  18512. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18513. return this.diffuseTexture;
  18514. };
  18515. // Methods
  18516. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18517. if (!mesh) {
  18518. return true;
  18519. }
  18520. if (this._defines.INSTANCES !== useInstances) {
  18521. return false;
  18522. }
  18523. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18524. return true;
  18525. }
  18526. return false;
  18527. };
  18528. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  18529. var lightIndex = 0;
  18530. var needNormals = false;
  18531. for (var index = 0; index < scene.lights.length; index++) {
  18532. var light = scene.lights[index];
  18533. if (!light.isEnabled()) {
  18534. continue;
  18535. }
  18536. // Excluded check
  18537. if (light._excludedMeshesIds.length > 0) {
  18538. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18539. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18540. if (excludedMesh) {
  18541. light.excludedMeshes.push(excludedMesh);
  18542. }
  18543. }
  18544. light._excludedMeshesIds = [];
  18545. }
  18546. // Included check
  18547. if (light._includedOnlyMeshesIds.length > 0) {
  18548. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18549. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18550. if (includedOnlyMesh) {
  18551. light.includedOnlyMeshes.push(includedOnlyMesh);
  18552. }
  18553. }
  18554. light._includedOnlyMeshesIds = [];
  18555. }
  18556. if (!light.canAffectMesh(mesh)) {
  18557. continue;
  18558. }
  18559. needNormals = true;
  18560. defines["LIGHT" + lightIndex] = true;
  18561. var type;
  18562. if (light instanceof BABYLON.SpotLight) {
  18563. type = "SPOTLIGHT" + lightIndex;
  18564. }
  18565. else if (light instanceof BABYLON.HemisphericLight) {
  18566. type = "HEMILIGHT" + lightIndex;
  18567. }
  18568. else if (light instanceof BABYLON.PointLight) {
  18569. type = "POINTLIGHT" + lightIndex;
  18570. }
  18571. else {
  18572. type = "DIRLIGHT" + lightIndex;
  18573. }
  18574. defines[type] = true;
  18575. // Specular
  18576. if (!light.specular.equalsFloats(0, 0, 0)) {
  18577. defines["SPECULARTERM"] = true;
  18578. }
  18579. // Shadows
  18580. if (scene.shadowsEnabled) {
  18581. var shadowGenerator = light.getShadowGenerator();
  18582. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18583. defines["SHADOW" + lightIndex] = true;
  18584. defines["SHADOWS"] = true;
  18585. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18586. defines["SHADOWVSM" + lightIndex] = true;
  18587. }
  18588. if (shadowGenerator.usePoissonSampling) {
  18589. defines["SHADOWPCF" + lightIndex] = true;
  18590. }
  18591. }
  18592. }
  18593. lightIndex++;
  18594. if (lightIndex === maxSimultaneousLights)
  18595. break;
  18596. }
  18597. return needNormals;
  18598. };
  18599. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  18600. var lightIndex = 0;
  18601. for (var index = 0; index < scene.lights.length; index++) {
  18602. var light = scene.lights[index];
  18603. if (!light.isEnabled()) {
  18604. continue;
  18605. }
  18606. if (!light.canAffectMesh(mesh)) {
  18607. continue;
  18608. }
  18609. if (light instanceof BABYLON.PointLight) {
  18610. // Point Light
  18611. light.transferToEffect(effect, "vLightData" + lightIndex);
  18612. }
  18613. else if (light instanceof BABYLON.DirectionalLight) {
  18614. // Directional Light
  18615. light.transferToEffect(effect, "vLightData" + lightIndex);
  18616. }
  18617. else if (light instanceof BABYLON.SpotLight) {
  18618. // Spot Light
  18619. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18620. }
  18621. else if (light instanceof BABYLON.HemisphericLight) {
  18622. // Hemispheric Light
  18623. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18624. }
  18625. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  18626. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  18627. if (defines["SPECULARTERM"]) {
  18628. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  18629. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  18630. }
  18631. // Shadows
  18632. if (scene.shadowsEnabled) {
  18633. var shadowGenerator = light.getShadowGenerator();
  18634. if (mesh.receiveShadows && shadowGenerator) {
  18635. if (!light.needCube()) {
  18636. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18637. }
  18638. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18639. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18640. }
  18641. }
  18642. lightIndex++;
  18643. if (lightIndex === maxSimultaneousLights)
  18644. break;
  18645. }
  18646. };
  18647. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18648. if (this.checkReadyOnlyOnce) {
  18649. if (this._wasPreviouslyReady) {
  18650. return true;
  18651. }
  18652. }
  18653. var scene = this.getScene();
  18654. if (!this.checkReadyOnEveryCall) {
  18655. if (this._renderId === scene.getRenderId()) {
  18656. if (this._checkCache(scene, mesh, useInstances)) {
  18657. return true;
  18658. }
  18659. }
  18660. }
  18661. var engine = scene.getEngine();
  18662. var needNormals = false;
  18663. var needUVs = false;
  18664. this._defines.reset();
  18665. // Textures
  18666. if (scene.texturesEnabled) {
  18667. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18668. if (!this.diffuseTexture.isReady()) {
  18669. return false;
  18670. }
  18671. else {
  18672. needUVs = true;
  18673. this._defines.DIFFUSE = true;
  18674. }
  18675. }
  18676. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18677. if (!this.ambientTexture.isReady()) {
  18678. return false;
  18679. }
  18680. else {
  18681. needUVs = true;
  18682. this._defines.AMBIENT = true;
  18683. }
  18684. }
  18685. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18686. if (!this.opacityTexture.isReady()) {
  18687. return false;
  18688. }
  18689. else {
  18690. needUVs = true;
  18691. this._defines.OPACITY = true;
  18692. if (this.opacityTexture.getAlphaFromRGB) {
  18693. this._defines.OPACITYRGB = true;
  18694. }
  18695. }
  18696. }
  18697. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18698. if (!this.reflectionTexture.isReady()) {
  18699. return false;
  18700. }
  18701. else {
  18702. needNormals = true;
  18703. this._defines.REFLECTION = true;
  18704. if (this.roughness > 0) {
  18705. this._defines.ROUGHNESS = true;
  18706. }
  18707. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  18708. this._defines.INVERTCUBICMAP = true;
  18709. }
  18710. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  18711. switch (this.reflectionTexture.coordinatesMode) {
  18712. case BABYLON.Texture.CUBIC_MODE:
  18713. case BABYLON.Texture.INVCUBIC_MODE:
  18714. this._defines.REFLECTIONMAP_CUBIC = true;
  18715. break;
  18716. case BABYLON.Texture.EXPLICIT_MODE:
  18717. this._defines.REFLECTIONMAP_EXPLICIT = true;
  18718. break;
  18719. case BABYLON.Texture.PLANAR_MODE:
  18720. this._defines.REFLECTIONMAP_PLANAR = true;
  18721. break;
  18722. case BABYLON.Texture.PROJECTION_MODE:
  18723. this._defines.REFLECTIONMAP_PROJECTION = true;
  18724. break;
  18725. case BABYLON.Texture.SKYBOX_MODE:
  18726. this._defines.REFLECTIONMAP_SKYBOX = true;
  18727. break;
  18728. case BABYLON.Texture.SPHERICAL_MODE:
  18729. this._defines.REFLECTIONMAP_SPHERICAL = true;
  18730. break;
  18731. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  18732. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  18733. break;
  18734. }
  18735. }
  18736. }
  18737. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18738. if (!this.emissiveTexture.isReady()) {
  18739. return false;
  18740. }
  18741. else {
  18742. needUVs = true;
  18743. this._defines.EMISSIVE = true;
  18744. }
  18745. }
  18746. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18747. if (!this.lightmapTexture.isReady()) {
  18748. return false;
  18749. }
  18750. else {
  18751. needUVs = true;
  18752. this._defines.LIGHTMAP = true;
  18753. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  18754. }
  18755. }
  18756. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18757. if (!this.specularTexture.isReady()) {
  18758. return false;
  18759. }
  18760. else {
  18761. needUVs = true;
  18762. this._defines.SPECULAR = true;
  18763. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18764. }
  18765. }
  18766. }
  18767. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18768. if (!this.bumpTexture.isReady()) {
  18769. return false;
  18770. }
  18771. else {
  18772. needUVs = true;
  18773. this._defines.BUMP = true;
  18774. }
  18775. }
  18776. // Effect
  18777. if (scene.clipPlane) {
  18778. this._defines.CLIPPLANE = true;
  18779. }
  18780. if (engine.getAlphaTesting()) {
  18781. this._defines.ALPHATEST = true;
  18782. }
  18783. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18784. this._defines.ALPHAFROMDIFFUSE = true;
  18785. }
  18786. if (this.useEmissiveAsIllumination) {
  18787. this._defines.EMISSIVEASILLUMINATION = true;
  18788. }
  18789. if (this.linkEmissiveWithDiffuse) {
  18790. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  18791. }
  18792. if (this.useReflectionFresnelFromSpecular) {
  18793. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18794. }
  18795. if (this.useLogarithmicDepth) {
  18796. this._defines.LOGARITHMICDEPTH = true;
  18797. }
  18798. // Point size
  18799. if (this.pointsCloud || scene.forcePointsCloud) {
  18800. this._defines.POINTSIZE = true;
  18801. }
  18802. // Fog
  18803. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18804. this._defines.FOG = true;
  18805. }
  18806. if (scene.lightsEnabled && !this.disableLighting) {
  18807. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  18808. }
  18809. if (StandardMaterial.FresnelEnabled) {
  18810. // Fresnel
  18811. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18812. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18813. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18814. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18815. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18816. this._defines.DIFFUSEFRESNEL = true;
  18817. }
  18818. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18819. this._defines.OPACITYFRESNEL = true;
  18820. }
  18821. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18822. this._defines.REFLECTIONFRESNEL = true;
  18823. }
  18824. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18825. this._defines.EMISSIVEFRESNEL = true;
  18826. }
  18827. needNormals = true;
  18828. this._defines.FRESNEL = true;
  18829. }
  18830. }
  18831. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18832. this._defines.SPECULAROVERALPHA = true;
  18833. }
  18834. // Attribs
  18835. if (mesh) {
  18836. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18837. this._defines.NORMAL = true;
  18838. }
  18839. if (needUVs) {
  18840. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18841. this._defines.UV1 = true;
  18842. }
  18843. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18844. this._defines.UV2 = true;
  18845. }
  18846. }
  18847. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18848. this._defines.VERTEXCOLOR = true;
  18849. if (mesh.hasVertexAlpha) {
  18850. this._defines.VERTEXALPHA = true;
  18851. }
  18852. }
  18853. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18854. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  18855. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18856. }
  18857. // Instances
  18858. if (useInstances) {
  18859. this._defines.INSTANCES = true;
  18860. }
  18861. }
  18862. // Get correct effect
  18863. if (!this._defines.isEqual(this._cachedDefines)) {
  18864. this._defines.cloneTo(this._cachedDefines);
  18865. scene.resetCachedMaterial();
  18866. // Fallbacks
  18867. var fallbacks = new BABYLON.EffectFallbacks();
  18868. if (this._defines.REFLECTION) {
  18869. fallbacks.addFallback(0, "REFLECTION");
  18870. }
  18871. if (this._defines.SPECULAR) {
  18872. fallbacks.addFallback(0, "SPECULAR");
  18873. }
  18874. if (this._defines.BUMP) {
  18875. fallbacks.addFallback(0, "BUMP");
  18876. }
  18877. if (this._defines.SPECULAROVERALPHA) {
  18878. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18879. }
  18880. if (this._defines.FOG) {
  18881. fallbacks.addFallback(1, "FOG");
  18882. }
  18883. if (this._defines.POINTSIZE) {
  18884. fallbacks.addFallback(0, "POINTSIZE");
  18885. }
  18886. if (this._defines.LOGARITHMICDEPTH) {
  18887. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  18888. }
  18889. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18890. if (!this._defines["LIGHT" + lightIndex]) {
  18891. continue;
  18892. }
  18893. if (lightIndex > 0) {
  18894. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18895. }
  18896. if (this._defines["SHADOW" + lightIndex]) {
  18897. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18898. }
  18899. if (this._defines["SHADOWPCF" + lightIndex]) {
  18900. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18901. }
  18902. if (this._defines["SHADOWVSM" + lightIndex]) {
  18903. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18904. }
  18905. }
  18906. if (this._defines.SPECULARTERM) {
  18907. fallbacks.addFallback(0, "SPECULARTERM");
  18908. }
  18909. if (this._defines.DIFFUSEFRESNEL) {
  18910. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18911. }
  18912. if (this._defines.OPACITYFRESNEL) {
  18913. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18914. }
  18915. if (this._defines.REFLECTIONFRESNEL) {
  18916. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18917. }
  18918. if (this._defines.EMISSIVEFRESNEL) {
  18919. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18920. }
  18921. if (this._defines.FRESNEL) {
  18922. fallbacks.addFallback(4, "FRESNEL");
  18923. }
  18924. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  18925. fallbacks.addCPUSkinningFallback(0, mesh);
  18926. }
  18927. //Attributes
  18928. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18929. if (this._defines.NORMAL) {
  18930. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18931. }
  18932. if (this._defines.UV1) {
  18933. attribs.push(BABYLON.VertexBuffer.UVKind);
  18934. }
  18935. if (this._defines.UV2) {
  18936. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18937. }
  18938. if (this._defines.VERTEXCOLOR) {
  18939. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18940. }
  18941. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  18942. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18943. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18944. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  18945. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  18946. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  18947. }
  18948. }
  18949. if (this._defines.INSTANCES) {
  18950. attribs.push("world0");
  18951. attribs.push("world1");
  18952. attribs.push("world2");
  18953. attribs.push("world3");
  18954. }
  18955. // Legacy browser patch
  18956. var shaderName = "default";
  18957. if (!scene.getEngine().getCaps().standardDerivatives) {
  18958. shaderName = "legacydefault";
  18959. }
  18960. var join = this._defines.toString();
  18961. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18962. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18963. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18964. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18965. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18966. "vFogInfos", "vFogColor", "pointSize",
  18967. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  18968. "mBones",
  18969. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  18970. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18971. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  18972. "logarithmicDepthConstant"
  18973. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  18974. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18975. ], join, fallbacks, this.onCompiled, this.onError);
  18976. }
  18977. if (!this._effect.isReady()) {
  18978. return false;
  18979. }
  18980. this._renderId = scene.getRenderId();
  18981. this._wasPreviouslyReady = true;
  18982. if (mesh) {
  18983. if (!mesh._materialDefines) {
  18984. mesh._materialDefines = new StandardMaterialDefines();
  18985. }
  18986. this._defines.cloneTo(mesh._materialDefines);
  18987. }
  18988. return true;
  18989. };
  18990. StandardMaterial.prototype.unbind = function () {
  18991. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18992. this._effect.setTexture("reflection2DSampler", null);
  18993. }
  18994. _super.prototype.unbind.call(this);
  18995. };
  18996. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18997. this._effect.setMatrix("world", world);
  18998. };
  18999. StandardMaterial.prototype.bind = function (world, mesh) {
  19000. var scene = this.getScene();
  19001. // Matrices
  19002. this.bindOnlyWorldMatrix(world);
  19003. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19004. // Bones
  19005. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19006. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19007. }
  19008. if (scene.getCachedMaterial() !== this) {
  19009. if (StandardMaterial.FresnelEnabled) {
  19010. // Fresnel
  19011. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19012. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19013. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19014. }
  19015. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19016. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19017. }
  19018. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19019. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19020. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19021. }
  19022. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19023. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19024. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19025. }
  19026. }
  19027. // Textures
  19028. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19029. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19030. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19031. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19032. }
  19033. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19034. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19035. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19036. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19037. }
  19038. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19039. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19040. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19041. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19042. }
  19043. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19044. if (this.reflectionTexture.isCube) {
  19045. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19046. }
  19047. else {
  19048. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19049. }
  19050. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19051. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19052. }
  19053. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19054. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19055. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19056. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19057. }
  19058. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19059. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19060. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19061. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19062. }
  19063. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19064. this._effect.setTexture("specularSampler", this.specularTexture);
  19065. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19066. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19067. }
  19068. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19069. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19070. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19071. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19072. }
  19073. // Clip plane
  19074. if (scene.clipPlane) {
  19075. var clipPlane = scene.clipPlane;
  19076. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19077. }
  19078. // Point size
  19079. if (this.pointsCloud) {
  19080. this._effect.setFloat("pointSize", this.pointSize);
  19081. }
  19082. // Colors
  19083. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19084. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19085. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19086. if (this._defines.SPECULARTERM) {
  19087. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19088. }
  19089. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19090. }
  19091. // Diffuse
  19092. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19093. // Lights
  19094. if (scene.lightsEnabled && !this.disableLighting) {
  19095. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19096. }
  19097. // View
  19098. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19099. this._effect.setMatrix("view", scene.getViewMatrix());
  19100. }
  19101. // Fog
  19102. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19103. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19104. this._effect.setColor3("vFogColor", scene.fogColor);
  19105. }
  19106. // Log. depth
  19107. if (this._defines.LOGARITHMICDEPTH) {
  19108. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19109. }
  19110. _super.prototype.bind.call(this, world, mesh);
  19111. };
  19112. StandardMaterial.prototype.getAnimatables = function () {
  19113. var results = [];
  19114. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19115. results.push(this.diffuseTexture);
  19116. }
  19117. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19118. results.push(this.ambientTexture);
  19119. }
  19120. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19121. results.push(this.opacityTexture);
  19122. }
  19123. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19124. results.push(this.reflectionTexture);
  19125. }
  19126. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19127. results.push(this.emissiveTexture);
  19128. }
  19129. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19130. results.push(this.specularTexture);
  19131. }
  19132. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19133. results.push(this.bumpTexture);
  19134. }
  19135. return results;
  19136. };
  19137. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19138. if (this.diffuseTexture) {
  19139. this.diffuseTexture.dispose();
  19140. }
  19141. if (this.ambientTexture) {
  19142. this.ambientTexture.dispose();
  19143. }
  19144. if (this.opacityTexture) {
  19145. this.opacityTexture.dispose();
  19146. }
  19147. if (this.reflectionTexture) {
  19148. this.reflectionTexture.dispose();
  19149. }
  19150. if (this.emissiveTexture) {
  19151. this.emissiveTexture.dispose();
  19152. }
  19153. if (this.specularTexture) {
  19154. this.specularTexture.dispose();
  19155. }
  19156. if (this.bumpTexture) {
  19157. this.bumpTexture.dispose();
  19158. }
  19159. _super.prototype.dispose.call(this, forceDisposeEffect);
  19160. };
  19161. StandardMaterial.prototype.clone = function (name) {
  19162. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19163. // Base material
  19164. this.copyTo(newStandardMaterial);
  19165. // Standard material
  19166. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19167. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19168. }
  19169. if (this.ambientTexture && this.ambientTexture.clone) {
  19170. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19171. }
  19172. if (this.opacityTexture && this.opacityTexture.clone) {
  19173. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19174. }
  19175. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19176. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19177. }
  19178. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19179. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19180. }
  19181. if (this.specularTexture && this.specularTexture.clone) {
  19182. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19183. }
  19184. if (this.bumpTexture && this.bumpTexture.clone) {
  19185. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19186. }
  19187. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19188. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19189. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19190. }
  19191. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19192. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19193. newStandardMaterial.specularColor = this.specularColor.clone();
  19194. newStandardMaterial.specularPower = this.specularPower;
  19195. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19196. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19197. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19198. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19199. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19200. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19201. newStandardMaterial.roughness = this.roughness;
  19202. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19203. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19204. }
  19205. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19206. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19207. }
  19208. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19209. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19210. }
  19211. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19212. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19213. }
  19214. return newStandardMaterial;
  19215. };
  19216. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19217. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19218. // Statics
  19219. // Flags used to enable or disable a type of texture for all Standard Materials
  19220. StandardMaterial.DiffuseTextureEnabled = true;
  19221. StandardMaterial.AmbientTextureEnabled = true;
  19222. StandardMaterial.OpacityTextureEnabled = true;
  19223. StandardMaterial.ReflectionTextureEnabled = true;
  19224. StandardMaterial.EmissiveTextureEnabled = true;
  19225. StandardMaterial.SpecularTextureEnabled = true;
  19226. StandardMaterial.BumpTextureEnabled = true;
  19227. StandardMaterial.FresnelEnabled = true;
  19228. StandardMaterial.LightmapEnabled = true;
  19229. return StandardMaterial;
  19230. })(BABYLON.Material);
  19231. BABYLON.StandardMaterial = StandardMaterial;
  19232. })(BABYLON || (BABYLON = {}));
  19233. var BABYLON;
  19234. (function (BABYLON) {
  19235. var MultiMaterial = (function (_super) {
  19236. __extends(MultiMaterial, _super);
  19237. function MultiMaterial(name, scene) {
  19238. _super.call(this, name, scene, true);
  19239. this.subMaterials = new Array();
  19240. scene.multiMaterials.push(this);
  19241. }
  19242. // Properties
  19243. MultiMaterial.prototype.getSubMaterial = function (index) {
  19244. if (index < 0 || index >= this.subMaterials.length) {
  19245. return this.getScene().defaultMaterial;
  19246. }
  19247. return this.subMaterials[index];
  19248. };
  19249. // Methods
  19250. MultiMaterial.prototype.isReady = function (mesh) {
  19251. for (var index = 0; index < this.subMaterials.length; index++) {
  19252. var subMaterial = this.subMaterials[index];
  19253. if (subMaterial) {
  19254. if (!this.subMaterials[index].isReady(mesh)) {
  19255. return false;
  19256. }
  19257. }
  19258. }
  19259. return true;
  19260. };
  19261. MultiMaterial.prototype.clone = function (name) {
  19262. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19263. for (var index = 0; index < this.subMaterials.length; index++) {
  19264. var subMaterial = this.subMaterials[index];
  19265. newMultiMaterial.subMaterials.push(subMaterial);
  19266. }
  19267. return newMultiMaterial;
  19268. };
  19269. return MultiMaterial;
  19270. })(BABYLON.Material);
  19271. BABYLON.MultiMaterial = MultiMaterial;
  19272. })(BABYLON || (BABYLON = {}));
  19273. var BABYLON;
  19274. (function (BABYLON) {
  19275. var SceneLoader = (function () {
  19276. function SceneLoader() {
  19277. }
  19278. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19279. get: function () {
  19280. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19281. },
  19282. set: function (value) {
  19283. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19284. },
  19285. enumerable: true,
  19286. configurable: true
  19287. });
  19288. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19289. get: function () {
  19290. return SceneLoader._ShowLoadingScreen;
  19291. },
  19292. set: function (value) {
  19293. SceneLoader._ShowLoadingScreen = value;
  19294. },
  19295. enumerable: true,
  19296. configurable: true
  19297. });
  19298. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19299. var dotPosition = sceneFilename.lastIndexOf(".");
  19300. var queryStringPosition = sceneFilename.indexOf("?");
  19301. if (queryStringPosition === -1) {
  19302. queryStringPosition = sceneFilename.length;
  19303. }
  19304. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19305. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19306. var plugin = this._registeredPlugins[index];
  19307. if (plugin.extensions.indexOf(extension) !== -1) {
  19308. return plugin;
  19309. }
  19310. }
  19311. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19312. };
  19313. // Public functions
  19314. SceneLoader.RegisterPlugin = function (plugin) {
  19315. plugin.extensions = plugin.extensions.toLowerCase();
  19316. SceneLoader._registeredPlugins.push(plugin);
  19317. };
  19318. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19319. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19320. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19321. return;
  19322. }
  19323. var loadingToken = {};
  19324. scene._addPendingData(loadingToken);
  19325. var manifestChecked = function (success) {
  19326. scene.database = database;
  19327. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19328. var importMeshFromData = function (data) {
  19329. var meshes = [];
  19330. var particleSystems = [];
  19331. var skeletons = [];
  19332. try {
  19333. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19334. if (onerror) {
  19335. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19336. }
  19337. scene._removePendingData(loadingToken);
  19338. return;
  19339. }
  19340. }
  19341. catch (e) {
  19342. if (onerror) {
  19343. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19344. }
  19345. scene._removePendingData(loadingToken);
  19346. return;
  19347. }
  19348. if (onsuccess) {
  19349. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19350. onsuccess(meshes, particleSystems, skeletons);
  19351. scene._removePendingData(loadingToken);
  19352. }
  19353. };
  19354. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19355. // Direct load
  19356. importMeshFromData(sceneFilename.substr(5));
  19357. return;
  19358. }
  19359. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19360. importMeshFromData(data);
  19361. }, progressCallBack, database);
  19362. };
  19363. if (scene.getEngine().enableOfflineSupport) {
  19364. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19365. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19366. }
  19367. else {
  19368. manifestChecked(true);
  19369. }
  19370. };
  19371. /**
  19372. * Load a scene
  19373. * @param rootUrl a string that defines the root url for scene and resources
  19374. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19375. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19376. */
  19377. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19378. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19379. };
  19380. /**
  19381. * Append a scene
  19382. * @param rootUrl a string that defines the root url for scene and resources
  19383. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19384. * @param scene is the instance of BABYLON.Scene to append to
  19385. */
  19386. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19387. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19388. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19389. return;
  19390. }
  19391. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19392. var database;
  19393. var loadingToken = {};
  19394. scene._addPendingData(loadingToken);
  19395. if (SceneLoader.ShowLoadingScreen) {
  19396. scene.getEngine().displayLoadingUI();
  19397. }
  19398. var loadSceneFromData = function (data) {
  19399. scene.database = database;
  19400. if (!plugin.load(scene, data, rootUrl)) {
  19401. if (onerror) {
  19402. onerror(scene);
  19403. }
  19404. scene._removePendingData(loadingToken);
  19405. scene.getEngine().hideLoadingUI();
  19406. return;
  19407. }
  19408. if (onsuccess) {
  19409. onsuccess(scene);
  19410. }
  19411. scene._removePendingData(loadingToken);
  19412. if (SceneLoader.ShowLoadingScreen) {
  19413. scene.executeWhenReady(function () {
  19414. scene.getEngine().hideLoadingUI();
  19415. });
  19416. }
  19417. };
  19418. var manifestChecked = function (success) {
  19419. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19420. };
  19421. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19422. // Direct load
  19423. loadSceneFromData(sceneFilename.substr(5));
  19424. return;
  19425. }
  19426. if (rootUrl.indexOf("file:") === -1) {
  19427. if (scene.getEngine().enableOfflineSupport) {
  19428. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19429. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19430. }
  19431. else {
  19432. manifestChecked(true);
  19433. }
  19434. }
  19435. else {
  19436. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19437. }
  19438. };
  19439. // Flags
  19440. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19441. SceneLoader._ShowLoadingScreen = true;
  19442. // Members
  19443. SceneLoader._registeredPlugins = new Array();
  19444. return SceneLoader;
  19445. })();
  19446. BABYLON.SceneLoader = SceneLoader;
  19447. ;
  19448. })(BABYLON || (BABYLON = {}));
  19449. var BABYLON;
  19450. (function (BABYLON) {
  19451. var Internals;
  19452. (function (Internals) {
  19453. var checkColors4 = function (colors, count) {
  19454. // Check if color3 was used
  19455. if (colors.length === count * 3) {
  19456. var colors4 = [];
  19457. for (var index = 0; index < colors.length; index += 3) {
  19458. var newIndex = (index / 3) * 4;
  19459. colors4[newIndex] = colors[index];
  19460. colors4[newIndex + 1] = colors[index + 1];
  19461. colors4[newIndex + 2] = colors[index + 2];
  19462. colors4[newIndex + 3] = 1.0;
  19463. }
  19464. return colors4;
  19465. }
  19466. return colors;
  19467. };
  19468. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19469. var texture = null;
  19470. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19471. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19472. texture.name = parsedTexture.name;
  19473. texture.hasAlpha = parsedTexture.hasAlpha;
  19474. texture.level = parsedTexture.level;
  19475. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19476. }
  19477. return texture;
  19478. };
  19479. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19480. if (parsedTexture.isCube) {
  19481. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19482. }
  19483. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19484. return null;
  19485. }
  19486. var texture;
  19487. if (parsedTexture.mirrorPlane) {
  19488. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19489. texture._waitingRenderList = parsedTexture.renderList;
  19490. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19491. }
  19492. else if (parsedTexture.isRenderTarget) {
  19493. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19494. texture._waitingRenderList = parsedTexture.renderList;
  19495. }
  19496. else {
  19497. if (parsedTexture.base64String) {
  19498. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19499. }
  19500. else {
  19501. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19502. }
  19503. }
  19504. texture.name = parsedTexture.name;
  19505. texture.hasAlpha = parsedTexture.hasAlpha;
  19506. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19507. texture.level = parsedTexture.level;
  19508. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19509. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19510. texture.uOffset = parsedTexture.uOffset;
  19511. texture.vOffset = parsedTexture.vOffset;
  19512. texture.uScale = parsedTexture.uScale;
  19513. texture.vScale = parsedTexture.vScale;
  19514. texture.uAng = parsedTexture.uAng;
  19515. texture.vAng = parsedTexture.vAng;
  19516. texture.wAng = parsedTexture.wAng;
  19517. texture.wrapU = parsedTexture.wrapU;
  19518. texture.wrapV = parsedTexture.wrapV;
  19519. // Animations
  19520. if (parsedTexture.animations) {
  19521. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19522. var parsedAnimation = parsedTexture.animations[animationIndex];
  19523. texture.animations.push(parseAnimation(parsedAnimation));
  19524. }
  19525. }
  19526. return texture;
  19527. };
  19528. var parseSkeleton = function (parsedSkeleton, scene) {
  19529. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19530. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19531. var parsedBone = parsedSkeleton.bones[index];
  19532. var parentBone = null;
  19533. if (parsedBone.parentBoneIndex > -1) {
  19534. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19535. }
  19536. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19537. if (parsedBone.animation) {
  19538. bone.animations.push(parseAnimation(parsedBone.animation));
  19539. }
  19540. }
  19541. return skeleton;
  19542. };
  19543. var parseFresnelParameters = function (parsedFresnelParameters) {
  19544. var fresnelParameters = new BABYLON.FresnelParameters();
  19545. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19546. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19547. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19548. fresnelParameters.bias = parsedFresnelParameters.bias;
  19549. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19550. return fresnelParameters;
  19551. };
  19552. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19553. var material;
  19554. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19555. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19556. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19557. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19558. material.specularPower = parsedMaterial.specularPower;
  19559. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19560. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19561. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19562. material.alpha = parsedMaterial.alpha;
  19563. material.id = parsedMaterial.id;
  19564. if (parsedMaterial.disableDepthWrite) {
  19565. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19566. }
  19567. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19568. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19569. material.wireframe = parsedMaterial.wireframe;
  19570. if (parsedMaterial.diffuseTexture) {
  19571. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19572. }
  19573. if (parsedMaterial.diffuseFresnelParameters) {
  19574. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19575. }
  19576. if (parsedMaterial.ambientTexture) {
  19577. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19578. }
  19579. if (parsedMaterial.opacityTexture) {
  19580. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19581. }
  19582. if (parsedMaterial.opacityFresnelParameters) {
  19583. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19584. }
  19585. if (parsedMaterial.reflectionTexture) {
  19586. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19587. }
  19588. if (parsedMaterial.reflectionFresnelParameters) {
  19589. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19590. }
  19591. if (parsedMaterial.emissiveTexture) {
  19592. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19593. }
  19594. if (parsedMaterial.lightmapTexture) {
  19595. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19596. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19597. }
  19598. if (parsedMaterial.emissiveFresnelParameters) {
  19599. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19600. }
  19601. if (parsedMaterial.specularTexture) {
  19602. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19603. }
  19604. if (parsedMaterial.bumpTexture) {
  19605. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19606. }
  19607. if (parsedMaterial.checkReadyOnlyOnce) {
  19608. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19609. }
  19610. return material;
  19611. };
  19612. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19613. for (var index = 0; index < parsedData.materials.length; index++) {
  19614. var parsedMaterial = parsedData.materials[index];
  19615. if (parsedMaterial.id === id) {
  19616. return parseMaterial(parsedMaterial, scene, rootUrl);
  19617. }
  19618. }
  19619. return null;
  19620. };
  19621. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19622. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19623. multiMaterial.id = parsedMultiMaterial.id;
  19624. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19625. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19626. var subMatId = parsedMultiMaterial.materials[matIndex];
  19627. if (subMatId) {
  19628. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19629. }
  19630. else {
  19631. multiMaterial.subMaterials.push(null);
  19632. }
  19633. }
  19634. return multiMaterial;
  19635. };
  19636. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19637. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19638. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19639. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19640. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19641. var parsedFlare = parsedLensFlareSystem.flares[index];
  19642. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19643. }
  19644. return lensFlareSystem;
  19645. };
  19646. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19647. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19648. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19649. if (parsedParticleSystem.textureName) {
  19650. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19651. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19652. }
  19653. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19654. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19655. particleSystem.minSize = parsedParticleSystem.minSize;
  19656. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19657. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19658. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19659. particleSystem.emitter = emitter;
  19660. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19661. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19662. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19663. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19664. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19665. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19666. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19667. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19668. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19669. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19670. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19671. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19672. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19673. particleSystem.start();
  19674. return particleSystem;
  19675. };
  19676. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19677. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19678. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19679. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19680. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19681. shadowGenerator.getShadowMap().renderList.push(mesh);
  19682. }
  19683. if (parsedShadowGenerator.usePoissonSampling) {
  19684. shadowGenerator.usePoissonSampling = true;
  19685. }
  19686. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19687. shadowGenerator.useVarianceShadowMap = true;
  19688. }
  19689. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19690. shadowGenerator.useBlurVarianceShadowMap = true;
  19691. if (parsedShadowGenerator.blurScale) {
  19692. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19693. }
  19694. if (parsedShadowGenerator.blurBoxOffset) {
  19695. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19696. }
  19697. }
  19698. if (parsedShadowGenerator.bias !== undefined) {
  19699. shadowGenerator.bias = parsedShadowGenerator.bias;
  19700. }
  19701. return shadowGenerator;
  19702. };
  19703. var parseAnimation = function (parsedAnimation) {
  19704. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19705. var dataType = parsedAnimation.dataType;
  19706. var keys = [];
  19707. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19708. var key = parsedAnimation.keys[index];
  19709. var data;
  19710. switch (dataType) {
  19711. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19712. data = key.values[0];
  19713. break;
  19714. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19715. data = BABYLON.Quaternion.FromArray(key.values);
  19716. break;
  19717. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19718. data = BABYLON.Matrix.FromArray(key.values);
  19719. break;
  19720. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19721. default:
  19722. data = BABYLON.Vector3.FromArray(key.values);
  19723. break;
  19724. }
  19725. keys.push({
  19726. frame: key.frame,
  19727. value: data
  19728. });
  19729. }
  19730. animation.setKeys(keys);
  19731. return animation;
  19732. };
  19733. var parseLight = function (parsedLight, scene) {
  19734. var light;
  19735. switch (parsedLight.type) {
  19736. case 0:
  19737. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19738. break;
  19739. case 1:
  19740. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19741. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19742. break;
  19743. case 2:
  19744. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19745. break;
  19746. case 3:
  19747. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19748. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19749. break;
  19750. }
  19751. light.id = parsedLight.id;
  19752. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19753. if (parsedLight.intensity !== undefined) {
  19754. light.intensity = parsedLight.intensity;
  19755. }
  19756. if (parsedLight.range) {
  19757. light.range = parsedLight.range;
  19758. }
  19759. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19760. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19761. if (parsedLight.excludedMeshesIds) {
  19762. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19763. }
  19764. // Parent
  19765. if (parsedLight.parentId) {
  19766. light._waitingParentId = parsedLight.parentId;
  19767. }
  19768. if (parsedLight.includedOnlyMeshesIds) {
  19769. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19770. }
  19771. // Animations
  19772. if (parsedLight.animations) {
  19773. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19774. var parsedAnimation = parsedLight.animations[animationIndex];
  19775. light.animations.push(parseAnimation(parsedAnimation));
  19776. }
  19777. }
  19778. if (parsedLight.autoAnimate) {
  19779. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19780. }
  19781. };
  19782. var parseCamera = function (parsedCamera, scene) {
  19783. var camera;
  19784. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19785. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19786. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19787. var alpha = parsedCamera.alpha;
  19788. var beta = parsedCamera.beta;
  19789. var radius = parsedCamera.radius;
  19790. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19791. var interaxial_distance = parsedCamera.interaxial_distance;
  19792. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19793. }
  19794. else {
  19795. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19796. }
  19797. }
  19798. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19799. interaxial_distance = parsedCamera.interaxial_distance;
  19800. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19801. }
  19802. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19803. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19804. }
  19805. else if (parsedCamera.type === "FollowCamera") {
  19806. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19807. camera.heightOffset = parsedCamera.heightOffset;
  19808. camera.radius = parsedCamera.radius;
  19809. camera.rotationOffset = parsedCamera.rotationOffset;
  19810. if (lockedTargetMesh)
  19811. camera.target = lockedTargetMesh;
  19812. }
  19813. else if (parsedCamera.type === "GamepadCamera") {
  19814. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19815. }
  19816. else if (parsedCamera.type === "TouchCamera") {
  19817. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19818. }
  19819. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19820. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19821. }
  19822. else if (parsedCamera.type === "WebVRFreeCamera") {
  19823. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19824. }
  19825. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19826. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19827. }
  19828. else {
  19829. // Free Camera is the default value
  19830. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19831. }
  19832. // apply 3d rig, when found
  19833. if (parsedCamera.cameraRigMode) {
  19834. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19835. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19836. }
  19837. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19838. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19839. camera.lockedTarget = lockedTargetMesh;
  19840. }
  19841. camera.id = parsedCamera.id;
  19842. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19843. // Parent
  19844. if (parsedCamera.parentId) {
  19845. camera._waitingParentId = parsedCamera.parentId;
  19846. }
  19847. // Target
  19848. if (parsedCamera.target) {
  19849. if (camera.setTarget) {
  19850. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19851. }
  19852. else {
  19853. //For ArcRotate
  19854. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19855. }
  19856. }
  19857. else {
  19858. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19859. }
  19860. camera.fov = parsedCamera.fov;
  19861. camera.minZ = parsedCamera.minZ;
  19862. camera.maxZ = parsedCamera.maxZ;
  19863. camera.speed = parsedCamera.speed;
  19864. camera.inertia = parsedCamera.inertia;
  19865. camera.checkCollisions = parsedCamera.checkCollisions;
  19866. camera.applyGravity = parsedCamera.applyGravity;
  19867. if (parsedCamera.ellipsoid) {
  19868. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19869. }
  19870. // Animations
  19871. if (parsedCamera.animations) {
  19872. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19873. var parsedAnimation = parsedCamera.animations[animationIndex];
  19874. camera.animations.push(parseAnimation(parsedAnimation));
  19875. }
  19876. }
  19877. if (parsedCamera.autoAnimate) {
  19878. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19879. }
  19880. // Layer Mask
  19881. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19882. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19883. }
  19884. else {
  19885. camera.layerMask = 0x0FFFFFFF;
  19886. }
  19887. return camera;
  19888. };
  19889. var parseGeometry = function (parsedGeometry, scene) {
  19890. var id = parsedGeometry.id;
  19891. return scene.getGeometryByID(id);
  19892. };
  19893. var parseBox = function (parsedBox, scene) {
  19894. if (parseGeometry(parsedBox, scene)) {
  19895. return null; // null since geometry could be something else than a box...
  19896. }
  19897. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19898. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19899. scene.pushGeometry(box, true);
  19900. return box;
  19901. };
  19902. var parseSphere = function (parsedSphere, scene) {
  19903. if (parseGeometry(parsedSphere, scene)) {
  19904. return null; // null since geometry could be something else than a sphere...
  19905. }
  19906. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19907. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19908. scene.pushGeometry(sphere, true);
  19909. return sphere;
  19910. };
  19911. var parseCylinder = function (parsedCylinder, scene) {
  19912. if (parseGeometry(parsedCylinder, scene)) {
  19913. return null; // null since geometry could be something else than a cylinder...
  19914. }
  19915. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19916. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19917. scene.pushGeometry(cylinder, true);
  19918. return cylinder;
  19919. };
  19920. var parseTorus = function (parsedTorus, scene) {
  19921. if (parseGeometry(parsedTorus, scene)) {
  19922. return null; // null since geometry could be something else than a torus...
  19923. }
  19924. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19925. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19926. scene.pushGeometry(torus, true);
  19927. return torus;
  19928. };
  19929. var parseGround = function (parsedGround, scene) {
  19930. if (parseGeometry(parsedGround, scene)) {
  19931. return null; // null since geometry could be something else than a ground...
  19932. }
  19933. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19934. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19935. scene.pushGeometry(ground, true);
  19936. return ground;
  19937. };
  19938. var parsePlane = function (parsedPlane, scene) {
  19939. if (parseGeometry(parsedPlane, scene)) {
  19940. return null; // null since geometry could be something else than a plane...
  19941. }
  19942. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19943. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19944. scene.pushGeometry(plane, true);
  19945. return plane;
  19946. };
  19947. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19948. if (parseGeometry(parsedTorusKnot, scene)) {
  19949. return null; // null since geometry could be something else than a torusKnot...
  19950. }
  19951. 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);
  19952. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19953. scene.pushGeometry(torusKnot, true);
  19954. return torusKnot;
  19955. };
  19956. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19957. if (parseGeometry(parsedVertexData, scene)) {
  19958. return null; // null since geometry could be a primitive
  19959. }
  19960. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19961. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19962. if (parsedVertexData.delayLoadingFile) {
  19963. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19964. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19965. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19966. geometry._delayInfo = [];
  19967. if (parsedVertexData.hasUVs) {
  19968. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19969. }
  19970. if (parsedVertexData.hasUVs2) {
  19971. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19972. }
  19973. if (parsedVertexData.hasUVs3) {
  19974. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19975. }
  19976. if (parsedVertexData.hasUVs4) {
  19977. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19978. }
  19979. if (parsedVertexData.hasUVs5) {
  19980. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19981. }
  19982. if (parsedVertexData.hasUVs6) {
  19983. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19984. }
  19985. if (parsedVertexData.hasColors) {
  19986. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19987. }
  19988. if (parsedVertexData.hasMatricesIndices) {
  19989. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19990. }
  19991. if (parsedVertexData.hasMatricesWeights) {
  19992. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19993. }
  19994. geometry._delayLoadingFunction = importVertexData;
  19995. }
  19996. else {
  19997. importVertexData(parsedVertexData, geometry);
  19998. }
  19999. scene.pushGeometry(geometry, true);
  20000. return geometry;
  20001. };
  20002. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20003. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20004. mesh.id = parsedMesh.id;
  20005. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20006. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20007. if (parsedMesh.rotationQuaternion) {
  20008. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20009. }
  20010. else if (parsedMesh.rotation) {
  20011. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20012. }
  20013. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20014. if (parsedMesh.localMatrix) {
  20015. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20016. }
  20017. else if (parsedMesh.pivotMatrix) {
  20018. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20019. }
  20020. mesh.setEnabled(parsedMesh.isEnabled);
  20021. mesh.isVisible = parsedMesh.isVisible;
  20022. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20023. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20024. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20025. if (parsedMesh.applyFog !== undefined) {
  20026. mesh.applyFog = parsedMesh.applyFog;
  20027. }
  20028. if (parsedMesh.pickable !== undefined) {
  20029. mesh.isPickable = parsedMesh.pickable;
  20030. }
  20031. if (parsedMesh.alphaIndex !== undefined) {
  20032. mesh.alphaIndex = parsedMesh.alphaIndex;
  20033. }
  20034. mesh.receiveShadows = parsedMesh.receiveShadows;
  20035. mesh.billboardMode = parsedMesh.billboardMode;
  20036. if (parsedMesh.visibility !== undefined) {
  20037. mesh.visibility = parsedMesh.visibility;
  20038. }
  20039. mesh.checkCollisions = parsedMesh.checkCollisions;
  20040. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20041. // freezeWorldMatrix
  20042. if (parsedMesh.freezeWorldMatrix) {
  20043. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20044. }
  20045. // Parent
  20046. if (parsedMesh.parentId) {
  20047. mesh._waitingParentId = parsedMesh.parentId;
  20048. }
  20049. // Actions
  20050. if (parsedMesh.actions !== undefined) {
  20051. mesh._waitingActions = parsedMesh.actions;
  20052. }
  20053. // Geometry
  20054. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20055. if (parsedMesh.delayLoadingFile) {
  20056. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20057. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20058. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20059. if (parsedMesh._binaryInfo) {
  20060. mesh._binaryInfo = parsedMesh._binaryInfo;
  20061. }
  20062. mesh._delayInfo = [];
  20063. if (parsedMesh.hasUVs) {
  20064. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20065. }
  20066. if (parsedMesh.hasUVs2) {
  20067. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20068. }
  20069. if (parsedMesh.hasUVs3) {
  20070. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20071. }
  20072. if (parsedMesh.hasUVs4) {
  20073. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20074. }
  20075. if (parsedMesh.hasUVs5) {
  20076. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20077. }
  20078. if (parsedMesh.hasUVs6) {
  20079. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20080. }
  20081. if (parsedMesh.hasColors) {
  20082. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20083. }
  20084. if (parsedMesh.hasMatricesIndices) {
  20085. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20086. }
  20087. if (parsedMesh.hasMatricesWeights) {
  20088. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20089. }
  20090. mesh._delayLoadingFunction = importGeometry;
  20091. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20092. mesh._checkDelayState();
  20093. }
  20094. }
  20095. else {
  20096. importGeometry(parsedMesh, mesh);
  20097. }
  20098. // Material
  20099. if (parsedMesh.materialId) {
  20100. mesh.setMaterialByID(parsedMesh.materialId);
  20101. }
  20102. else {
  20103. mesh.material = null;
  20104. }
  20105. // Skeleton
  20106. if (parsedMesh.skeletonId > -1) {
  20107. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20108. if (parsedMesh.numBoneInfluencers) {
  20109. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20110. }
  20111. }
  20112. // Physics
  20113. if (parsedMesh.physicsImpostor) {
  20114. if (!scene.isPhysicsEnabled()) {
  20115. scene.enablePhysics();
  20116. }
  20117. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20118. }
  20119. // Animations
  20120. if (parsedMesh.animations) {
  20121. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20122. var parsedAnimation = parsedMesh.animations[animationIndex];
  20123. mesh.animations.push(parseAnimation(parsedAnimation));
  20124. }
  20125. }
  20126. if (parsedMesh.autoAnimate) {
  20127. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20128. }
  20129. // Layer Mask
  20130. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20131. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20132. }
  20133. else {
  20134. mesh.layerMask = 0x0FFFFFFF;
  20135. }
  20136. // Instances
  20137. if (parsedMesh.instances) {
  20138. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20139. var parsedInstance = parsedMesh.instances[index];
  20140. var instance = mesh.createInstance(parsedInstance.name);
  20141. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20142. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20143. if (parsedInstance.rotationQuaternion) {
  20144. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20145. }
  20146. else if (parsedInstance.rotation) {
  20147. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20148. }
  20149. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20150. instance.checkCollisions = mesh.checkCollisions;
  20151. if (parsedMesh.animations) {
  20152. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20153. parsedAnimation = parsedMesh.animations[animationIndex];
  20154. instance.animations.push(parseAnimation(parsedAnimation));
  20155. }
  20156. }
  20157. }
  20158. }
  20159. return mesh;
  20160. };
  20161. var parseActions = function (parsedActions, object, scene) {
  20162. var actionManager = new BABYLON.ActionManager(scene);
  20163. if (object === null)
  20164. scene.actionManager = actionManager;
  20165. else
  20166. object.actionManager = actionManager;
  20167. // instanciate a new object
  20168. var instanciate = function (name, params) {
  20169. var newInstance = Object.create(BABYLON[name].prototype);
  20170. newInstance.constructor.apply(newInstance, params);
  20171. return newInstance;
  20172. };
  20173. var parseParameter = function (name, value, target, propertyPath) {
  20174. if (propertyPath === null) {
  20175. // String, boolean or float
  20176. var floatValue = parseFloat(value);
  20177. if (value === "true" || value === "false")
  20178. return value === "true";
  20179. else
  20180. return isNaN(floatValue) ? value : floatValue;
  20181. }
  20182. var effectiveTarget = propertyPath.split(".");
  20183. var values = value.split(",");
  20184. // Get effective Target
  20185. for (var i = 0; i < effectiveTarget.length; i++) {
  20186. target = target[effectiveTarget[i]];
  20187. }
  20188. // Return appropriate value with its type
  20189. if (typeof (target) === "boolean")
  20190. return values[0] === "true";
  20191. if (typeof (target) === "string")
  20192. return values[0];
  20193. // Parameters with multiple values such as Vector3 etc.
  20194. var split = new Array();
  20195. for (var i = 0; i < values.length; i++)
  20196. split.push(parseFloat(values[i]));
  20197. if (target instanceof BABYLON.Vector3)
  20198. return BABYLON.Vector3.FromArray(split);
  20199. if (target instanceof BABYLON.Vector4)
  20200. return BABYLON.Vector4.FromArray(split);
  20201. if (target instanceof BABYLON.Color3)
  20202. return BABYLON.Color3.FromArray(split);
  20203. if (target instanceof BABYLON.Color4)
  20204. return BABYLON.Color4.FromArray(split);
  20205. return parseFloat(values[0]);
  20206. };
  20207. // traverse graph per trigger
  20208. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20209. if (combineArray === void 0) { combineArray = null; }
  20210. if (parsedAction.detached)
  20211. return;
  20212. var parameters = new Array();
  20213. var target = null;
  20214. var propertyPath = null;
  20215. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20216. // Parameters
  20217. if (parsedAction.type === 2)
  20218. parameters.push(actionManager);
  20219. else
  20220. parameters.push(trigger);
  20221. if (combine) {
  20222. var actions = new Array();
  20223. for (var j = 0; j < parsedAction.combine.length; j++) {
  20224. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20225. }
  20226. parameters.push(actions);
  20227. }
  20228. else {
  20229. for (var i = 0; i < parsedAction.properties.length; i++) {
  20230. var value = parsedAction.properties[i].value;
  20231. var name = parsedAction.properties[i].name;
  20232. var targetType = parsedAction.properties[i].targetType;
  20233. if (name === "target")
  20234. if (targetType !== null && targetType === "SceneProperties")
  20235. value = target = scene;
  20236. else
  20237. value = target = scene.getNodeByName(value);
  20238. else if (name === "parent")
  20239. value = scene.getNodeByName(value);
  20240. else if (name === "sound")
  20241. value = scene.getSoundByName(value);
  20242. else if (name !== "propertyPath") {
  20243. if (parsedAction.type === 2 && name === "operator")
  20244. value = BABYLON.ValueCondition[value];
  20245. else
  20246. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20247. }
  20248. else {
  20249. propertyPath = value;
  20250. }
  20251. parameters.push(value);
  20252. }
  20253. }
  20254. if (combineArray === null) {
  20255. parameters.push(condition);
  20256. }
  20257. else {
  20258. parameters.push(null);
  20259. }
  20260. // If interpolate value action
  20261. if (parsedAction.name === "InterpolateValueAction") {
  20262. var param = parameters[parameters.length - 2];
  20263. parameters[parameters.length - 1] = param;
  20264. parameters[parameters.length - 2] = condition;
  20265. }
  20266. // Action or condition(s) and not CombineAction
  20267. var newAction = instanciate(parsedAction.name, parameters);
  20268. if (newAction instanceof BABYLON.Condition && condition !== null) {
  20269. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  20270. if (action)
  20271. action.then(nothing);
  20272. else
  20273. actionManager.registerAction(nothing);
  20274. action = nothing;
  20275. }
  20276. if (combineArray === null) {
  20277. if (newAction instanceof BABYLON.Condition) {
  20278. condition = newAction;
  20279. newAction = action;
  20280. }
  20281. else {
  20282. condition = null;
  20283. if (action)
  20284. action.then(newAction);
  20285. else
  20286. actionManager.registerAction(newAction);
  20287. }
  20288. }
  20289. else {
  20290. combineArray.push(newAction);
  20291. }
  20292. for (var i = 0; i < parsedAction.children.length; i++)
  20293. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20294. };
  20295. // triggers
  20296. for (var i = 0; i < parsedActions.children.length; i++) {
  20297. var triggerParams;
  20298. var trigger = parsedActions.children[i];
  20299. if (trigger.properties.length > 0) {
  20300. var param = trigger.properties[0].value;
  20301. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20302. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20303. }
  20304. else
  20305. triggerParams = BABYLON.ActionManager[trigger.name];
  20306. for (var j = 0; j < trigger.children.length; j++) {
  20307. if (!trigger.detached)
  20308. traverse(trigger.children[j], triggerParams, null, null);
  20309. }
  20310. }
  20311. };
  20312. var parseSound = function (parsedSound, scene, rootUrl) {
  20313. var soundName = parsedSound.name;
  20314. var soundUrl = rootUrl + soundName;
  20315. var options = {
  20316. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20317. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20318. rolloffFactor: parsedSound.rolloffFactor,
  20319. refDistance: parsedSound.refDistance,
  20320. distanceModel: parsedSound.distanceModel,
  20321. playbackRate: parsedSound.playbackRate
  20322. };
  20323. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20324. scene._addPendingData(newSound);
  20325. if (parsedSound.position) {
  20326. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20327. newSound.setPosition(soundPosition);
  20328. }
  20329. if (parsedSound.isDirectional) {
  20330. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20331. if (parsedSound.localDirectionToMesh) {
  20332. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20333. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20334. }
  20335. }
  20336. if (parsedSound.connectedMeshId) {
  20337. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20338. if (connectedMesh) {
  20339. newSound.attachToMesh(connectedMesh);
  20340. }
  20341. }
  20342. };
  20343. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20344. names = (names instanceof Array) ? names : [names];
  20345. for (var i in names) {
  20346. if (mesh.name === names[i]) {
  20347. hierarchyIds.push(mesh.id);
  20348. return true;
  20349. }
  20350. }
  20351. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20352. hierarchyIds.push(mesh.id);
  20353. return true;
  20354. }
  20355. return false;
  20356. };
  20357. var importVertexData = function (parsedVertexData, geometry) {
  20358. var vertexData = new BABYLON.VertexData();
  20359. // positions
  20360. var positions = parsedVertexData.positions;
  20361. if (positions) {
  20362. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20363. }
  20364. // normals
  20365. var normals = parsedVertexData.normals;
  20366. if (normals) {
  20367. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20368. }
  20369. // uvs
  20370. var uvs = parsedVertexData.uvs;
  20371. if (uvs) {
  20372. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20373. }
  20374. // uv2s
  20375. var uv2s = parsedVertexData.uv2s;
  20376. if (uv2s) {
  20377. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20378. }
  20379. // uv3s
  20380. var uv3s = parsedVertexData.uv3s;
  20381. if (uv3s) {
  20382. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20383. }
  20384. // uv4s
  20385. var uv4s = parsedVertexData.uv4s;
  20386. if (uv4s) {
  20387. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20388. }
  20389. // uv5s
  20390. var uv5s = parsedVertexData.uv5s;
  20391. if (uv5s) {
  20392. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20393. }
  20394. // uv6s
  20395. var uv6s = parsedVertexData.uv6s;
  20396. if (uv6s) {
  20397. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20398. }
  20399. // colors
  20400. var colors = parsedVertexData.colors;
  20401. if (colors) {
  20402. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20403. }
  20404. // matricesIndices
  20405. var matricesIndices = parsedVertexData.matricesIndices;
  20406. if (matricesIndices) {
  20407. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20408. }
  20409. // matricesWeights
  20410. var matricesWeights = parsedVertexData.matricesWeights;
  20411. if (matricesWeights) {
  20412. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20413. }
  20414. // indices
  20415. var indices = parsedVertexData.indices;
  20416. if (indices) {
  20417. vertexData.indices = indices;
  20418. }
  20419. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20420. };
  20421. var importGeometry = function (parsedGeometry, mesh) {
  20422. var scene = mesh.getScene();
  20423. // Geometry
  20424. var geometryId = parsedGeometry.geometryId;
  20425. if (geometryId) {
  20426. var geometry = scene.getGeometryByID(geometryId);
  20427. if (geometry) {
  20428. geometry.applyToMesh(mesh);
  20429. }
  20430. }
  20431. else if (parsedGeometry instanceof ArrayBuffer) {
  20432. var binaryInfo = mesh._binaryInfo;
  20433. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20434. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20435. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20436. }
  20437. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20438. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20439. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20440. }
  20441. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20442. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20443. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20444. }
  20445. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20446. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20447. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20448. }
  20449. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20450. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20451. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20452. }
  20453. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20454. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20455. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20456. }
  20457. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20458. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20459. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20460. }
  20461. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20462. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20463. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20464. }
  20465. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20466. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20467. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20468. }
  20469. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20470. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20471. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20472. }
  20473. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20474. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20475. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20476. }
  20477. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20478. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20479. mesh.setIndices(indicesData);
  20480. }
  20481. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20482. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20483. mesh.subMeshes = [];
  20484. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20485. var materialIndex = subMeshesData[(i * 5) + 0];
  20486. var verticesStart = subMeshesData[(i * 5) + 1];
  20487. var verticesCount = subMeshesData[(i * 5) + 2];
  20488. var indexStart = subMeshesData[(i * 5) + 3];
  20489. var indexCount = subMeshesData[(i * 5) + 4];
  20490. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20491. }
  20492. }
  20493. }
  20494. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20495. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20496. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20497. if (parsedGeometry.uvs) {
  20498. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20499. }
  20500. if (parsedGeometry.uvs2) {
  20501. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20502. }
  20503. if (parsedGeometry.uvs3) {
  20504. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20505. }
  20506. if (parsedGeometry.uvs4) {
  20507. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20508. }
  20509. if (parsedGeometry.uvs5) {
  20510. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20511. }
  20512. if (parsedGeometry.uvs6) {
  20513. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20514. }
  20515. if (parsedGeometry.colors) {
  20516. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20517. }
  20518. if (parsedGeometry.matricesIndices) {
  20519. if (!parsedGeometry.matricesIndices._isExpanded) {
  20520. var floatIndices = [];
  20521. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20522. var matricesIndex = parsedGeometry.matricesIndices[i];
  20523. floatIndices.push(matricesIndex & 0x000000FF);
  20524. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20525. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20526. floatIndices.push(matricesIndex >> 24);
  20527. }
  20528. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20529. }
  20530. else {
  20531. delete parsedGeometry.matricesIndices._isExpanded;
  20532. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20533. }
  20534. }
  20535. if (parsedGeometry.matricesIndicesExtra) {
  20536. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  20537. var floatIndices = [];
  20538. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  20539. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  20540. floatIndices.push(matricesIndex & 0x000000FF);
  20541. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20542. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20543. floatIndices.push(matricesIndex >> 24);
  20544. }
  20545. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  20546. }
  20547. else {
  20548. delete parsedGeometry.matricesIndices._isExpanded;
  20549. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  20550. }
  20551. }
  20552. if (parsedGeometry.matricesWeights) {
  20553. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20554. }
  20555. if (parsedGeometry.matricesWeightsExtra) {
  20556. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  20557. }
  20558. mesh.setIndices(parsedGeometry.indices);
  20559. }
  20560. // SubMeshes
  20561. if (parsedGeometry.subMeshes) {
  20562. mesh.subMeshes = [];
  20563. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20564. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20565. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20566. }
  20567. }
  20568. // Flat shading
  20569. if (mesh._shouldGenerateFlatShading) {
  20570. mesh.convertToFlatShadedMesh();
  20571. delete mesh._shouldGenerateFlatShading;
  20572. }
  20573. // Update
  20574. mesh.computeWorldMatrix(true);
  20575. // Octree
  20576. if (scene._selectionOctree) {
  20577. scene._selectionOctree.addMesh(mesh);
  20578. }
  20579. };
  20580. BABYLON.SceneLoader.RegisterPlugin({
  20581. extensions: ".babylon",
  20582. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20583. var parsedData = JSON.parse(data);
  20584. var loadedSkeletonsIds = [];
  20585. var loadedMaterialsIds = [];
  20586. var hierarchyIds = [];
  20587. for (var index = 0; index < parsedData.meshes.length; index++) {
  20588. var parsedMesh = parsedData.meshes[index];
  20589. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20590. if (meshesNames instanceof Array) {
  20591. // Remove found mesh name from list.
  20592. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20593. }
  20594. //Geometry?
  20595. if (parsedMesh.geometryId) {
  20596. //does the file contain geometries?
  20597. if (parsedData.geometries) {
  20598. //find the correct geometry and add it to the scene
  20599. var found = false;
  20600. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20601. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20602. return;
  20603. }
  20604. else {
  20605. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20606. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20607. switch (geometryType) {
  20608. case "boxes":
  20609. parseBox(parsedGeometryData, scene);
  20610. break;
  20611. case "spheres":
  20612. parseSphere(parsedGeometryData, scene);
  20613. break;
  20614. case "cylinders":
  20615. parseCylinder(parsedGeometryData, scene);
  20616. break;
  20617. case "toruses":
  20618. parseTorus(parsedGeometryData, scene);
  20619. break;
  20620. case "grounds":
  20621. parseGround(parsedGeometryData, scene);
  20622. break;
  20623. case "planes":
  20624. parsePlane(parsedGeometryData, scene);
  20625. break;
  20626. case "torusKnots":
  20627. parseTorusKnot(parsedGeometryData, scene);
  20628. break;
  20629. case "vertexData":
  20630. parseVertexData(parsedGeometryData, scene, rootUrl);
  20631. break;
  20632. }
  20633. found = true;
  20634. }
  20635. });
  20636. }
  20637. });
  20638. if (!found) {
  20639. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20640. }
  20641. }
  20642. }
  20643. // Material ?
  20644. if (parsedMesh.materialId) {
  20645. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20646. if (!materialFound && parsedData.multiMaterials) {
  20647. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20648. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20649. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20650. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20651. var subMatId = parsedMultiMaterial.materials[matIndex];
  20652. loadedMaterialsIds.push(subMatId);
  20653. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20654. }
  20655. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20656. parseMultiMaterial(parsedMultiMaterial, scene);
  20657. materialFound = true;
  20658. break;
  20659. }
  20660. }
  20661. }
  20662. if (!materialFound) {
  20663. loadedMaterialsIds.push(parsedMesh.materialId);
  20664. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20665. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20666. }
  20667. }
  20668. }
  20669. // Skeleton ?
  20670. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20671. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20672. if (!skeletonAlreadyLoaded) {
  20673. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20674. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20675. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20676. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20677. loadedSkeletonsIds.push(parsedSkeleton.id);
  20678. }
  20679. }
  20680. }
  20681. }
  20682. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20683. meshes.push(mesh);
  20684. }
  20685. }
  20686. // Connecting parents
  20687. for (index = 0; index < scene.meshes.length; index++) {
  20688. var currentMesh = scene.meshes[index];
  20689. if (currentMesh._waitingParentId) {
  20690. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20691. currentMesh._waitingParentId = undefined;
  20692. }
  20693. }
  20694. // freeze world matrix application
  20695. for (index = 0; index < scene.meshes.length; index++) {
  20696. var currentMesh = scene.meshes[index];
  20697. if (currentMesh._waitingFreezeWorldMatrix) {
  20698. currentMesh.freezeWorldMatrix();
  20699. currentMesh._waitingFreezeWorldMatrix = undefined;
  20700. }
  20701. }
  20702. // Particles
  20703. if (parsedData.particleSystems) {
  20704. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20705. var parsedParticleSystem = parsedData.particleSystems[index];
  20706. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20707. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20708. }
  20709. }
  20710. }
  20711. return true;
  20712. },
  20713. load: function (scene, data, rootUrl) {
  20714. var parsedData = JSON.parse(data);
  20715. // Scene
  20716. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20717. scene.autoClear = parsedData.autoClear;
  20718. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20719. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20720. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20721. // Fog
  20722. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20723. scene.fogMode = parsedData.fogMode;
  20724. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20725. scene.fogStart = parsedData.fogStart;
  20726. scene.fogEnd = parsedData.fogEnd;
  20727. scene.fogDensity = parsedData.fogDensity;
  20728. }
  20729. // Lights
  20730. for (var index = 0; index < parsedData.lights.length; index++) {
  20731. var parsedLight = parsedData.lights[index];
  20732. parseLight(parsedLight, scene);
  20733. }
  20734. // Materials
  20735. if (parsedData.materials) {
  20736. for (index = 0; index < parsedData.materials.length; index++) {
  20737. var parsedMaterial = parsedData.materials[index];
  20738. parseMaterial(parsedMaterial, scene, rootUrl);
  20739. }
  20740. }
  20741. if (parsedData.multiMaterials) {
  20742. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20743. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20744. parseMultiMaterial(parsedMultiMaterial, scene);
  20745. }
  20746. }
  20747. // Skeletons
  20748. if (parsedData.skeletons) {
  20749. for (index = 0; index < parsedData.skeletons.length; index++) {
  20750. var parsedSkeleton = parsedData.skeletons[index];
  20751. parseSkeleton(parsedSkeleton, scene);
  20752. }
  20753. }
  20754. // Geometries
  20755. var geometries = parsedData.geometries;
  20756. if (geometries) {
  20757. // Boxes
  20758. var boxes = geometries.boxes;
  20759. if (boxes) {
  20760. for (index = 0; index < boxes.length; index++) {
  20761. var parsedBox = boxes[index];
  20762. parseBox(parsedBox, scene);
  20763. }
  20764. }
  20765. // Spheres
  20766. var spheres = geometries.spheres;
  20767. if (spheres) {
  20768. for (index = 0; index < spheres.length; index++) {
  20769. var parsedSphere = spheres[index];
  20770. parseSphere(parsedSphere, scene);
  20771. }
  20772. }
  20773. // Cylinders
  20774. var cylinders = geometries.cylinders;
  20775. if (cylinders) {
  20776. for (index = 0; index < cylinders.length; index++) {
  20777. var parsedCylinder = cylinders[index];
  20778. parseCylinder(parsedCylinder, scene);
  20779. }
  20780. }
  20781. // Toruses
  20782. var toruses = geometries.toruses;
  20783. if (toruses) {
  20784. for (index = 0; index < toruses.length; index++) {
  20785. var parsedTorus = toruses[index];
  20786. parseTorus(parsedTorus, scene);
  20787. }
  20788. }
  20789. // Grounds
  20790. var grounds = geometries.grounds;
  20791. if (grounds) {
  20792. for (index = 0; index < grounds.length; index++) {
  20793. var parsedGround = grounds[index];
  20794. parseGround(parsedGround, scene);
  20795. }
  20796. }
  20797. // Planes
  20798. var planes = geometries.planes;
  20799. if (planes) {
  20800. for (index = 0; index < planes.length; index++) {
  20801. var parsedPlane = planes[index];
  20802. parsePlane(parsedPlane, scene);
  20803. }
  20804. }
  20805. // TorusKnots
  20806. var torusKnots = geometries.torusKnots;
  20807. if (torusKnots) {
  20808. for (index = 0; index < torusKnots.length; index++) {
  20809. var parsedTorusKnot = torusKnots[index];
  20810. parseTorusKnot(parsedTorusKnot, scene);
  20811. }
  20812. }
  20813. // VertexData
  20814. var vertexData = geometries.vertexData;
  20815. if (vertexData) {
  20816. for (index = 0; index < vertexData.length; index++) {
  20817. var parsedVertexData = vertexData[index];
  20818. parseVertexData(parsedVertexData, scene, rootUrl);
  20819. }
  20820. }
  20821. }
  20822. // Meshes
  20823. for (index = 0; index < parsedData.meshes.length; index++) {
  20824. var parsedMesh = parsedData.meshes[index];
  20825. parseMesh(parsedMesh, scene, rootUrl);
  20826. }
  20827. // Cameras
  20828. for (index = 0; index < parsedData.cameras.length; index++) {
  20829. var parsedCamera = parsedData.cameras[index];
  20830. parseCamera(parsedCamera, scene);
  20831. }
  20832. if (parsedData.activeCameraID) {
  20833. scene.setActiveCameraByID(parsedData.activeCameraID);
  20834. }
  20835. // Browsing all the graph to connect the dots
  20836. for (index = 0; index < scene.cameras.length; index++) {
  20837. var camera = scene.cameras[index];
  20838. if (camera._waitingParentId) {
  20839. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20840. camera._waitingParentId = undefined;
  20841. }
  20842. }
  20843. for (index = 0; index < scene.lights.length; index++) {
  20844. var light = scene.lights[index];
  20845. if (light._waitingParentId) {
  20846. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20847. light._waitingParentId = undefined;
  20848. }
  20849. }
  20850. // Sounds
  20851. if (BABYLON.AudioEngine && parsedData.sounds) {
  20852. for (index = 0; index < parsedData.sounds.length; index++) {
  20853. var parsedSound = parsedData.sounds[index];
  20854. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20855. parseSound(parsedSound, scene, rootUrl);
  20856. }
  20857. else {
  20858. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20859. }
  20860. }
  20861. }
  20862. // Connect parents & children and parse actions
  20863. for (index = 0; index < scene.meshes.length; index++) {
  20864. var mesh = scene.meshes[index];
  20865. if (mesh._waitingParentId) {
  20866. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20867. mesh._waitingParentId = undefined;
  20868. }
  20869. if (mesh._waitingActions) {
  20870. parseActions(mesh._waitingActions, mesh, scene);
  20871. mesh._waitingActions = undefined;
  20872. }
  20873. }
  20874. // freeze world matrix application
  20875. for (index = 0; index < scene.meshes.length; index++) {
  20876. var currentMesh = scene.meshes[index];
  20877. if (currentMesh._waitingFreezeWorldMatrix) {
  20878. currentMesh.freezeWorldMatrix();
  20879. currentMesh._waitingFreezeWorldMatrix = undefined;
  20880. }
  20881. }
  20882. // Particles Systems
  20883. if (parsedData.particleSystems) {
  20884. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20885. var parsedParticleSystem = parsedData.particleSystems[index];
  20886. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20887. }
  20888. }
  20889. // Lens flares
  20890. if (parsedData.lensFlareSystems) {
  20891. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20892. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20893. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20894. }
  20895. }
  20896. // Shadows
  20897. if (parsedData.shadowGenerators) {
  20898. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20899. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20900. parseShadowGenerator(parsedShadowGenerator, scene);
  20901. }
  20902. }
  20903. // Actions (scene)
  20904. if (parsedData.actions) {
  20905. parseActions(parsedData.actions, null, scene);
  20906. }
  20907. // Finish
  20908. return true;
  20909. }
  20910. });
  20911. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20912. })(BABYLON || (BABYLON = {}));
  20913. var BABYLON;
  20914. (function (BABYLON) {
  20915. var SpriteManager = (function () {
  20916. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20917. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20918. this.name = name;
  20919. this.cellSize = cellSize;
  20920. this.sprites = new Array();
  20921. this.renderingGroupId = 0;
  20922. this.layerMask = 0x0FFFFFFF;
  20923. this.fogEnabled = true;
  20924. this.isPickable = false;
  20925. this._vertexDeclaration = [4, 4, 4, 4];
  20926. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20927. this._capacity = capacity;
  20928. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20929. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20930. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20931. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20932. this._scene = scene;
  20933. this._scene.spriteManagers.push(this);
  20934. // VBO
  20935. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20936. var indices = [];
  20937. var index = 0;
  20938. for (var count = 0; count < capacity; count++) {
  20939. indices.push(index);
  20940. indices.push(index + 1);
  20941. indices.push(index + 2);
  20942. indices.push(index);
  20943. indices.push(index + 2);
  20944. indices.push(index + 3);
  20945. index += 4;
  20946. }
  20947. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20948. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20949. // Effects
  20950. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20951. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20952. }
  20953. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20954. var arrayOffset = index * 16;
  20955. if (offsetX === 0)
  20956. offsetX = this._epsilon;
  20957. else if (offsetX === 1)
  20958. offsetX = 1 - this._epsilon;
  20959. if (offsetY === 0)
  20960. offsetY = this._epsilon;
  20961. else if (offsetY === 1)
  20962. offsetY = 1 - this._epsilon;
  20963. this._vertices[arrayOffset] = sprite.position.x;
  20964. this._vertices[arrayOffset + 1] = sprite.position.y;
  20965. this._vertices[arrayOffset + 2] = sprite.position.z;
  20966. this._vertices[arrayOffset + 3] = sprite.angle;
  20967. this._vertices[arrayOffset + 4] = sprite.width;
  20968. this._vertices[arrayOffset + 5] = sprite.height;
  20969. this._vertices[arrayOffset + 6] = offsetX;
  20970. this._vertices[arrayOffset + 7] = offsetY;
  20971. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20972. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20973. var offset = (sprite.cellIndex / rowSize) >> 0;
  20974. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20975. this._vertices[arrayOffset + 11] = offset;
  20976. // Color
  20977. this._vertices[arrayOffset + 12] = sprite.color.r;
  20978. this._vertices[arrayOffset + 13] = sprite.color.g;
  20979. this._vertices[arrayOffset + 14] = sprite.color.b;
  20980. this._vertices[arrayOffset + 15] = sprite.color.a;
  20981. };
  20982. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20983. var count = Math.min(this._capacity, this.sprites.length);
  20984. var min = BABYLON.Vector3.Zero();
  20985. var max = BABYLON.Vector3.Zero();
  20986. var distance = Number.MAX_VALUE;
  20987. var currentSprite;
  20988. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20989. var cameraView = camera.getViewMatrix();
  20990. for (var index = 0; index < count; index++) {
  20991. var sprite = this.sprites[index];
  20992. if (!sprite) {
  20993. continue;
  20994. }
  20995. if (predicate) {
  20996. if (!predicate(sprite)) {
  20997. continue;
  20998. }
  20999. }
  21000. else if (!sprite.isPickable) {
  21001. continue;
  21002. }
  21003. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21004. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21005. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21006. if (ray.intersectsBoxMinMax(min, max)) {
  21007. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21008. if (distance > currentDistance) {
  21009. distance = currentDistance;
  21010. currentSprite = sprite;
  21011. if (fastCheck) {
  21012. break;
  21013. }
  21014. }
  21015. }
  21016. }
  21017. if (currentSprite) {
  21018. var result = new BABYLON.PickingInfo();
  21019. result.hit = true;
  21020. result.pickedSprite = currentSprite;
  21021. result.distance = distance;
  21022. return result;
  21023. }
  21024. return null;
  21025. };
  21026. SpriteManager.prototype.render = function () {
  21027. // Check
  21028. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21029. return;
  21030. var engine = this._scene.getEngine();
  21031. var baseSize = this._spriteTexture.getBaseSize();
  21032. // Sprites
  21033. var deltaTime = engine.getDeltaTime();
  21034. var max = Math.min(this._capacity, this.sprites.length);
  21035. var rowSize = baseSize.width / this.cellSize;
  21036. var offset = 0;
  21037. for (var index = 0; index < max; index++) {
  21038. var sprite = this.sprites[index];
  21039. if (!sprite) {
  21040. continue;
  21041. }
  21042. sprite._animate(deltaTime);
  21043. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21044. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21045. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21046. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21047. }
  21048. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21049. // Render
  21050. var effect = this._effectBase;
  21051. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21052. effect = this._effectFog;
  21053. }
  21054. engine.enableEffect(effect);
  21055. var viewMatrix = this._scene.getViewMatrix();
  21056. effect.setTexture("diffuseSampler", this._spriteTexture);
  21057. effect.setMatrix("view", viewMatrix);
  21058. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21059. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21060. // Fog
  21061. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21062. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21063. effect.setColor3("vFogColor", this._scene.fogColor);
  21064. }
  21065. // VBOs
  21066. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21067. // Draw order
  21068. engine.setDepthFunctionToLessOrEqual();
  21069. effect.setBool("alphaTest", true);
  21070. engine.setColorWrite(false);
  21071. engine.draw(true, 0, max * 6);
  21072. engine.setColorWrite(true);
  21073. effect.setBool("alphaTest", false);
  21074. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21075. engine.draw(true, 0, max * 6);
  21076. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21077. };
  21078. SpriteManager.prototype.dispose = function () {
  21079. if (this._vertexBuffer) {
  21080. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21081. this._vertexBuffer = null;
  21082. }
  21083. if (this._indexBuffer) {
  21084. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21085. this._indexBuffer = null;
  21086. }
  21087. if (this._spriteTexture) {
  21088. this._spriteTexture.dispose();
  21089. this._spriteTexture = null;
  21090. }
  21091. // Remove from scene
  21092. var index = this._scene.spriteManagers.indexOf(this);
  21093. this._scene.spriteManagers.splice(index, 1);
  21094. // Callback
  21095. if (this.onDispose) {
  21096. this.onDispose();
  21097. }
  21098. };
  21099. return SpriteManager;
  21100. })();
  21101. BABYLON.SpriteManager = SpriteManager;
  21102. })(BABYLON || (BABYLON = {}));
  21103. var BABYLON;
  21104. (function (BABYLON) {
  21105. var Sprite = (function () {
  21106. function Sprite(name, manager) {
  21107. this.name = name;
  21108. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21109. this.width = 1.0;
  21110. this.height = 1.0;
  21111. this.angle = 0;
  21112. this.cellIndex = 0;
  21113. this.invertU = 0;
  21114. this.invertV = 0;
  21115. this.animations = new Array();
  21116. this.isPickable = false;
  21117. this._animationStarted = false;
  21118. this._loopAnimation = false;
  21119. this._fromIndex = 0;
  21120. this._toIndex = 0;
  21121. this._delay = 0;
  21122. this._direction = 1;
  21123. this._frameCount = 0;
  21124. this._time = 0;
  21125. this._manager = manager;
  21126. this._manager.sprites.push(this);
  21127. this.position = BABYLON.Vector3.Zero();
  21128. }
  21129. Object.defineProperty(Sprite.prototype, "size", {
  21130. get: function () {
  21131. return this.width;
  21132. },
  21133. set: function (value) {
  21134. this.width = value;
  21135. this.height = value;
  21136. },
  21137. enumerable: true,
  21138. configurable: true
  21139. });
  21140. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21141. this._fromIndex = from;
  21142. this._toIndex = to;
  21143. this._loopAnimation = loop;
  21144. this._delay = delay;
  21145. this._animationStarted = true;
  21146. this._direction = from < to ? 1 : -1;
  21147. this.cellIndex = from;
  21148. this._time = 0;
  21149. };
  21150. Sprite.prototype.stopAnimation = function () {
  21151. this._animationStarted = false;
  21152. };
  21153. Sprite.prototype._animate = function (deltaTime) {
  21154. if (!this._animationStarted)
  21155. return;
  21156. this._time += deltaTime;
  21157. if (this._time > this._delay) {
  21158. this._time = this._time % this._delay;
  21159. this.cellIndex += this._direction;
  21160. if (this.cellIndex == this._toIndex) {
  21161. if (this._loopAnimation) {
  21162. this.cellIndex = this._fromIndex;
  21163. }
  21164. else {
  21165. this._animationStarted = false;
  21166. if (this.disposeWhenFinishedAnimating) {
  21167. this.dispose();
  21168. }
  21169. }
  21170. }
  21171. }
  21172. };
  21173. Sprite.prototype.dispose = function () {
  21174. for (var i = 0; i < this._manager.sprites.length; i++) {
  21175. if (this._manager.sprites[i] == this) {
  21176. this._manager.sprites.splice(i, 1);
  21177. }
  21178. }
  21179. };
  21180. return Sprite;
  21181. })();
  21182. BABYLON.Sprite = Sprite;
  21183. })(BABYLON || (BABYLON = {}));
  21184. var BABYLON;
  21185. (function (BABYLON) {
  21186. var Layer = (function () {
  21187. function Layer(name, imgUrl, scene, isBackground, color) {
  21188. this.name = name;
  21189. this._vertexDeclaration = [2];
  21190. this._vertexStrideSize = 2 * 4;
  21191. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21192. this.isBackground = isBackground === undefined ? true : isBackground;
  21193. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21194. this._scene = scene;
  21195. this._scene.layers.push(this);
  21196. // VBO
  21197. var vertices = [];
  21198. vertices.push(1, 1);
  21199. vertices.push(-1, 1);
  21200. vertices.push(-1, -1);
  21201. vertices.push(1, -1);
  21202. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21203. // Indices
  21204. var indices = [];
  21205. indices.push(0);
  21206. indices.push(1);
  21207. indices.push(2);
  21208. indices.push(0);
  21209. indices.push(2);
  21210. indices.push(3);
  21211. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21212. // Effects
  21213. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21214. }
  21215. Layer.prototype.render = function () {
  21216. // Check
  21217. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21218. return;
  21219. var engine = this._scene.getEngine();
  21220. // Render
  21221. engine.enableEffect(this._effect);
  21222. engine.setState(false);
  21223. // Texture
  21224. this._effect.setTexture("textureSampler", this.texture);
  21225. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21226. // Color
  21227. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21228. // VBOs
  21229. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21230. // Draw order
  21231. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21232. engine.draw(true, 0, 6);
  21233. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21234. };
  21235. Layer.prototype.dispose = function () {
  21236. if (this._vertexBuffer) {
  21237. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21238. this._vertexBuffer = null;
  21239. }
  21240. if (this._indexBuffer) {
  21241. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21242. this._indexBuffer = null;
  21243. }
  21244. if (this.texture) {
  21245. this.texture.dispose();
  21246. this.texture = null;
  21247. }
  21248. // Remove from scene
  21249. var index = this._scene.layers.indexOf(this);
  21250. this._scene.layers.splice(index, 1);
  21251. // Callback
  21252. if (this.onDispose) {
  21253. this.onDispose();
  21254. }
  21255. };
  21256. return Layer;
  21257. })();
  21258. BABYLON.Layer = Layer;
  21259. })(BABYLON || (BABYLON = {}));
  21260. var BABYLON;
  21261. (function (BABYLON) {
  21262. var Particle = (function () {
  21263. function Particle() {
  21264. this.position = BABYLON.Vector3.Zero();
  21265. this.direction = BABYLON.Vector3.Zero();
  21266. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21267. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21268. this.lifeTime = 1.0;
  21269. this.age = 0;
  21270. this.size = 0;
  21271. this.angle = 0;
  21272. this.angularSpeed = 0;
  21273. }
  21274. Particle.prototype.copyTo = function (other) {
  21275. other.position.copyFrom(this.position);
  21276. other.direction.copyFrom(this.direction);
  21277. other.color.copyFrom(this.color);
  21278. other.colorStep.copyFrom(this.colorStep);
  21279. other.lifeTime = this.lifeTime;
  21280. other.age = this.age;
  21281. other.size = this.size;
  21282. other.angle = this.angle;
  21283. other.angularSpeed = this.angularSpeed;
  21284. };
  21285. return Particle;
  21286. })();
  21287. BABYLON.Particle = Particle;
  21288. })(BABYLON || (BABYLON = {}));
  21289. var BABYLON;
  21290. (function (BABYLON) {
  21291. var randomNumber = function (min, max) {
  21292. if (min === max) {
  21293. return (min);
  21294. }
  21295. var random = Math.random();
  21296. return ((random * (max - min)) + min);
  21297. };
  21298. var ParticleSystem = (function () {
  21299. function ParticleSystem(name, capacity, scene, customEffect) {
  21300. var _this = this;
  21301. this.name = name;
  21302. this.renderingGroupId = 0;
  21303. this.emitter = null;
  21304. this.emitRate = 10;
  21305. this.manualEmitCount = -1;
  21306. this.updateSpeed = 0.01;
  21307. this.targetStopDuration = 0;
  21308. this.disposeOnStop = false;
  21309. this.minEmitPower = 1;
  21310. this.maxEmitPower = 1;
  21311. this.minLifeTime = 1;
  21312. this.maxLifeTime = 1;
  21313. this.minSize = 1;
  21314. this.maxSize = 1;
  21315. this.minAngularSpeed = 0;
  21316. this.maxAngularSpeed = 0;
  21317. this.layerMask = 0x0FFFFFFF;
  21318. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21319. this.forceDepthWrite = false;
  21320. this.gravity = BABYLON.Vector3.Zero();
  21321. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21322. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21323. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21324. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21325. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21326. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21327. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21328. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21329. this.particles = new Array();
  21330. this._vertexDeclaration = [3, 4, 4];
  21331. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21332. this._stockParticles = new Array();
  21333. this._newPartsExcess = 0;
  21334. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21335. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21336. this._scaledDirection = BABYLON.Vector3.Zero();
  21337. this._scaledGravity = BABYLON.Vector3.Zero();
  21338. this._currentRenderId = -1;
  21339. this._started = false;
  21340. this._stopped = false;
  21341. this._actualFrame = 0;
  21342. this.id = name;
  21343. this._capacity = capacity;
  21344. this._scene = scene;
  21345. this._customEffect = customEffect;
  21346. scene.particleSystems.push(this);
  21347. // VBO
  21348. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21349. var indices = [];
  21350. var index = 0;
  21351. for (var count = 0; count < capacity; count++) {
  21352. indices.push(index);
  21353. indices.push(index + 1);
  21354. indices.push(index + 2);
  21355. indices.push(index);
  21356. indices.push(index + 2);
  21357. indices.push(index + 3);
  21358. index += 4;
  21359. }
  21360. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21361. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21362. // Default behaviors
  21363. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21364. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21365. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21366. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21367. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21368. };
  21369. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21370. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21371. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21372. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21373. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21374. };
  21375. this.updateFunction = function (particles) {
  21376. for (var index = 0; index < particles.length; index++) {
  21377. var particle = particles[index];
  21378. particle.age += _this._scaledUpdateSpeed;
  21379. if (particle.age >= particle.lifeTime) {
  21380. _this.recycleParticle(particle);
  21381. index--;
  21382. continue;
  21383. }
  21384. else {
  21385. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21386. particle.color.addInPlace(_this._scaledColorStep);
  21387. if (particle.color.a < 0)
  21388. particle.color.a = 0;
  21389. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21390. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21391. particle.position.addInPlace(_this._scaledDirection);
  21392. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21393. particle.direction.addInPlace(_this._scaledGravity);
  21394. }
  21395. }
  21396. };
  21397. }
  21398. ParticleSystem.prototype.recycleParticle = function (particle) {
  21399. var lastParticle = this.particles.pop();
  21400. if (lastParticle !== particle) {
  21401. lastParticle.copyTo(particle);
  21402. this._stockParticles.push(lastParticle);
  21403. }
  21404. };
  21405. ParticleSystem.prototype.getCapacity = function () {
  21406. return this._capacity;
  21407. };
  21408. ParticleSystem.prototype.isAlive = function () {
  21409. return this._alive;
  21410. };
  21411. ParticleSystem.prototype.isStarted = function () {
  21412. return this._started;
  21413. };
  21414. ParticleSystem.prototype.start = function () {
  21415. this._started = true;
  21416. this._stopped = false;
  21417. this._actualFrame = 0;
  21418. };
  21419. ParticleSystem.prototype.stop = function () {
  21420. this._stopped = true;
  21421. };
  21422. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21423. var offset = index * 11;
  21424. this._vertices[offset] = particle.position.x;
  21425. this._vertices[offset + 1] = particle.position.y;
  21426. this._vertices[offset + 2] = particle.position.z;
  21427. this._vertices[offset + 3] = particle.color.r;
  21428. this._vertices[offset + 4] = particle.color.g;
  21429. this._vertices[offset + 5] = particle.color.b;
  21430. this._vertices[offset + 6] = particle.color.a;
  21431. this._vertices[offset + 7] = particle.angle;
  21432. this._vertices[offset + 8] = particle.size;
  21433. this._vertices[offset + 9] = offsetX;
  21434. this._vertices[offset + 10] = offsetY;
  21435. };
  21436. ParticleSystem.prototype._update = function (newParticles) {
  21437. // Update current
  21438. this._alive = this.particles.length > 0;
  21439. this.updateFunction(this.particles);
  21440. // Add new ones
  21441. var worldMatrix;
  21442. if (this.emitter.position) {
  21443. worldMatrix = this.emitter.getWorldMatrix();
  21444. }
  21445. else {
  21446. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21447. }
  21448. for (var index = 0; index < newParticles; index++) {
  21449. if (this.particles.length === this._capacity) {
  21450. break;
  21451. }
  21452. if (this._stockParticles.length !== 0) {
  21453. var particle = this._stockParticles.pop();
  21454. particle.age = 0;
  21455. }
  21456. else {
  21457. particle = new BABYLON.Particle();
  21458. }
  21459. this.particles.push(particle);
  21460. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21461. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21462. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21463. particle.size = randomNumber(this.minSize, this.maxSize);
  21464. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21465. this.startPositionFunction(worldMatrix, particle.position);
  21466. var step = randomNumber(0, 1.0);
  21467. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21468. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21469. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21470. }
  21471. };
  21472. ParticleSystem.prototype._getEffect = function () {
  21473. if (this._customEffect) {
  21474. return this._customEffect;
  21475. }
  21476. ;
  21477. var defines = [];
  21478. if (this._scene.clipPlane) {
  21479. defines.push("#define CLIPPLANE");
  21480. }
  21481. // Effect
  21482. var join = defines.join("\n");
  21483. if (this._cachedDefines !== join) {
  21484. this._cachedDefines = join;
  21485. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21486. }
  21487. return this._effect;
  21488. };
  21489. ParticleSystem.prototype.animate = function () {
  21490. if (!this._started)
  21491. return;
  21492. var effect = this._getEffect();
  21493. // Check
  21494. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21495. return;
  21496. if (this._currentRenderId === this._scene.getRenderId()) {
  21497. return;
  21498. }
  21499. this._currentRenderId = this._scene.getRenderId();
  21500. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21501. // determine the number of particles we need to create
  21502. var emitCout;
  21503. if (this.manualEmitCount > -1) {
  21504. emitCout = this.manualEmitCount;
  21505. this.manualEmitCount = 0;
  21506. }
  21507. else {
  21508. emitCout = this.emitRate;
  21509. }
  21510. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21511. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21512. if (this._newPartsExcess > 1.0) {
  21513. newParticles += this._newPartsExcess >> 0;
  21514. this._newPartsExcess -= this._newPartsExcess >> 0;
  21515. }
  21516. this._alive = false;
  21517. if (!this._stopped) {
  21518. this._actualFrame += this._scaledUpdateSpeed;
  21519. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21520. this.stop();
  21521. }
  21522. else {
  21523. newParticles = 0;
  21524. }
  21525. this._update(newParticles);
  21526. // Stopped?
  21527. if (this._stopped) {
  21528. if (!this._alive) {
  21529. this._started = false;
  21530. if (this.disposeOnStop) {
  21531. this._scene._toBeDisposed.push(this);
  21532. }
  21533. }
  21534. }
  21535. // Update VBO
  21536. var offset = 0;
  21537. for (var index = 0; index < this.particles.length; index++) {
  21538. var particle = this.particles[index];
  21539. this._appendParticleVertex(offset++, particle, 0, 0);
  21540. this._appendParticleVertex(offset++, particle, 1, 0);
  21541. this._appendParticleVertex(offset++, particle, 1, 1);
  21542. this._appendParticleVertex(offset++, particle, 0, 1);
  21543. }
  21544. var engine = this._scene.getEngine();
  21545. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21546. };
  21547. ParticleSystem.prototype.render = function () {
  21548. var effect = this._getEffect();
  21549. // Check
  21550. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21551. return 0;
  21552. var engine = this._scene.getEngine();
  21553. // Render
  21554. engine.enableEffect(effect);
  21555. engine.setState(false);
  21556. var viewMatrix = this._scene.getViewMatrix();
  21557. effect.setTexture("diffuseSampler", this.particleTexture);
  21558. effect.setMatrix("view", viewMatrix);
  21559. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21560. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21561. if (this._scene.clipPlane) {
  21562. var clipPlane = this._scene.clipPlane;
  21563. var invView = viewMatrix.clone();
  21564. invView.invert();
  21565. effect.setMatrix("invView", invView);
  21566. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21567. }
  21568. // VBOs
  21569. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21570. // Draw order
  21571. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21572. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21573. }
  21574. else {
  21575. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21576. }
  21577. if (this.forceDepthWrite) {
  21578. engine.setDepthWrite(true);
  21579. }
  21580. engine.draw(true, 0, this.particles.length * 6);
  21581. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21582. return this.particles.length;
  21583. };
  21584. ParticleSystem.prototype.dispose = function () {
  21585. if (this._vertexBuffer) {
  21586. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21587. this._vertexBuffer = null;
  21588. }
  21589. if (this._indexBuffer) {
  21590. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21591. this._indexBuffer = null;
  21592. }
  21593. if (this.particleTexture) {
  21594. this.particleTexture.dispose();
  21595. this.particleTexture = null;
  21596. }
  21597. // Remove from scene
  21598. var index = this._scene.particleSystems.indexOf(this);
  21599. this._scene.particleSystems.splice(index, 1);
  21600. // Callback
  21601. if (this.onDispose) {
  21602. this.onDispose();
  21603. }
  21604. };
  21605. // Clone
  21606. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21607. var result = new ParticleSystem(name, this._capacity, this._scene);
  21608. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21609. if (newEmitter === undefined) {
  21610. newEmitter = this.emitter;
  21611. }
  21612. result.emitter = newEmitter;
  21613. if (this.particleTexture) {
  21614. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21615. }
  21616. result.start();
  21617. return result;
  21618. };
  21619. // Statics
  21620. ParticleSystem.BLENDMODE_ONEONE = 0;
  21621. ParticleSystem.BLENDMODE_STANDARD = 1;
  21622. return ParticleSystem;
  21623. })();
  21624. BABYLON.ParticleSystem = ParticleSystem;
  21625. })(BABYLON || (BABYLON = {}));
  21626. var BABYLON;
  21627. (function (BABYLON) {
  21628. var AnimationRange = (function () {
  21629. function AnimationRange(name, from, to) {
  21630. this.name = name;
  21631. this.from = from;
  21632. this.to = to;
  21633. }
  21634. return AnimationRange;
  21635. })();
  21636. BABYLON.AnimationRange = AnimationRange;
  21637. var Animation = (function () {
  21638. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21639. this.name = name;
  21640. this.targetProperty = targetProperty;
  21641. this.framePerSecond = framePerSecond;
  21642. this.dataType = dataType;
  21643. this.loopMode = loopMode;
  21644. this._offsetsCache = {};
  21645. this._highLimitsCache = {};
  21646. this._stopped = false;
  21647. this.allowMatricesInterpolation = false;
  21648. this._ranges = new Array();
  21649. this.targetPropertyPath = targetProperty.split(".");
  21650. this.dataType = dataType;
  21651. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21652. }
  21653. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21654. var dataType = undefined;
  21655. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21656. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21657. }
  21658. else if (from instanceof BABYLON.Quaternion) {
  21659. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21660. }
  21661. else if (from instanceof BABYLON.Vector3) {
  21662. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21663. }
  21664. else if (from instanceof BABYLON.Vector2) {
  21665. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21666. }
  21667. else if (from instanceof BABYLON.Color3) {
  21668. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21669. }
  21670. if (dataType == undefined) {
  21671. return null;
  21672. }
  21673. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21674. var keys = [];
  21675. keys.push({ frame: 0, value: from });
  21676. keys.push({ frame: totalFrame, value: to });
  21677. animation.setKeys(keys);
  21678. if (easingFunction !== undefined) {
  21679. animation.setEasingFunction(easingFunction);
  21680. }
  21681. return animation;
  21682. };
  21683. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21684. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21685. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21686. };
  21687. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21688. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21689. node.animations.push(animation);
  21690. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21691. };
  21692. // Methods
  21693. Animation.prototype.createRange = function (name, from, to) {
  21694. this._ranges.push(new AnimationRange(name, from, to));
  21695. };
  21696. Animation.prototype.deleteRange = function (name) {
  21697. for (var index = 0; index < this._ranges.length; index++) {
  21698. if (this._ranges[index].name === name) {
  21699. this._ranges.splice(index, 1);
  21700. return;
  21701. }
  21702. }
  21703. };
  21704. Animation.prototype.getRange = function (name) {
  21705. for (var index = 0; index < this._ranges.length; index++) {
  21706. if (this._ranges[index].name === name) {
  21707. return this._ranges[index];
  21708. }
  21709. }
  21710. return null;
  21711. };
  21712. Animation.prototype.reset = function () {
  21713. this._offsetsCache = {};
  21714. this._highLimitsCache = {};
  21715. this.currentFrame = 0;
  21716. };
  21717. Animation.prototype.isStopped = function () {
  21718. return this._stopped;
  21719. };
  21720. Animation.prototype.getKeys = function () {
  21721. return this._keys;
  21722. };
  21723. Animation.prototype.getEasingFunction = function () {
  21724. return this._easingFunction;
  21725. };
  21726. Animation.prototype.setEasingFunction = function (easingFunction) {
  21727. this._easingFunction = easingFunction;
  21728. };
  21729. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21730. return startValue + (endValue - startValue) * gradient;
  21731. };
  21732. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21733. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21734. };
  21735. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21736. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21737. };
  21738. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21739. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21740. };
  21741. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21742. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21743. };
  21744. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21745. var startScale = new BABYLON.Vector3(0, 0, 0);
  21746. var startRotation = new BABYLON.Quaternion();
  21747. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21748. startValue.decompose(startScale, startRotation, startTranslation);
  21749. var endScale = new BABYLON.Vector3(0, 0, 0);
  21750. var endRotation = new BABYLON.Quaternion();
  21751. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21752. endValue.decompose(endScale, endRotation, endTranslation);
  21753. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21754. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21755. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21756. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21757. return result;
  21758. };
  21759. Animation.prototype.clone = function () {
  21760. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21761. if (this._keys) {
  21762. clone.setKeys(this._keys);
  21763. }
  21764. return clone;
  21765. };
  21766. Animation.prototype.setKeys = function (values) {
  21767. this._keys = values.slice(0);
  21768. this._offsetsCache = {};
  21769. this._highLimitsCache = {};
  21770. };
  21771. Animation.prototype._getKeyValue = function (value) {
  21772. if (typeof value === "function") {
  21773. return value();
  21774. }
  21775. return value;
  21776. };
  21777. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21778. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21779. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21780. }
  21781. this.currentFrame = currentFrame;
  21782. // Try to get a hash to find the right key
  21783. 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));
  21784. if (this._keys[startKey].frame >= currentFrame) {
  21785. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21786. startKey--;
  21787. }
  21788. }
  21789. for (var key = startKey; key < this._keys.length; key++) {
  21790. if (this._keys[key + 1].frame >= currentFrame) {
  21791. var startValue = this._getKeyValue(this._keys[key].value);
  21792. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21793. // gradient : percent of currentFrame between the frame inf and the frame sup
  21794. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21795. // check for easingFunction and correction of gradient
  21796. if (this._easingFunction != null) {
  21797. gradient = this._easingFunction.ease(gradient);
  21798. }
  21799. switch (this.dataType) {
  21800. // Float
  21801. case Animation.ANIMATIONTYPE_FLOAT:
  21802. switch (loopMode) {
  21803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21805. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21806. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21807. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21808. }
  21809. break;
  21810. // Quaternion
  21811. case Animation.ANIMATIONTYPE_QUATERNION:
  21812. var quaternion = null;
  21813. switch (loopMode) {
  21814. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21815. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21816. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21817. break;
  21818. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21819. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21820. break;
  21821. }
  21822. return quaternion;
  21823. // Vector3
  21824. case Animation.ANIMATIONTYPE_VECTOR3:
  21825. switch (loopMode) {
  21826. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21827. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21828. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21829. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21830. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21831. }
  21832. // Vector2
  21833. case Animation.ANIMATIONTYPE_VECTOR2:
  21834. switch (loopMode) {
  21835. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21836. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21837. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21838. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21839. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21840. }
  21841. // Color3
  21842. case Animation.ANIMATIONTYPE_COLOR3:
  21843. switch (loopMode) {
  21844. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21845. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21846. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21847. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21848. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21849. }
  21850. // Matrix
  21851. case Animation.ANIMATIONTYPE_MATRIX:
  21852. switch (loopMode) {
  21853. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21854. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21855. if (this.allowMatricesInterpolation) {
  21856. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21857. }
  21858. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21859. return startValue;
  21860. }
  21861. default:
  21862. break;
  21863. }
  21864. break;
  21865. }
  21866. }
  21867. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21868. };
  21869. Animation.prototype.setValue = function (currentValue) {
  21870. // Set value
  21871. if (this.targetPropertyPath.length > 1) {
  21872. var property = this._target[this.targetPropertyPath[0]];
  21873. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21874. property = property[this.targetPropertyPath[index]];
  21875. }
  21876. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21877. }
  21878. else {
  21879. this._target[this.targetPropertyPath[0]] = currentValue;
  21880. }
  21881. if (this._target.markAsDirty) {
  21882. this._target.markAsDirty(this.targetProperty);
  21883. }
  21884. };
  21885. Animation.prototype.goToFrame = function (frame) {
  21886. if (frame < this._keys[0].frame) {
  21887. frame = this._keys[0].frame;
  21888. }
  21889. else if (frame > this._keys[this._keys.length - 1].frame) {
  21890. frame = this._keys[this._keys.length - 1].frame;
  21891. }
  21892. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21893. this.setValue(currentValue);
  21894. };
  21895. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21896. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21897. this._stopped = true;
  21898. return false;
  21899. }
  21900. var returnValue = true;
  21901. // Adding a start key at frame 0 if missing
  21902. if (this._keys[0].frame !== 0) {
  21903. var newKey = { frame: 0, value: this._keys[0].value };
  21904. this._keys.splice(0, 0, newKey);
  21905. }
  21906. // Check limits
  21907. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21908. from = this._keys[0].frame;
  21909. }
  21910. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21911. to = this._keys[this._keys.length - 1].frame;
  21912. }
  21913. // Compute ratio
  21914. var range = to - from;
  21915. var offsetValue;
  21916. // ratio represents the frame delta between from and to
  21917. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21918. var highLimitValue = 0;
  21919. if (ratio > range && !loop) {
  21920. returnValue = false;
  21921. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21922. }
  21923. else {
  21924. // Get max value if required
  21925. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21926. var keyOffset = to.toString() + from.toString();
  21927. if (!this._offsetsCache[keyOffset]) {
  21928. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21929. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21930. switch (this.dataType) {
  21931. // Float
  21932. case Animation.ANIMATIONTYPE_FLOAT:
  21933. this._offsetsCache[keyOffset] = toValue - fromValue;
  21934. break;
  21935. // Quaternion
  21936. case Animation.ANIMATIONTYPE_QUATERNION:
  21937. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21938. break;
  21939. // Vector3
  21940. case Animation.ANIMATIONTYPE_VECTOR3:
  21941. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21942. // Vector2
  21943. case Animation.ANIMATIONTYPE_VECTOR2:
  21944. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21945. // Color3
  21946. case Animation.ANIMATIONTYPE_COLOR3:
  21947. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21948. default:
  21949. break;
  21950. }
  21951. this._highLimitsCache[keyOffset] = toValue;
  21952. }
  21953. highLimitValue = this._highLimitsCache[keyOffset];
  21954. offsetValue = this._offsetsCache[keyOffset];
  21955. }
  21956. }
  21957. if (offsetValue === undefined) {
  21958. switch (this.dataType) {
  21959. // Float
  21960. case Animation.ANIMATIONTYPE_FLOAT:
  21961. offsetValue = 0;
  21962. break;
  21963. // Quaternion
  21964. case Animation.ANIMATIONTYPE_QUATERNION:
  21965. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21966. break;
  21967. // Vector3
  21968. case Animation.ANIMATIONTYPE_VECTOR3:
  21969. offsetValue = BABYLON.Vector3.Zero();
  21970. break;
  21971. // Vector2
  21972. case Animation.ANIMATIONTYPE_VECTOR2:
  21973. offsetValue = BABYLON.Vector2.Zero();
  21974. break;
  21975. // Color3
  21976. case Animation.ANIMATIONTYPE_COLOR3:
  21977. offsetValue = BABYLON.Color3.Black();
  21978. }
  21979. }
  21980. // Compute value
  21981. var repeatCount = (ratio / range) >> 0;
  21982. var currentFrame = returnValue ? from + ratio % range : to;
  21983. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21984. // Set value
  21985. this.setValue(currentValue);
  21986. if (!returnValue) {
  21987. this._stopped = true;
  21988. }
  21989. return returnValue;
  21990. };
  21991. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21992. get: function () {
  21993. return Animation._ANIMATIONTYPE_FLOAT;
  21994. },
  21995. enumerable: true,
  21996. configurable: true
  21997. });
  21998. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21999. get: function () {
  22000. return Animation._ANIMATIONTYPE_VECTOR3;
  22001. },
  22002. enumerable: true,
  22003. configurable: true
  22004. });
  22005. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22006. get: function () {
  22007. return Animation._ANIMATIONTYPE_VECTOR2;
  22008. },
  22009. enumerable: true,
  22010. configurable: true
  22011. });
  22012. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22013. get: function () {
  22014. return Animation._ANIMATIONTYPE_QUATERNION;
  22015. },
  22016. enumerable: true,
  22017. configurable: true
  22018. });
  22019. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22020. get: function () {
  22021. return Animation._ANIMATIONTYPE_MATRIX;
  22022. },
  22023. enumerable: true,
  22024. configurable: true
  22025. });
  22026. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22027. get: function () {
  22028. return Animation._ANIMATIONTYPE_COLOR3;
  22029. },
  22030. enumerable: true,
  22031. configurable: true
  22032. });
  22033. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22034. get: function () {
  22035. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22036. },
  22037. enumerable: true,
  22038. configurable: true
  22039. });
  22040. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22041. get: function () {
  22042. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22043. },
  22044. enumerable: true,
  22045. configurable: true
  22046. });
  22047. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22048. get: function () {
  22049. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22050. },
  22051. enumerable: true,
  22052. configurable: true
  22053. });
  22054. // Statics
  22055. Animation._ANIMATIONTYPE_FLOAT = 0;
  22056. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22057. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22058. Animation._ANIMATIONTYPE_MATRIX = 3;
  22059. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22060. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22061. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22062. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22063. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22064. return Animation;
  22065. })();
  22066. BABYLON.Animation = Animation;
  22067. })(BABYLON || (BABYLON = {}));
  22068. var BABYLON;
  22069. (function (BABYLON) {
  22070. var Animatable = (function () {
  22071. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22072. if (fromFrame === void 0) { fromFrame = 0; }
  22073. if (toFrame === void 0) { toFrame = 100; }
  22074. if (loopAnimation === void 0) { loopAnimation = false; }
  22075. if (speedRatio === void 0) { speedRatio = 1.0; }
  22076. this.target = target;
  22077. this.fromFrame = fromFrame;
  22078. this.toFrame = toFrame;
  22079. this.loopAnimation = loopAnimation;
  22080. this.speedRatio = speedRatio;
  22081. this.onAnimationEnd = onAnimationEnd;
  22082. this._animations = new Array();
  22083. this._paused = false;
  22084. this.animationStarted = false;
  22085. if (animations) {
  22086. this.appendAnimations(target, animations);
  22087. }
  22088. this._scene = scene;
  22089. scene._activeAnimatables.push(this);
  22090. }
  22091. // Methods
  22092. Animatable.prototype.getAnimations = function () {
  22093. return this._animations;
  22094. };
  22095. Animatable.prototype.appendAnimations = function (target, animations) {
  22096. for (var index = 0; index < animations.length; index++) {
  22097. var animation = animations[index];
  22098. animation._target = target;
  22099. this._animations.push(animation);
  22100. }
  22101. };
  22102. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22103. var animations = this._animations;
  22104. for (var index = 0; index < animations.length; index++) {
  22105. if (animations[index].targetProperty === property) {
  22106. return animations[index];
  22107. }
  22108. }
  22109. return null;
  22110. };
  22111. Animatable.prototype.reset = function () {
  22112. var animations = this._animations;
  22113. for (var index = 0; index < animations.length; index++) {
  22114. animations[index].reset();
  22115. }
  22116. this._localDelayOffset = null;
  22117. this._pausedDelay = null;
  22118. };
  22119. Animatable.prototype.goToFrame = function (frame) {
  22120. var animations = this._animations;
  22121. for (var index = 0; index < animations.length; index++) {
  22122. animations[index].goToFrame(frame);
  22123. }
  22124. };
  22125. Animatable.prototype.pause = function () {
  22126. if (this._paused) {
  22127. return;
  22128. }
  22129. this._paused = true;
  22130. };
  22131. Animatable.prototype.restart = function () {
  22132. this._paused = false;
  22133. };
  22134. Animatable.prototype.stop = function () {
  22135. var index = this._scene._activeAnimatables.indexOf(this);
  22136. if (index > -1) {
  22137. this._scene._activeAnimatables.splice(index, 1);
  22138. }
  22139. if (this.onAnimationEnd) {
  22140. this.onAnimationEnd();
  22141. }
  22142. };
  22143. Animatable.prototype._animate = function (delay) {
  22144. if (this._paused) {
  22145. this.animationStarted = false;
  22146. if (!this._pausedDelay) {
  22147. this._pausedDelay = delay;
  22148. }
  22149. return true;
  22150. }
  22151. if (!this._localDelayOffset) {
  22152. this._localDelayOffset = delay;
  22153. }
  22154. else if (this._pausedDelay) {
  22155. this._localDelayOffset += delay - this._pausedDelay;
  22156. this._pausedDelay = null;
  22157. }
  22158. // Animating
  22159. var running = false;
  22160. var animations = this._animations;
  22161. var index;
  22162. for (index = 0; index < animations.length; index++) {
  22163. var animation = animations[index];
  22164. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22165. running = running || isRunning;
  22166. }
  22167. this.animationStarted = running;
  22168. if (!running) {
  22169. // Remove from active animatables
  22170. index = this._scene._activeAnimatables.indexOf(this);
  22171. this._scene._activeAnimatables.splice(index, 1);
  22172. }
  22173. if (!running && this.onAnimationEnd) {
  22174. this.onAnimationEnd();
  22175. }
  22176. return running;
  22177. };
  22178. return Animatable;
  22179. })();
  22180. BABYLON.Animatable = Animatable;
  22181. })(BABYLON || (BABYLON = {}));
  22182. var BABYLON;
  22183. (function (BABYLON) {
  22184. var EasingFunction = (function () {
  22185. function EasingFunction() {
  22186. // Properties
  22187. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22188. }
  22189. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22190. get: function () {
  22191. return EasingFunction._EASINGMODE_EASEIN;
  22192. },
  22193. enumerable: true,
  22194. configurable: true
  22195. });
  22196. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22197. get: function () {
  22198. return EasingFunction._EASINGMODE_EASEOUT;
  22199. },
  22200. enumerable: true,
  22201. configurable: true
  22202. });
  22203. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22204. get: function () {
  22205. return EasingFunction._EASINGMODE_EASEINOUT;
  22206. },
  22207. enumerable: true,
  22208. configurable: true
  22209. });
  22210. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22211. var n = Math.min(Math.max(easingMode, 0), 2);
  22212. this._easingMode = n;
  22213. };
  22214. EasingFunction.prototype.getEasingMode = function () {
  22215. return this._easingMode;
  22216. };
  22217. EasingFunction.prototype.easeInCore = function (gradient) {
  22218. throw new Error('You must implement this method');
  22219. };
  22220. EasingFunction.prototype.ease = function (gradient) {
  22221. switch (this._easingMode) {
  22222. case EasingFunction.EASINGMODE_EASEIN:
  22223. return this.easeInCore(gradient);
  22224. case EasingFunction.EASINGMODE_EASEOUT:
  22225. return (1 - this.easeInCore(1 - gradient));
  22226. }
  22227. if (gradient >= 0.5) {
  22228. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22229. }
  22230. return (this.easeInCore(gradient * 2) * 0.5);
  22231. };
  22232. //Statics
  22233. EasingFunction._EASINGMODE_EASEIN = 0;
  22234. EasingFunction._EASINGMODE_EASEOUT = 1;
  22235. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22236. return EasingFunction;
  22237. })();
  22238. BABYLON.EasingFunction = EasingFunction;
  22239. var CircleEase = (function (_super) {
  22240. __extends(CircleEase, _super);
  22241. function CircleEase() {
  22242. _super.apply(this, arguments);
  22243. }
  22244. CircleEase.prototype.easeInCore = function (gradient) {
  22245. gradient = Math.max(0, Math.min(1, gradient));
  22246. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22247. };
  22248. return CircleEase;
  22249. })(EasingFunction);
  22250. BABYLON.CircleEase = CircleEase;
  22251. var BackEase = (function (_super) {
  22252. __extends(BackEase, _super);
  22253. function BackEase(amplitude) {
  22254. if (amplitude === void 0) { amplitude = 1; }
  22255. _super.call(this);
  22256. this.amplitude = amplitude;
  22257. }
  22258. BackEase.prototype.easeInCore = function (gradient) {
  22259. var num = Math.max(0, this.amplitude);
  22260. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22261. };
  22262. return BackEase;
  22263. })(EasingFunction);
  22264. BABYLON.BackEase = BackEase;
  22265. var BounceEase = (function (_super) {
  22266. __extends(BounceEase, _super);
  22267. function BounceEase(bounces, bounciness) {
  22268. if (bounces === void 0) { bounces = 3; }
  22269. if (bounciness === void 0) { bounciness = 2; }
  22270. _super.call(this);
  22271. this.bounces = bounces;
  22272. this.bounciness = bounciness;
  22273. }
  22274. BounceEase.prototype.easeInCore = function (gradient) {
  22275. var y = Math.max(0.0, this.bounces);
  22276. var bounciness = this.bounciness;
  22277. if (bounciness <= 1.0) {
  22278. bounciness = 1.001;
  22279. }
  22280. var num9 = Math.pow(bounciness, y);
  22281. var num5 = 1.0 - bounciness;
  22282. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22283. var num15 = gradient * num4;
  22284. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22285. var num3 = Math.floor(num65);
  22286. var num13 = num3 + 1.0;
  22287. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22288. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22289. var num7 = (num8 + num12) * 0.5;
  22290. var num6 = gradient - num7;
  22291. var num2 = num7 - num8;
  22292. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22293. };
  22294. return BounceEase;
  22295. })(EasingFunction);
  22296. BABYLON.BounceEase = BounceEase;
  22297. var CubicEase = (function (_super) {
  22298. __extends(CubicEase, _super);
  22299. function CubicEase() {
  22300. _super.apply(this, arguments);
  22301. }
  22302. CubicEase.prototype.easeInCore = function (gradient) {
  22303. return (gradient * gradient * gradient);
  22304. };
  22305. return CubicEase;
  22306. })(EasingFunction);
  22307. BABYLON.CubicEase = CubicEase;
  22308. var ElasticEase = (function (_super) {
  22309. __extends(ElasticEase, _super);
  22310. function ElasticEase(oscillations, springiness) {
  22311. if (oscillations === void 0) { oscillations = 3; }
  22312. if (springiness === void 0) { springiness = 3; }
  22313. _super.call(this);
  22314. this.oscillations = oscillations;
  22315. this.springiness = springiness;
  22316. }
  22317. ElasticEase.prototype.easeInCore = function (gradient) {
  22318. var num2;
  22319. var num3 = Math.max(0.0, this.oscillations);
  22320. var num = Math.max(0.0, this.springiness);
  22321. if (num == 0) {
  22322. num2 = gradient;
  22323. }
  22324. else {
  22325. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22326. }
  22327. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22328. };
  22329. return ElasticEase;
  22330. })(EasingFunction);
  22331. BABYLON.ElasticEase = ElasticEase;
  22332. var ExponentialEase = (function (_super) {
  22333. __extends(ExponentialEase, _super);
  22334. function ExponentialEase(exponent) {
  22335. if (exponent === void 0) { exponent = 2; }
  22336. _super.call(this);
  22337. this.exponent = exponent;
  22338. }
  22339. ExponentialEase.prototype.easeInCore = function (gradient) {
  22340. if (this.exponent <= 0) {
  22341. return gradient;
  22342. }
  22343. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22344. };
  22345. return ExponentialEase;
  22346. })(EasingFunction);
  22347. BABYLON.ExponentialEase = ExponentialEase;
  22348. var PowerEase = (function (_super) {
  22349. __extends(PowerEase, _super);
  22350. function PowerEase(power) {
  22351. if (power === void 0) { power = 2; }
  22352. _super.call(this);
  22353. this.power = power;
  22354. }
  22355. PowerEase.prototype.easeInCore = function (gradient) {
  22356. var y = Math.max(0.0, this.power);
  22357. return Math.pow(gradient, y);
  22358. };
  22359. return PowerEase;
  22360. })(EasingFunction);
  22361. BABYLON.PowerEase = PowerEase;
  22362. var QuadraticEase = (function (_super) {
  22363. __extends(QuadraticEase, _super);
  22364. function QuadraticEase() {
  22365. _super.apply(this, arguments);
  22366. }
  22367. QuadraticEase.prototype.easeInCore = function (gradient) {
  22368. return (gradient * gradient);
  22369. };
  22370. return QuadraticEase;
  22371. })(EasingFunction);
  22372. BABYLON.QuadraticEase = QuadraticEase;
  22373. var QuarticEase = (function (_super) {
  22374. __extends(QuarticEase, _super);
  22375. function QuarticEase() {
  22376. _super.apply(this, arguments);
  22377. }
  22378. QuarticEase.prototype.easeInCore = function (gradient) {
  22379. return (gradient * gradient * gradient * gradient);
  22380. };
  22381. return QuarticEase;
  22382. })(EasingFunction);
  22383. BABYLON.QuarticEase = QuarticEase;
  22384. var QuinticEase = (function (_super) {
  22385. __extends(QuinticEase, _super);
  22386. function QuinticEase() {
  22387. _super.apply(this, arguments);
  22388. }
  22389. QuinticEase.prototype.easeInCore = function (gradient) {
  22390. return (gradient * gradient * gradient * gradient * gradient);
  22391. };
  22392. return QuinticEase;
  22393. })(EasingFunction);
  22394. BABYLON.QuinticEase = QuinticEase;
  22395. var SineEase = (function (_super) {
  22396. __extends(SineEase, _super);
  22397. function SineEase() {
  22398. _super.apply(this, arguments);
  22399. }
  22400. SineEase.prototype.easeInCore = function (gradient) {
  22401. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22402. };
  22403. return SineEase;
  22404. })(EasingFunction);
  22405. BABYLON.SineEase = SineEase;
  22406. var BezierCurveEase = (function (_super) {
  22407. __extends(BezierCurveEase, _super);
  22408. function BezierCurveEase(x1, y1, x2, y2) {
  22409. if (x1 === void 0) { x1 = 0; }
  22410. if (y1 === void 0) { y1 = 0; }
  22411. if (x2 === void 0) { x2 = 1; }
  22412. if (y2 === void 0) { y2 = 1; }
  22413. _super.call(this);
  22414. this.x1 = x1;
  22415. this.y1 = y1;
  22416. this.x2 = x2;
  22417. this.y2 = y2;
  22418. }
  22419. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22420. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22421. };
  22422. return BezierCurveEase;
  22423. })(EasingFunction);
  22424. BABYLON.BezierCurveEase = BezierCurveEase;
  22425. })(BABYLON || (BABYLON = {}));
  22426. var BABYLON;
  22427. (function (BABYLON) {
  22428. var Bone = (function (_super) {
  22429. __extends(Bone, _super);
  22430. function Bone(name, skeleton, parentBone, matrix) {
  22431. _super.call(this, name, skeleton.getScene());
  22432. this.name = name;
  22433. this.children = new Array();
  22434. this.animations = new Array();
  22435. this._worldTransform = new BABYLON.Matrix();
  22436. this._absoluteTransform = new BABYLON.Matrix();
  22437. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22438. this._skeleton = skeleton;
  22439. this._matrix = matrix;
  22440. this._baseMatrix = matrix;
  22441. skeleton.bones.push(this);
  22442. if (parentBone) {
  22443. this._parent = parentBone;
  22444. parentBone.children.push(this);
  22445. }
  22446. else {
  22447. this._parent = null;
  22448. }
  22449. this._updateDifferenceMatrix();
  22450. }
  22451. // Members
  22452. Bone.prototype.getParent = function () {
  22453. return this._parent;
  22454. };
  22455. Bone.prototype.getLocalMatrix = function () {
  22456. return this._matrix;
  22457. };
  22458. Bone.prototype.getBaseMatrix = function () {
  22459. return this._baseMatrix;
  22460. };
  22461. Bone.prototype.getWorldMatrix = function () {
  22462. return this._worldTransform;
  22463. };
  22464. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22465. return this._invertedAbsoluteTransform;
  22466. };
  22467. Bone.prototype.getAbsoluteMatrix = function () {
  22468. var matrix = this._matrix.clone();
  22469. var parent = this._parent;
  22470. while (parent) {
  22471. matrix = matrix.multiply(parent.getLocalMatrix());
  22472. parent = parent.getParent();
  22473. }
  22474. return matrix;
  22475. };
  22476. // Methods
  22477. Bone.prototype.updateMatrix = function (matrix) {
  22478. this._matrix = matrix;
  22479. this._skeleton._markAsDirty();
  22480. this._updateDifferenceMatrix();
  22481. };
  22482. Bone.prototype._updateDifferenceMatrix = function () {
  22483. if (this._parent) {
  22484. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22485. }
  22486. else {
  22487. this._absoluteTransform.copyFrom(this._matrix);
  22488. }
  22489. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22490. for (var index = 0; index < this.children.length; index++) {
  22491. this.children[index]._updateDifferenceMatrix();
  22492. }
  22493. };
  22494. Bone.prototype.markAsDirty = function () {
  22495. this._currentRenderId++;
  22496. this._skeleton._markAsDirty();
  22497. };
  22498. return Bone;
  22499. })(BABYLON.Node);
  22500. BABYLON.Bone = Bone;
  22501. })(BABYLON || (BABYLON = {}));
  22502. var BABYLON;
  22503. (function (BABYLON) {
  22504. var Skeleton = (function () {
  22505. function Skeleton(name, id, scene) {
  22506. this.name = name;
  22507. this.id = id;
  22508. this.bones = new Array();
  22509. this._isDirty = true;
  22510. this._identity = BABYLON.Matrix.Identity();
  22511. this._ranges = new Array();
  22512. this.bones = [];
  22513. this._scene = scene;
  22514. scene.skeletons.push(this);
  22515. this.prepare();
  22516. //make sure it will recalculate the matrix next time prepare is called.
  22517. this._isDirty = true;
  22518. }
  22519. // Members
  22520. Skeleton.prototype.getTransformMatrices = function () {
  22521. return this._transformMatrices;
  22522. };
  22523. Skeleton.prototype.getScene = function () {
  22524. return this._scene;
  22525. };
  22526. // Methods
  22527. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22528. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22529. };
  22530. Skeleton.prototype.deleteAnimationRange = function (name) {
  22531. for (var index = 0; index < this._ranges.length; index++) {
  22532. if (this._ranges[index].name === name) {
  22533. this._ranges.splice(index, 1);
  22534. return;
  22535. }
  22536. }
  22537. };
  22538. Skeleton.prototype.getAnimationRange = function (name) {
  22539. for (var index = 0; index < this._ranges.length; index++) {
  22540. if (this._ranges[index].name === name) {
  22541. return this._ranges[index];
  22542. }
  22543. }
  22544. return null;
  22545. };
  22546. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22547. var range = this.getAnimationRange(name);
  22548. if (!range) {
  22549. return null;
  22550. }
  22551. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22552. };
  22553. Skeleton.prototype._markAsDirty = function () {
  22554. this._isDirty = true;
  22555. };
  22556. Skeleton.prototype.prepare = function () {
  22557. if (!this._isDirty) {
  22558. return;
  22559. }
  22560. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22561. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22562. }
  22563. for (var index = 0; index < this.bones.length; index++) {
  22564. var bone = this.bones[index];
  22565. var parentBone = bone.getParent();
  22566. if (parentBone) {
  22567. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22568. }
  22569. else {
  22570. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22571. }
  22572. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22573. }
  22574. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22575. this._isDirty = false;
  22576. this._scene._activeBones += this.bones.length;
  22577. };
  22578. Skeleton.prototype.getAnimatables = function () {
  22579. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22580. this._animatables = [];
  22581. for (var index = 0; index < this.bones.length; index++) {
  22582. this._animatables.push(this.bones[index]);
  22583. }
  22584. }
  22585. return this._animatables;
  22586. };
  22587. Skeleton.prototype.clone = function (name, id) {
  22588. var result = new Skeleton(name, id || name, this._scene);
  22589. for (var index = 0; index < this.bones.length; index++) {
  22590. var source = this.bones[index];
  22591. var parentBone = null;
  22592. if (source.getParent()) {
  22593. var parentIndex = this.bones.indexOf(source.getParent());
  22594. parentBone = result.bones[parentIndex];
  22595. }
  22596. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22597. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22598. }
  22599. return result;
  22600. };
  22601. Skeleton.prototype.dispose = function () {
  22602. // Animations
  22603. this.getScene().stopAnimation(this);
  22604. // Remove from scene
  22605. this.getScene().removeSkeleton(this);
  22606. };
  22607. return Skeleton;
  22608. })();
  22609. BABYLON.Skeleton = Skeleton;
  22610. })(BABYLON || (BABYLON = {}));
  22611. var BABYLON;
  22612. (function (BABYLON) {
  22613. var PostProcess = (function () {
  22614. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22616. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22617. this.name = name;
  22618. this.width = -1;
  22619. this.height = -1;
  22620. this._reusable = false;
  22621. this._textures = new BABYLON.SmartArray(2);
  22622. this._currentRenderTextureInd = 0;
  22623. if (camera != null) {
  22624. this._camera = camera;
  22625. this._scene = camera.getScene();
  22626. camera.attachPostProcess(this);
  22627. this._engine = this._scene.getEngine();
  22628. }
  22629. else {
  22630. this._engine = engine;
  22631. }
  22632. this._renderRatio = ratio;
  22633. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22634. this._reusable = reusable || false;
  22635. this._textureType = textureType;
  22636. this._samplers = samplers || [];
  22637. this._samplers.push("textureSampler");
  22638. this._fragmentUrl = fragmentUrl;
  22639. this._parameters = parameters || [];
  22640. this.updateEffect(defines);
  22641. }
  22642. PostProcess.prototype.updateEffect = function (defines) {
  22643. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22644. };
  22645. PostProcess.prototype.isReusable = function () {
  22646. return this._reusable;
  22647. };
  22648. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22649. camera = camera || this._camera;
  22650. var scene = camera.getScene();
  22651. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22652. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22653. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22654. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22655. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22656. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22657. if (this._textures.length > 0) {
  22658. for (var i = 0; i < this._textures.length; i++) {
  22659. this._engine._releaseTexture(this._textures.data[i]);
  22660. }
  22661. this._textures.reset();
  22662. }
  22663. this.width = desiredWidth;
  22664. this.height = desiredHeight;
  22665. 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 }));
  22666. if (this._reusable) {
  22667. 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 }));
  22668. }
  22669. if (this.onSizeChanged) {
  22670. this.onSizeChanged();
  22671. }
  22672. }
  22673. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22674. if (this.onActivate) {
  22675. this.onActivate(camera);
  22676. }
  22677. // Clear
  22678. if (this.clearColor) {
  22679. this._engine.clear(this.clearColor, true, true);
  22680. }
  22681. else {
  22682. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22683. }
  22684. if (this._reusable) {
  22685. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22686. }
  22687. };
  22688. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22689. get: function () {
  22690. return this._effect.isSupported;
  22691. },
  22692. enumerable: true,
  22693. configurable: true
  22694. });
  22695. PostProcess.prototype.apply = function () {
  22696. // Check
  22697. if (!this._effect.isReady())
  22698. return null;
  22699. // States
  22700. this._engine.enableEffect(this._effect);
  22701. this._engine.setState(false);
  22702. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22703. this._engine.setDepthBuffer(false);
  22704. this._engine.setDepthWrite(false);
  22705. // Texture
  22706. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22707. // Parameters
  22708. if (this.onApply) {
  22709. this.onApply(this._effect);
  22710. }
  22711. return this._effect;
  22712. };
  22713. PostProcess.prototype.dispose = function (camera) {
  22714. camera = camera || this._camera;
  22715. if (this._textures.length > 0) {
  22716. for (var i = 0; i < this._textures.length; i++) {
  22717. this._engine._releaseTexture(this._textures.data[i]);
  22718. }
  22719. this._textures.reset();
  22720. }
  22721. if (!camera) {
  22722. return;
  22723. }
  22724. camera.detachPostProcess(this);
  22725. var index = camera._postProcesses.indexOf(this);
  22726. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22727. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22728. }
  22729. };
  22730. return PostProcess;
  22731. })();
  22732. BABYLON.PostProcess = PostProcess;
  22733. })(BABYLON || (BABYLON = {}));
  22734. var BABYLON;
  22735. (function (BABYLON) {
  22736. var PostProcessManager = (function () {
  22737. function PostProcessManager(scene) {
  22738. this._vertexDeclaration = [2];
  22739. this._vertexStrideSize = 2 * 4;
  22740. this._scene = scene;
  22741. }
  22742. PostProcessManager.prototype._prepareBuffers = function () {
  22743. if (this._vertexBuffer) {
  22744. return;
  22745. }
  22746. // VBO
  22747. var vertices = [];
  22748. vertices.push(1, 1);
  22749. vertices.push(-1, 1);
  22750. vertices.push(-1, -1);
  22751. vertices.push(1, -1);
  22752. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22753. // Indices
  22754. var indices = [];
  22755. indices.push(0);
  22756. indices.push(1);
  22757. indices.push(2);
  22758. indices.push(0);
  22759. indices.push(2);
  22760. indices.push(3);
  22761. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22762. };
  22763. // Methods
  22764. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22765. var postProcesses = this._scene.activeCamera._postProcesses;
  22766. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22767. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22768. return false;
  22769. }
  22770. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22771. return true;
  22772. };
  22773. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22774. var engine = this._scene.getEngine();
  22775. for (var index = 0; index < postProcesses.length; index++) {
  22776. if (index < postProcesses.length - 1) {
  22777. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22778. }
  22779. else {
  22780. if (targetTexture) {
  22781. engine.bindFramebuffer(targetTexture);
  22782. }
  22783. else {
  22784. engine.restoreDefaultFramebuffer();
  22785. }
  22786. }
  22787. var pp = postProcesses[index];
  22788. var effect = pp.apply();
  22789. if (effect) {
  22790. if (pp.onBeforeRender) {
  22791. pp.onBeforeRender(effect);
  22792. }
  22793. // VBOs
  22794. this._prepareBuffers();
  22795. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22796. // Draw order
  22797. engine.draw(true, 0, 6);
  22798. if (pp.onAfterRender) {
  22799. pp.onAfterRender(effect);
  22800. }
  22801. }
  22802. }
  22803. // Restore depth buffer
  22804. engine.setDepthBuffer(true);
  22805. engine.setDepthWrite(true);
  22806. };
  22807. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22808. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22809. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22810. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22811. return;
  22812. }
  22813. var engine = this._scene.getEngine();
  22814. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22815. if (index < postProcessesTakenIndices.length - 1) {
  22816. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22817. }
  22818. else {
  22819. if (targetTexture) {
  22820. engine.bindFramebuffer(targetTexture, faceIndex);
  22821. }
  22822. else {
  22823. engine.restoreDefaultFramebuffer();
  22824. }
  22825. }
  22826. if (doNotPresent) {
  22827. break;
  22828. }
  22829. var pp = postProcesses[postProcessesTakenIndices[index]];
  22830. var effect = pp.apply();
  22831. if (effect) {
  22832. if (pp.onBeforeRender) {
  22833. pp.onBeforeRender(effect);
  22834. }
  22835. // VBOs
  22836. this._prepareBuffers();
  22837. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22838. // Draw order
  22839. engine.draw(true, 0, 6);
  22840. if (pp.onAfterRender) {
  22841. pp.onAfterRender(effect);
  22842. }
  22843. }
  22844. }
  22845. // Restore depth buffer
  22846. engine.setDepthBuffer(true);
  22847. engine.setDepthWrite(true);
  22848. };
  22849. PostProcessManager.prototype.dispose = function () {
  22850. if (this._vertexBuffer) {
  22851. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22852. this._vertexBuffer = null;
  22853. }
  22854. if (this._indexBuffer) {
  22855. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22856. this._indexBuffer = null;
  22857. }
  22858. };
  22859. return PostProcessManager;
  22860. })();
  22861. BABYLON.PostProcessManager = PostProcessManager;
  22862. })(BABYLON || (BABYLON = {}));
  22863. var BABYLON;
  22864. (function (BABYLON) {
  22865. var PassPostProcess = (function (_super) {
  22866. __extends(PassPostProcess, _super);
  22867. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22868. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22869. }
  22870. return PassPostProcess;
  22871. })(BABYLON.PostProcess);
  22872. BABYLON.PassPostProcess = PassPostProcess;
  22873. })(BABYLON || (BABYLON = {}));
  22874. var BABYLON;
  22875. (function (BABYLON) {
  22876. var PhysicsEngine = (function () {
  22877. function PhysicsEngine(plugin) {
  22878. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22879. }
  22880. PhysicsEngine.prototype._initialize = function (gravity) {
  22881. this._currentPlugin.initialize();
  22882. this._setGravity(gravity);
  22883. };
  22884. PhysicsEngine.prototype._runOneStep = function (delta) {
  22885. if (delta > 0.1) {
  22886. delta = 0.1;
  22887. }
  22888. else if (delta <= 0) {
  22889. delta = 1.0 / 60.0;
  22890. }
  22891. this._currentPlugin.runOneStep(delta);
  22892. };
  22893. PhysicsEngine.prototype._setGravity = function (gravity) {
  22894. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22895. this._currentPlugin.setGravity(this.gravity);
  22896. };
  22897. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22898. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22899. };
  22900. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22901. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22902. };
  22903. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22904. this._currentPlugin.unregisterMesh(mesh);
  22905. };
  22906. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22907. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22908. };
  22909. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22910. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22911. };
  22912. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22913. this._currentPlugin.updateBodyPosition(mesh);
  22914. };
  22915. PhysicsEngine.prototype.dispose = function () {
  22916. this._currentPlugin.dispose();
  22917. };
  22918. PhysicsEngine.prototype.isSupported = function () {
  22919. return this._currentPlugin.isSupported();
  22920. };
  22921. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22922. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22923. };
  22924. // Statics
  22925. PhysicsEngine.NoImpostor = 0;
  22926. PhysicsEngine.SphereImpostor = 1;
  22927. PhysicsEngine.BoxImpostor = 2;
  22928. PhysicsEngine.PlaneImpostor = 3;
  22929. PhysicsEngine.MeshImpostor = 4;
  22930. PhysicsEngine.CapsuleImpostor = 5;
  22931. PhysicsEngine.ConeImpostor = 6;
  22932. PhysicsEngine.CylinderImpostor = 7;
  22933. PhysicsEngine.ConvexHullImpostor = 8;
  22934. PhysicsEngine.HeightmapImpostor = 9;
  22935. PhysicsEngine.Epsilon = 0.001;
  22936. return PhysicsEngine;
  22937. })();
  22938. BABYLON.PhysicsEngine = PhysicsEngine;
  22939. })(BABYLON || (BABYLON = {}));
  22940. var BABYLON;
  22941. (function (BABYLON) {
  22942. var VertexData = (function () {
  22943. function VertexData() {
  22944. }
  22945. VertexData.prototype.set = function (data, kind) {
  22946. switch (kind) {
  22947. case BABYLON.VertexBuffer.PositionKind:
  22948. this.positions = data;
  22949. break;
  22950. case BABYLON.VertexBuffer.NormalKind:
  22951. this.normals = data;
  22952. break;
  22953. case BABYLON.VertexBuffer.UVKind:
  22954. this.uvs = data;
  22955. break;
  22956. case BABYLON.VertexBuffer.UV2Kind:
  22957. this.uvs2 = data;
  22958. break;
  22959. case BABYLON.VertexBuffer.UV3Kind:
  22960. this.uvs3 = data;
  22961. break;
  22962. case BABYLON.VertexBuffer.UV4Kind:
  22963. this.uvs4 = data;
  22964. break;
  22965. case BABYLON.VertexBuffer.UV5Kind:
  22966. this.uvs5 = data;
  22967. break;
  22968. case BABYLON.VertexBuffer.UV6Kind:
  22969. this.uvs6 = data;
  22970. break;
  22971. case BABYLON.VertexBuffer.ColorKind:
  22972. this.colors = data;
  22973. break;
  22974. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22975. this.matricesIndices = data;
  22976. break;
  22977. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22978. this.matricesWeights = data;
  22979. break;
  22980. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22981. this.matricesIndicesExtra = data;
  22982. break;
  22983. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22984. this.matricesWeightsExtra = data;
  22985. break;
  22986. }
  22987. };
  22988. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22989. this._applyTo(mesh, updatable);
  22990. };
  22991. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22992. this._applyTo(geometry, updatable);
  22993. };
  22994. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22995. this._update(mesh);
  22996. };
  22997. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22998. this._update(geometry);
  22999. };
  23000. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23001. if (this.positions) {
  23002. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23003. }
  23004. if (this.normals) {
  23005. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23006. }
  23007. if (this.uvs) {
  23008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23009. }
  23010. if (this.uvs2) {
  23011. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23012. }
  23013. if (this.uvs3) {
  23014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23015. }
  23016. if (this.uvs4) {
  23017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23018. }
  23019. if (this.uvs5) {
  23020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23021. }
  23022. if (this.uvs6) {
  23023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23024. }
  23025. if (this.colors) {
  23026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23027. }
  23028. if (this.matricesIndices) {
  23029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23030. }
  23031. if (this.matricesWeights) {
  23032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23033. }
  23034. if (this.matricesIndicesExtra) {
  23035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23036. }
  23037. if (this.matricesWeightsExtra) {
  23038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23039. }
  23040. if (this.indices) {
  23041. meshOrGeometry.setIndices(this.indices);
  23042. }
  23043. };
  23044. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23045. if (this.positions) {
  23046. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23047. }
  23048. if (this.normals) {
  23049. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23050. }
  23051. if (this.uvs) {
  23052. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23053. }
  23054. if (this.uvs2) {
  23055. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23056. }
  23057. if (this.uvs3) {
  23058. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23059. }
  23060. if (this.uvs4) {
  23061. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23062. }
  23063. if (this.uvs5) {
  23064. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23065. }
  23066. if (this.uvs6) {
  23067. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23068. }
  23069. if (this.colors) {
  23070. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23071. }
  23072. if (this.matricesIndices) {
  23073. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23074. }
  23075. if (this.matricesWeights) {
  23076. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23077. }
  23078. if (this.matricesIndicesExtra) {
  23079. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23080. }
  23081. if (this.matricesWeightsExtra) {
  23082. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23083. }
  23084. if (this.indices) {
  23085. meshOrGeometry.setIndices(this.indices);
  23086. }
  23087. };
  23088. VertexData.prototype.transform = function (matrix) {
  23089. var transformed = BABYLON.Vector3.Zero();
  23090. var index;
  23091. if (this.positions) {
  23092. var position = BABYLON.Vector3.Zero();
  23093. for (index = 0; index < this.positions.length; index += 3) {
  23094. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23095. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23096. this.positions[index] = transformed.x;
  23097. this.positions[index + 1] = transformed.y;
  23098. this.positions[index + 2] = transformed.z;
  23099. }
  23100. }
  23101. if (this.normals) {
  23102. var normal = BABYLON.Vector3.Zero();
  23103. for (index = 0; index < this.normals.length; index += 3) {
  23104. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23105. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23106. this.normals[index] = transformed.x;
  23107. this.normals[index + 1] = transformed.y;
  23108. this.normals[index + 2] = transformed.z;
  23109. }
  23110. }
  23111. };
  23112. VertexData.prototype.merge = function (other) {
  23113. var index;
  23114. if (other.indices) {
  23115. if (!this.indices) {
  23116. this.indices = [];
  23117. }
  23118. var offset = this.positions ? this.positions.length / 3 : 0;
  23119. for (index = 0; index < other.indices.length; index++) {
  23120. this.indices.push(other.indices[index] + offset);
  23121. }
  23122. }
  23123. if (other.positions) {
  23124. if (!this.positions) {
  23125. this.positions = [];
  23126. }
  23127. for (index = 0; index < other.positions.length; index++) {
  23128. this.positions.push(other.positions[index]);
  23129. }
  23130. }
  23131. if (other.normals) {
  23132. if (!this.normals) {
  23133. this.normals = [];
  23134. }
  23135. for (index = 0; index < other.normals.length; index++) {
  23136. this.normals.push(other.normals[index]);
  23137. }
  23138. }
  23139. if (other.uvs) {
  23140. if (!this.uvs) {
  23141. this.uvs = [];
  23142. }
  23143. for (index = 0; index < other.uvs.length; index++) {
  23144. this.uvs.push(other.uvs[index]);
  23145. }
  23146. }
  23147. if (other.uvs2) {
  23148. if (!this.uvs2) {
  23149. this.uvs2 = [];
  23150. }
  23151. for (index = 0; index < other.uvs2.length; index++) {
  23152. this.uvs2.push(other.uvs2[index]);
  23153. }
  23154. }
  23155. if (other.uvs3) {
  23156. if (!this.uvs3) {
  23157. this.uvs3 = [];
  23158. }
  23159. for (index = 0; index < other.uvs3.length; index++) {
  23160. this.uvs3.push(other.uvs3[index]);
  23161. }
  23162. }
  23163. if (other.uvs4) {
  23164. if (!this.uvs4) {
  23165. this.uvs4 = [];
  23166. }
  23167. for (index = 0; index < other.uvs4.length; index++) {
  23168. this.uvs4.push(other.uvs4[index]);
  23169. }
  23170. }
  23171. if (other.uvs5) {
  23172. if (!this.uvs5) {
  23173. this.uvs5 = [];
  23174. }
  23175. for (index = 0; index < other.uvs5.length; index++) {
  23176. this.uvs5.push(other.uvs5[index]);
  23177. }
  23178. }
  23179. if (other.uvs6) {
  23180. if (!this.uvs6) {
  23181. this.uvs6 = [];
  23182. }
  23183. for (index = 0; index < other.uvs6.length; index++) {
  23184. this.uvs6.push(other.uvs6[index]);
  23185. }
  23186. }
  23187. if (other.matricesIndices) {
  23188. if (!this.matricesIndices) {
  23189. this.matricesIndices = [];
  23190. }
  23191. for (index = 0; index < other.matricesIndices.length; index++) {
  23192. this.matricesIndices.push(other.matricesIndices[index]);
  23193. }
  23194. }
  23195. if (other.matricesWeights) {
  23196. if (!this.matricesWeights) {
  23197. this.matricesWeights = [];
  23198. }
  23199. for (index = 0; index < other.matricesWeights.length; index++) {
  23200. this.matricesWeights.push(other.matricesWeights[index]);
  23201. }
  23202. }
  23203. if (other.matricesIndicesExtra) {
  23204. if (!this.matricesIndicesExtra) {
  23205. this.matricesIndicesExtra = [];
  23206. }
  23207. for (index = 0; index < other.matricesIndicesExtra.length; index++) {
  23208. this.matricesIndicesExtra.push(other.matricesIndicesExtra[index]);
  23209. }
  23210. }
  23211. if (other.matricesWeightsExtra) {
  23212. if (!this.matricesWeightsExtra) {
  23213. this.matricesWeightsExtra = [];
  23214. }
  23215. for (index = 0; index < other.matricesWeightsExtra.length; index++) {
  23216. this.matricesWeightsExtra.push(other.matricesWeightsExtra[index]);
  23217. }
  23218. }
  23219. if (other.colors) {
  23220. if (!this.colors) {
  23221. this.colors = [];
  23222. }
  23223. for (index = 0; index < other.colors.length; index++) {
  23224. this.colors.push(other.colors[index]);
  23225. }
  23226. }
  23227. };
  23228. // Statics
  23229. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23230. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23231. };
  23232. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23233. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23234. };
  23235. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23236. var result = new VertexData();
  23237. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23238. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23239. }
  23240. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23241. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23242. }
  23243. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23244. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23245. }
  23246. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23247. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23248. }
  23249. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23250. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23251. }
  23252. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23253. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23254. }
  23255. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23256. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23257. }
  23258. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23259. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23260. }
  23261. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23262. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23263. }
  23264. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23265. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23266. }
  23267. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23268. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23269. }
  23270. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23271. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23272. }
  23273. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23274. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23275. }
  23276. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23277. return result;
  23278. };
  23279. VertexData.CreateRibbon = function (options) {
  23280. var pathArray = options.pathArray;
  23281. var closeArray = options.closeArray || false;
  23282. var closePath = options.closePath || false;
  23283. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23284. var offset = options.offset || defaultOffset;
  23285. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23286. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23287. var positions = [];
  23288. var indices = [];
  23289. var normals = [];
  23290. var uvs = [];
  23291. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23292. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23293. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23294. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23295. var minlg; // minimal length among all paths from pathArray
  23296. var lg = []; // array of path lengths : nb of vertex per path
  23297. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23298. var p; // path iterator
  23299. var i; // point iterator
  23300. var j; // point iterator
  23301. // if single path in pathArray
  23302. if (pathArray.length < 2) {
  23303. var ar1 = [];
  23304. var ar2 = [];
  23305. for (i = 0; i < pathArray[0].length - offset; i++) {
  23306. ar1.push(pathArray[0][i]);
  23307. ar2.push(pathArray[0][i + offset]);
  23308. }
  23309. pathArray = [ar1, ar2];
  23310. }
  23311. // positions and horizontal distances (u)
  23312. var idc = 0;
  23313. var closePathCorr = (closePath) ? 1 : 0;
  23314. var path;
  23315. var l;
  23316. minlg = pathArray[0].length;
  23317. var vectlg;
  23318. var dist;
  23319. for (p = 0; p < pathArray.length; p++) {
  23320. uTotalDistance[p] = 0;
  23321. us[p] = [0];
  23322. path = pathArray[p];
  23323. l = path.length;
  23324. minlg = (minlg < l) ? minlg : l;
  23325. j = 0;
  23326. while (j < l) {
  23327. positions.push(path[j].x, path[j].y, path[j].z);
  23328. if (j > 0) {
  23329. vectlg = path[j].subtract(path[j - 1]).length();
  23330. dist = vectlg + uTotalDistance[p];
  23331. us[p].push(dist);
  23332. uTotalDistance[p] = dist;
  23333. }
  23334. j++;
  23335. }
  23336. if (closePath) {
  23337. j--;
  23338. positions.push(path[0].x, path[0].y, path[0].z);
  23339. vectlg = path[j].subtract(path[0]).length();
  23340. dist = vectlg + uTotalDistance[p];
  23341. us[p].push(dist);
  23342. uTotalDistance[p] = dist;
  23343. }
  23344. lg[p] = l + closePathCorr;
  23345. idx[p] = idc;
  23346. idc += (l + closePathCorr);
  23347. }
  23348. // vertical distances (v)
  23349. var path1;
  23350. var path2;
  23351. var vertex1;
  23352. var vertex2;
  23353. for (i = 0; i < minlg + closePathCorr; i++) {
  23354. vTotalDistance[i] = 0;
  23355. vs[i] = [0];
  23356. for (p = 0; p < pathArray.length - 1; p++) {
  23357. path1 = pathArray[p];
  23358. path2 = pathArray[p + 1];
  23359. if (i === minlg) {
  23360. vertex1 = path1[0];
  23361. vertex2 = path2[0];
  23362. }
  23363. else {
  23364. vertex1 = path1[i];
  23365. vertex2 = path2[i];
  23366. }
  23367. vectlg = vertex2.subtract(vertex1).length();
  23368. dist = vectlg + vTotalDistance[i];
  23369. vs[i].push(dist);
  23370. vTotalDistance[i] = dist;
  23371. }
  23372. if (closeArray) {
  23373. path1 = pathArray[p];
  23374. path2 = pathArray[0];
  23375. if (i === minlg) {
  23376. vertex2 = path2[0];
  23377. }
  23378. vectlg = vertex2.subtract(vertex1).length();
  23379. dist = vectlg + vTotalDistance[i];
  23380. vTotalDistance[i] = dist;
  23381. }
  23382. }
  23383. // uvs
  23384. var u;
  23385. var v;
  23386. for (p = 0; p < pathArray.length; p++) {
  23387. for (i = 0; i < minlg + closePathCorr; i++) {
  23388. u = us[p][i] / uTotalDistance[p];
  23389. v = vs[i][p] / vTotalDistance[i];
  23390. uvs.push(u, v);
  23391. }
  23392. }
  23393. // indices
  23394. p = 0; // path index
  23395. var pi = 0; // positions array index
  23396. var l1 = lg[p] - 1; // path1 length
  23397. var l2 = lg[p + 1] - 1; // path2 length
  23398. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23399. var shft = idx[1] - idx[0]; // shift
  23400. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23401. while (pi <= min && p < path1nb) {
  23402. // 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
  23403. indices.push(pi, pi + shft, pi + 1);
  23404. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23405. pi += 1;
  23406. if (pi === min) {
  23407. p++;
  23408. if (p === lg.length - 1) {
  23409. shft = idx[0] - idx[p];
  23410. l1 = lg[p] - 1;
  23411. l2 = lg[0] - 1;
  23412. }
  23413. else {
  23414. shft = idx[p + 1] - idx[p];
  23415. l1 = lg[p] - 1;
  23416. l2 = lg[p + 1] - 1;
  23417. }
  23418. pi = idx[p];
  23419. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23420. }
  23421. }
  23422. // normals
  23423. VertexData.ComputeNormals(positions, indices, normals);
  23424. if (closePath) {
  23425. var indexFirst = 0;
  23426. var indexLast = 0;
  23427. for (p = 0; p < pathArray.length; p++) {
  23428. indexFirst = idx[p] * 3;
  23429. if (p + 1 < pathArray.length) {
  23430. indexLast = (idx[p + 1] - 1) * 3;
  23431. }
  23432. else {
  23433. indexLast = normals.length - 3;
  23434. }
  23435. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23436. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23437. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23438. normals[indexLast] = normals[indexFirst];
  23439. normals[indexLast + 1] = normals[indexFirst + 1];
  23440. normals[indexLast + 2] = normals[indexFirst + 2];
  23441. }
  23442. }
  23443. // sides
  23444. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23445. // Result
  23446. var vertexData = new VertexData();
  23447. vertexData.indices = indices;
  23448. vertexData.positions = positions;
  23449. vertexData.normals = normals;
  23450. vertexData.uvs = uvs;
  23451. if (closePath) {
  23452. vertexData._idx = idx;
  23453. }
  23454. return vertexData;
  23455. };
  23456. VertexData.CreateBox = function (options) {
  23457. var normalsSource = [
  23458. new BABYLON.Vector3(0, 0, 1),
  23459. new BABYLON.Vector3(0, 0, -1),
  23460. new BABYLON.Vector3(1, 0, 0),
  23461. new BABYLON.Vector3(-1, 0, 0),
  23462. new BABYLON.Vector3(0, 1, 0),
  23463. new BABYLON.Vector3(0, -1, 0)
  23464. ];
  23465. var indices = [];
  23466. var positions = [];
  23467. var normals = [];
  23468. var uvs = [];
  23469. var width = options.width || options.size || 1;
  23470. var height = options.height || options.size || 1;
  23471. var depth = options.depth || options.size || 1;
  23472. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23473. var faceUV = options.faceUV || new Array(6);
  23474. var faceColors = options.faceColors;
  23475. var colors = [];
  23476. // default face colors and UV if undefined
  23477. for (var f = 0; f < 6; f++) {
  23478. if (faceUV[f] === undefined) {
  23479. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23480. }
  23481. if (faceColors && faceColors[f] === undefined) {
  23482. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23483. }
  23484. }
  23485. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23486. // Create each face in turn.
  23487. for (var index = 0; index < normalsSource.length; index++) {
  23488. var normal = normalsSource[index];
  23489. // Get two vectors perpendicular to the face normal and to each other.
  23490. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23491. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23492. // Six indices (two triangles) per face.
  23493. var verticesLength = positions.length / 3;
  23494. indices.push(verticesLength);
  23495. indices.push(verticesLength + 1);
  23496. indices.push(verticesLength + 2);
  23497. indices.push(verticesLength);
  23498. indices.push(verticesLength + 2);
  23499. indices.push(verticesLength + 3);
  23500. // Four vertices per face.
  23501. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23502. positions.push(vertex.x, vertex.y, vertex.z);
  23503. normals.push(normal.x, normal.y, normal.z);
  23504. uvs.push(faceUV[index].z, faceUV[index].w);
  23505. if (faceColors) {
  23506. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23507. }
  23508. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23509. positions.push(vertex.x, vertex.y, vertex.z);
  23510. normals.push(normal.x, normal.y, normal.z);
  23511. uvs.push(faceUV[index].x, faceUV[index].w);
  23512. if (faceColors) {
  23513. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23514. }
  23515. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23516. positions.push(vertex.x, vertex.y, vertex.z);
  23517. normals.push(normal.x, normal.y, normal.z);
  23518. uvs.push(faceUV[index].x, faceUV[index].y);
  23519. if (faceColors) {
  23520. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23521. }
  23522. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23523. positions.push(vertex.x, vertex.y, vertex.z);
  23524. normals.push(normal.x, normal.y, normal.z);
  23525. uvs.push(faceUV[index].z, faceUV[index].y);
  23526. if (faceColors) {
  23527. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23528. }
  23529. }
  23530. // sides
  23531. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23532. // Result
  23533. var vertexData = new VertexData();
  23534. vertexData.indices = indices;
  23535. vertexData.positions = positions;
  23536. vertexData.normals = normals;
  23537. vertexData.uvs = uvs;
  23538. if (faceColors) {
  23539. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23540. vertexData.colors = totalColors;
  23541. }
  23542. return vertexData;
  23543. };
  23544. VertexData.CreateSphere = function (options) {
  23545. var segments = options.segments || 32;
  23546. var diameterX = options.diameterX || options.diameter || 1;
  23547. var diameterY = options.diameterY || options.diameter || 1;
  23548. var diameterZ = options.diameterZ || options.diameter || 1;
  23549. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23550. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23551. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23552. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23553. var totalZRotationSteps = 2 + segments;
  23554. var totalYRotationSteps = 2 * totalZRotationSteps;
  23555. var indices = [];
  23556. var positions = [];
  23557. var normals = [];
  23558. var uvs = [];
  23559. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23560. var normalizedZ = zRotationStep / totalZRotationSteps;
  23561. var angleZ = normalizedZ * Math.PI * slice;
  23562. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23563. var normalizedY = yRotationStep / totalYRotationSteps;
  23564. var angleY = normalizedY * Math.PI * 2 * arc;
  23565. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23566. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23567. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23568. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23569. var vertex = complete.multiply(radius);
  23570. var normal = BABYLON.Vector3.Normalize(vertex);
  23571. positions.push(vertex.x, vertex.y, vertex.z);
  23572. normals.push(normal.x, normal.y, normal.z);
  23573. uvs.push(normalizedY, normalizedZ);
  23574. }
  23575. if (zRotationStep > 0) {
  23576. var verticesCount = positions.length / 3;
  23577. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23578. indices.push((firstIndex));
  23579. indices.push((firstIndex + 1));
  23580. indices.push(firstIndex + totalYRotationSteps + 1);
  23581. indices.push((firstIndex + totalYRotationSteps + 1));
  23582. indices.push((firstIndex + 1));
  23583. indices.push((firstIndex + totalYRotationSteps + 2));
  23584. }
  23585. }
  23586. }
  23587. // Sides
  23588. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23589. // Result
  23590. var vertexData = new VertexData();
  23591. vertexData.indices = indices;
  23592. vertexData.positions = positions;
  23593. vertexData.normals = normals;
  23594. vertexData.uvs = uvs;
  23595. return vertexData;
  23596. };
  23597. // Cylinder and cone
  23598. VertexData.CreateCylinder = function (options) {
  23599. var height = options.height || 2;
  23600. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23601. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23602. var tessellation = options.tessellation || 24;
  23603. var subdivisions = options.subdivisions || 1;
  23604. var hasRings = options.hasRings;
  23605. var enclose = options.enclose;
  23606. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23607. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23608. var faceUV = options.faceUV || new Array(3);
  23609. var faceColors = options.faceColors;
  23610. // default face colors and UV if undefined
  23611. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23612. var ringNb = (hasRings) ? subdivisions : 1;
  23613. var colorNb = 2 + (1 + quadNb) * ringNb;
  23614. var f;
  23615. for (f = 0; f < colorNb; f++) {
  23616. if (faceColors && faceColors[f] === undefined) {
  23617. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23618. }
  23619. }
  23620. for (f = 0; f < 3; f++) {
  23621. if (faceUV && faceUV[f] === undefined) {
  23622. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23623. }
  23624. }
  23625. var indices = [];
  23626. var positions = [];
  23627. var normals = [];
  23628. var uvs = [];
  23629. var colors = [];
  23630. var angle_step = Math.PI * 2 * arc / tessellation;
  23631. var angle;
  23632. var h;
  23633. var radius;
  23634. var tan = (diameterBottom - diameterTop) / 2 / height;
  23635. var ringVertex = BABYLON.Vector3.Zero();
  23636. var ringNormal = BABYLON.Vector3.Zero();
  23637. var ringFirstVertex = BABYLON.Vector3.Zero();
  23638. var ringFirstNormal = BABYLON.Vector3.Zero();
  23639. var quadNormal = BABYLON.Vector3.Zero();
  23640. var Y = BABYLON.Axis.Y;
  23641. // positions, normals, uvs
  23642. var i;
  23643. var j;
  23644. var r;
  23645. var ringIdx = 1;
  23646. for (i = 0; i <= subdivisions; i++) {
  23647. h = i / subdivisions;
  23648. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23649. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23650. for (r = 0; r < ringIdx; r++) {
  23651. for (j = 0; j <= tessellation; j++) {
  23652. angle = j * angle_step;
  23653. // position
  23654. ringVertex.x = Math.cos(-angle) * radius;
  23655. ringVertex.y = -height / 2 + h * height;
  23656. ringVertex.z = Math.sin(-angle) * radius;
  23657. // normal
  23658. if (diameterTop === 0 && i === subdivisions) {
  23659. // if no top cap, reuse former normals
  23660. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23661. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23662. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23663. }
  23664. else {
  23665. ringNormal.x = ringVertex.x;
  23666. ringNormal.z = ringVertex.z;
  23667. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23668. ringNormal.normalize();
  23669. }
  23670. // keep first values for enclose
  23671. if (j === 0) {
  23672. ringFirstVertex.copyFrom(ringVertex);
  23673. ringFirstNormal.copyFrom(ringNormal);
  23674. }
  23675. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23676. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23677. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  23678. if (faceColors) {
  23679. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23680. }
  23681. }
  23682. // if enclose, add four vertices and their dedicated normals
  23683. if (arc !== 1 && enclose) {
  23684. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23685. positions.push(0, ringVertex.y, 0);
  23686. positions.push(0, ringVertex.y, 0);
  23687. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23688. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23689. quadNormal.normalize();
  23690. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23691. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23692. quadNormal.normalize();
  23693. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23694. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x), faceUV[1].y + (faceUV[1].w - faceUV[1].y));
  23695. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x), faceUV[1].y + (faceUV[1].w - faceUV[1].y));
  23696. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x), faceUV[1].y + (faceUV[1].w - faceUV[1].y));
  23697. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x), faceUV[1].y + (faceUV[1].w - faceUV[1].y));
  23698. if (faceColors) {
  23699. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23700. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23701. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23702. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23703. }
  23704. }
  23705. }
  23706. }
  23707. // indices
  23708. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23709. var s;
  23710. i = 0;
  23711. for (s = 0; s < subdivisions; s++) {
  23712. for (j = 0; j < tessellation; j++) {
  23713. var i0 = i * (e + 1) + j;
  23714. var i1 = (i + 1) * (e + 1) + j;
  23715. var i2 = i * (e + 1) + (j + 1);
  23716. var i3 = (i + 1) * (e + 1) + (j + 1);
  23717. indices.push(i0, i1, i2);
  23718. indices.push(i3, i2, i1);
  23719. }
  23720. if (arc !== 1 && enclose) {
  23721. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23722. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23723. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23724. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23725. }
  23726. i = (hasRings) ? (i + 2) : (i + 1);
  23727. }
  23728. // Caps
  23729. var createCylinderCap = function (isTop) {
  23730. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23731. if (radius === 0) {
  23732. return;
  23733. }
  23734. // Cap positions, normals & uvs
  23735. var angle;
  23736. var circleVector;
  23737. var i;
  23738. var u = (isTop) ? faceUV[2] : faceUV[0];
  23739. var c;
  23740. if (faceColors) {
  23741. c = (isTop) ? faceColors[colorNb - 1] : faceColors[0];
  23742. }
  23743. // cap center
  23744. var vbase = positions.length / 3;
  23745. var offset = isTop ? height / 2 : -height / 2;
  23746. var center = new BABYLON.Vector3(0, offset, 0);
  23747. positions.push(center.x, center.y, center.z);
  23748. normals.push(0, isTop ? 1 : -1, 0);
  23749. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23750. if (faceColors) {
  23751. colors.push(c.r, c.g, c.b, c.a);
  23752. }
  23753. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23754. for (i = 0; i <= tessellation; i++) {
  23755. angle = Math.PI * 2 * i * arc / tessellation;
  23756. var cos = Math.cos(-angle);
  23757. var sin = Math.sin(-angle);
  23758. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23759. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23760. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23761. normals.push(0, isTop ? 1 : -1, 0);
  23762. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23763. if (faceColors) {
  23764. colors.push(c.r, c.g, c.b, c.a);
  23765. }
  23766. }
  23767. // Cap indices
  23768. for (i = 0; i < tessellation; i++) {
  23769. if (!isTop) {
  23770. indices.push(vbase);
  23771. indices.push(vbase + (i + 1));
  23772. indices.push(vbase + (i + 2));
  23773. }
  23774. else {
  23775. indices.push(vbase);
  23776. indices.push(vbase + (i + 2));
  23777. indices.push(vbase + (i + 1));
  23778. }
  23779. }
  23780. };
  23781. // add caps to geometry
  23782. createCylinderCap(false);
  23783. createCylinderCap(true);
  23784. // Sides
  23785. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23786. var vertexData = new VertexData();
  23787. vertexData.indices = indices;
  23788. vertexData.positions = positions;
  23789. vertexData.normals = normals;
  23790. vertexData.uvs = uvs;
  23791. if (faceColors) {
  23792. vertexData.colors = colors;
  23793. }
  23794. return vertexData;
  23795. };
  23796. VertexData.CreateTorus = function (options) {
  23797. var indices = [];
  23798. var positions = [];
  23799. var normals = [];
  23800. var uvs = [];
  23801. var diameter = options.diameter || 1;
  23802. var thickness = options.thickness || 0.5;
  23803. var tessellation = options.tessellation || 16;
  23804. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23805. var stride = tessellation + 1;
  23806. for (var i = 0; i <= tessellation; i++) {
  23807. var u = i / tessellation;
  23808. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23809. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23810. for (var j = 0; j <= tessellation; j++) {
  23811. var v = 1 - j / tessellation;
  23812. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23813. var dx = Math.cos(innerAngle);
  23814. var dy = Math.sin(innerAngle);
  23815. // Create a vertex.
  23816. var normal = new BABYLON.Vector3(dx, dy, 0);
  23817. var position = normal.scale(thickness / 2);
  23818. var textureCoordinate = new BABYLON.Vector2(u, v);
  23819. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23820. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23821. positions.push(position.x, position.y, position.z);
  23822. normals.push(normal.x, normal.y, normal.z);
  23823. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23824. // And create indices for two triangles.
  23825. var nextI = (i + 1) % stride;
  23826. var nextJ = (j + 1) % stride;
  23827. indices.push(i * stride + j);
  23828. indices.push(i * stride + nextJ);
  23829. indices.push(nextI * stride + j);
  23830. indices.push(i * stride + nextJ);
  23831. indices.push(nextI * stride + nextJ);
  23832. indices.push(nextI * stride + j);
  23833. }
  23834. }
  23835. // Sides
  23836. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23837. // Result
  23838. var vertexData = new VertexData();
  23839. vertexData.indices = indices;
  23840. vertexData.positions = positions;
  23841. vertexData.normals = normals;
  23842. vertexData.uvs = uvs;
  23843. return vertexData;
  23844. };
  23845. VertexData.CreateLines = function (options) {
  23846. var indices = [];
  23847. var positions = [];
  23848. var points = options.points;
  23849. for (var index = 0; index < points.length; index++) {
  23850. positions.push(points[index].x, points[index].y, points[index].z);
  23851. if (index > 0) {
  23852. indices.push(index - 1);
  23853. indices.push(index);
  23854. }
  23855. }
  23856. // Result
  23857. var vertexData = new VertexData();
  23858. vertexData.indices = indices;
  23859. vertexData.positions = positions;
  23860. return vertexData;
  23861. };
  23862. VertexData.CreateDashedLines = function (options) {
  23863. var dashSize = options.dashSize || 3;
  23864. var gapSize = options.gapSize || 1;
  23865. var dashNb = options.dashNb || 200;
  23866. var points = options.points;
  23867. var positions = new Array();
  23868. var indices = new Array();
  23869. var curvect = BABYLON.Vector3.Zero();
  23870. var lg = 0;
  23871. var nb = 0;
  23872. var shft = 0;
  23873. var dashshft = 0;
  23874. var curshft = 0;
  23875. var idx = 0;
  23876. var i = 0;
  23877. for (i = 0; i < points.length - 1; i++) {
  23878. points[i + 1].subtractToRef(points[i], curvect);
  23879. lg += curvect.length();
  23880. }
  23881. shft = lg / dashNb;
  23882. dashshft = dashSize * shft / (dashSize + gapSize);
  23883. for (i = 0; i < points.length - 1; i++) {
  23884. points[i + 1].subtractToRef(points[i], curvect);
  23885. nb = Math.floor(curvect.length() / shft);
  23886. curvect.normalize();
  23887. for (var j = 0; j < nb; j++) {
  23888. curshft = shft * j;
  23889. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23890. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23891. indices.push(idx, idx + 1);
  23892. idx += 2;
  23893. }
  23894. }
  23895. // Result
  23896. var vertexData = new VertexData();
  23897. vertexData.positions = positions;
  23898. vertexData.indices = indices;
  23899. return vertexData;
  23900. };
  23901. VertexData.CreateGround = function (options) {
  23902. var indices = [];
  23903. var positions = [];
  23904. var normals = [];
  23905. var uvs = [];
  23906. var row, col;
  23907. var width = options.width || 1;
  23908. var height = options.height || 1;
  23909. var subdivisions = options.subdivisions || 1;
  23910. for (row = 0; row <= subdivisions; row++) {
  23911. for (col = 0; col <= subdivisions; col++) {
  23912. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23913. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23914. positions.push(position.x, position.y, position.z);
  23915. normals.push(normal.x, normal.y, normal.z);
  23916. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23917. }
  23918. }
  23919. for (row = 0; row < subdivisions; row++) {
  23920. for (col = 0; col < subdivisions; col++) {
  23921. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23922. indices.push(col + 1 + row * (subdivisions + 1));
  23923. indices.push(col + row * (subdivisions + 1));
  23924. indices.push(col + (row + 1) * (subdivisions + 1));
  23925. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23926. indices.push(col + row * (subdivisions + 1));
  23927. }
  23928. }
  23929. // Result
  23930. var vertexData = new VertexData();
  23931. vertexData.indices = indices;
  23932. vertexData.positions = positions;
  23933. vertexData.normals = normals;
  23934. vertexData.uvs = uvs;
  23935. return vertexData;
  23936. };
  23937. VertexData.CreateTiledGround = function (options) {
  23938. var xmin = options.xmin;
  23939. var zmin = options.zmin;
  23940. var xmax = options.xmax;
  23941. var zmax = options.zmax;
  23942. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23943. var precision = options.precision || { w: 1, h: 1 };
  23944. var indices = [];
  23945. var positions = [];
  23946. var normals = [];
  23947. var uvs = [];
  23948. var row, col, tileRow, tileCol;
  23949. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23950. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23951. precision.w = (precision.w < 1) ? 1 : precision.w;
  23952. precision.h = (precision.h < 1) ? 1 : precision.h;
  23953. var tileSize = {
  23954. 'w': (xmax - xmin) / subdivisions.w,
  23955. 'h': (zmax - zmin) / subdivisions.h
  23956. };
  23957. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23958. // Indices
  23959. var base = positions.length / 3;
  23960. var rowLength = precision.w + 1;
  23961. for (row = 0; row < precision.h; row++) {
  23962. for (col = 0; col < precision.w; col++) {
  23963. var square = [
  23964. base + col + row * rowLength,
  23965. base + (col + 1) + row * rowLength,
  23966. base + (col + 1) + (row + 1) * rowLength,
  23967. base + col + (row + 1) * rowLength
  23968. ];
  23969. indices.push(square[1]);
  23970. indices.push(square[2]);
  23971. indices.push(square[3]);
  23972. indices.push(square[0]);
  23973. indices.push(square[1]);
  23974. indices.push(square[3]);
  23975. }
  23976. }
  23977. // Position, normals and uvs
  23978. var position = BABYLON.Vector3.Zero();
  23979. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23980. for (row = 0; row <= precision.h; row++) {
  23981. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23982. for (col = 0; col <= precision.w; col++) {
  23983. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23984. position.y = 0;
  23985. positions.push(position.x, position.y, position.z);
  23986. normals.push(normal.x, normal.y, normal.z);
  23987. uvs.push(col / precision.w, row / precision.h);
  23988. }
  23989. }
  23990. }
  23991. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23992. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23993. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23994. }
  23995. }
  23996. // Result
  23997. var vertexData = new VertexData();
  23998. vertexData.indices = indices;
  23999. vertexData.positions = positions;
  24000. vertexData.normals = normals;
  24001. vertexData.uvs = uvs;
  24002. return vertexData;
  24003. };
  24004. VertexData.CreateGroundFromHeightMap = function (options) {
  24005. var indices = [];
  24006. var positions = [];
  24007. var normals = [];
  24008. var uvs = [];
  24009. var row, col;
  24010. // Vertices
  24011. for (row = 0; row <= options.subdivisions; row++) {
  24012. for (col = 0; col <= options.subdivisions; col++) {
  24013. 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));
  24014. // Compute height
  24015. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24016. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24017. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24018. var r = options.buffer[pos] / 255.0;
  24019. var g = options.buffer[pos + 1] / 255.0;
  24020. var b = options.buffer[pos + 2] / 255.0;
  24021. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24022. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24023. // Add vertex
  24024. positions.push(position.x, position.y, position.z);
  24025. normals.push(0, 0, 0);
  24026. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24027. }
  24028. }
  24029. // Indices
  24030. for (row = 0; row < options.subdivisions; row++) {
  24031. for (col = 0; col < options.subdivisions; col++) {
  24032. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24033. indices.push(col + 1 + row * (options.subdivisions + 1));
  24034. indices.push(col + row * (options.subdivisions + 1));
  24035. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24036. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24037. indices.push(col + row * (options.subdivisions + 1));
  24038. }
  24039. }
  24040. // Normals
  24041. VertexData.ComputeNormals(positions, indices, normals);
  24042. // Result
  24043. var vertexData = new VertexData();
  24044. vertexData.indices = indices;
  24045. vertexData.positions = positions;
  24046. vertexData.normals = normals;
  24047. vertexData.uvs = uvs;
  24048. return vertexData;
  24049. };
  24050. VertexData.CreatePlane = function (options) {
  24051. var indices = [];
  24052. var positions = [];
  24053. var normals = [];
  24054. var uvs = [];
  24055. var width = options.width || options.size || 1;
  24056. var height = options.height || options.size || 1;
  24057. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24058. // Vertices
  24059. var halfWidth = width / 2.0;
  24060. var halfHeight = height / 2.0;
  24061. positions.push(-halfWidth, -halfHeight, 0);
  24062. normals.push(0, 0, -1.0);
  24063. uvs.push(0.0, 0.0);
  24064. positions.push(halfWidth, -halfHeight, 0);
  24065. normals.push(0, 0, -1.0);
  24066. uvs.push(1.0, 0.0);
  24067. positions.push(halfWidth, halfHeight, 0);
  24068. normals.push(0, 0, -1.0);
  24069. uvs.push(1.0, 1.0);
  24070. positions.push(-halfWidth, halfHeight, 0);
  24071. normals.push(0, 0, -1.0);
  24072. uvs.push(0.0, 1.0);
  24073. // Indices
  24074. indices.push(0);
  24075. indices.push(1);
  24076. indices.push(2);
  24077. indices.push(0);
  24078. indices.push(2);
  24079. indices.push(3);
  24080. // Sides
  24081. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24082. // Result
  24083. var vertexData = new VertexData();
  24084. vertexData.indices = indices;
  24085. vertexData.positions = positions;
  24086. vertexData.normals = normals;
  24087. vertexData.uvs = uvs;
  24088. return vertexData;
  24089. };
  24090. VertexData.CreateDisc = function (options) {
  24091. var positions = [];
  24092. var indices = [];
  24093. var normals = [];
  24094. var uvs = [];
  24095. var radius = options.radius || 0.5;
  24096. var tessellation = options.tessellation || 64;
  24097. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24098. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24099. // positions and uvs
  24100. positions.push(0, 0, 0); // disc center first
  24101. uvs.push(0.5, 0.5);
  24102. var theta = Math.PI * 2 * arc;
  24103. var step = theta / tessellation;
  24104. for (var a = 0; a < theta; a += step) {
  24105. var x = Math.cos(a);
  24106. var y = Math.sin(a);
  24107. var u = (x + 1) / 2;
  24108. var v = (1 - y) / 2;
  24109. positions.push(radius * x, radius * y, 0);
  24110. uvs.push(u, v);
  24111. }
  24112. if (arc === 1) {
  24113. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24114. uvs.push(uvs[2], uvs[3]);
  24115. }
  24116. //indices
  24117. var vertexNb = positions.length / 3;
  24118. for (var i = 1; i < vertexNb - 1; i++) {
  24119. indices.push(i + 1, 0, i);
  24120. }
  24121. // result
  24122. VertexData.ComputeNormals(positions, indices, normals);
  24123. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24124. var vertexData = new VertexData();
  24125. vertexData.indices = indices;
  24126. vertexData.positions = positions;
  24127. vertexData.normals = normals;
  24128. vertexData.uvs = uvs;
  24129. return vertexData;
  24130. };
  24131. VertexData.CreateIcoSphere = function (options) {
  24132. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24133. var radius = options.radius || 1;
  24134. var flat = (options.flat === undefined) ? true : options.flat;
  24135. var subdivisions = options.subdivisions || 4;
  24136. var radiusX = options.radiusX || radius;
  24137. var radiusY = options.radiusY || radius;
  24138. var radiusZ = options.radiusZ || radius;
  24139. var t = (1 + Math.sqrt(5)) / 2;
  24140. // 12 vertex x,y,z
  24141. var ico_vertices = [
  24142. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24143. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24144. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24145. ];
  24146. // index of 3 vertex makes a face of icopshere
  24147. var ico_indices = [
  24148. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24149. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24150. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24151. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24152. ];
  24153. // vertex for uv have aliased position, not for UV
  24154. var vertices_unalias_id = [
  24155. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24156. // vertex alias
  24157. 0,
  24158. 2,
  24159. 3,
  24160. 3,
  24161. 3,
  24162. 4,
  24163. 7,
  24164. 8,
  24165. 9,
  24166. 9,
  24167. 10,
  24168. 11 // 23: B + 12
  24169. ];
  24170. // uv as integer step (not pixels !)
  24171. var ico_vertexuv = [
  24172. 5, 1, 3, 1, 6, 4, 0, 0,
  24173. 5, 3, 4, 2, 2, 2, 4, 0,
  24174. 2, 0, 1, 1, 6, 0, 6, 2,
  24175. // vertex alias (for same vertex on different faces)
  24176. 0, 4,
  24177. 3, 3,
  24178. 4, 4,
  24179. 3, 1,
  24180. 4, 2,
  24181. 4, 4,
  24182. 0, 2,
  24183. 1, 1,
  24184. 2, 2,
  24185. 3, 3,
  24186. 1, 3,
  24187. 2, 4 // 23: B + 12
  24188. ];
  24189. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24190. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24191. // First island of uv mapping
  24192. // v = 4h 3+ 2
  24193. // v = 3h 9+ 4
  24194. // v = 2h 9+ 5 B
  24195. // v = 1h 9 1 0
  24196. // v = 0h 3 8 7 A
  24197. // u = 0 1 2 3 4 5 6 *a
  24198. // Second island of uv mapping
  24199. // v = 4h 0+ B+ 4+
  24200. // v = 3h A+ 2+
  24201. // v = 2h 7+ 6 3+
  24202. // v = 1h 8+ 3+
  24203. // v = 0h
  24204. // u = 0 1 2 3 4 5 6 *a
  24205. // Face layout on texture UV mapping
  24206. // ============
  24207. // \ 4 /\ 16 / ======
  24208. // \ / \ / /\ 11 /
  24209. // \/ 7 \/ / \ /
  24210. // ======= / 10 \/
  24211. // /\ 17 /\ =======
  24212. // / \ / \ \ 15 /\
  24213. // / 8 \/ 12 \ \ / \
  24214. // ============ \/ 6 \
  24215. // \ 18 /\ ============
  24216. // \ / \ \ 5 /\ 0 /
  24217. // \/ 13 \ \ / \ /
  24218. // ======= \/ 1 \/
  24219. // =============
  24220. // /\ 19 /\ 2 /\
  24221. // / \ / \ / \
  24222. // / 14 \/ 9 \/ 3 \
  24223. // ===================
  24224. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24225. var ustep = 138 / 1024;
  24226. var vstep = 239 / 1024;
  24227. var uoffset = 60 / 1024;
  24228. var voffset = 26 / 1024;
  24229. // Second island should have margin, not to touch the first island
  24230. // avoid any borderline artefact in pixel rounding
  24231. var island_u_offset = -40 / 1024;
  24232. var island_v_offset = +20 / 1024;
  24233. // face is either island 0 or 1 :
  24234. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24235. var island = [
  24236. 0, 0, 0, 0, 1,
  24237. 0, 0, 1, 1, 0,
  24238. 0, 0, 1, 1, 0,
  24239. 0, 1, 1, 1, 0,
  24240. ];
  24241. var indices = [];
  24242. var positions = [];
  24243. var normals = [];
  24244. var uvs = [];
  24245. var current_indice = 0;
  24246. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24247. var face_vertex_pos = new Array(3);
  24248. var face_vertex_uv = new Array(3);
  24249. for (var v012 = 0; v012 < 3; v012++) {
  24250. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24251. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24252. }
  24253. // create all with normals
  24254. for (var face = 0; face < 20; face++) {
  24255. // 3 vertex per face
  24256. for (var v012 = 0; v012 < 3; v012++) {
  24257. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24258. var v_id = ico_indices[3 * face + v012];
  24259. // vertex have 3D position (x,y,z)
  24260. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  24261. // Normalize to get normal, then scale to radius
  24262. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24263. // uv Coordinates from vertex ID
  24264. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  24265. }
  24266. // Subdivide the face (interpolate pos, norm, uv)
  24267. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24268. // - norm is linear interpolation of vertex corner normal
  24269. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24270. // - uv is linear interpolation
  24271. //
  24272. // Topology is as below for sub-divide by 2
  24273. // vertex shown as v0,v1,v2
  24274. // interp index is i1 to progress in range [v0,v1[
  24275. // interp index is i2 to progress in range [v0,v2[
  24276. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24277. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24278. //
  24279. //
  24280. // i2 v2
  24281. // ^ ^
  24282. // / / \
  24283. // / / \
  24284. // / / \
  24285. // / / (0,1) \
  24286. // / #---------\
  24287. // / / \ (0,0)'/ \
  24288. // / / \ / \
  24289. // / / \ / \
  24290. // / / (0,0) \ / (1,0) \
  24291. // / #---------#---------\
  24292. // v0 v1
  24293. //
  24294. // --------------------> i1
  24295. //
  24296. // interp of (i1,i2):
  24297. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24298. // along i1 : lerp(x0,x1, i1/(S-i2))
  24299. //
  24300. // centroid of triangle is needed to get help normal computation
  24301. // (c1,c2) are used for centroid location
  24302. var interp_vertex = function (i1, i2, c1, c2) {
  24303. // vertex is interpolated from
  24304. // - face_vertex_pos[0..2]
  24305. // - face_vertex_uv[0..2]
  24306. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24307. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24308. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24309. pos_interp.normalize();
  24310. pos_interp.x *= radiusX;
  24311. pos_interp.y *= radiusY;
  24312. pos_interp.z *= radiusZ;
  24313. var vertex_normal;
  24314. if (flat) {
  24315. // in flat mode, recalculate normal as face centroid normal
  24316. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24317. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24318. var centroid_interp = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24319. vertex_normal = BABYLON.Vector3.Normalize(centroid_interp);
  24320. }
  24321. else {
  24322. // in smooth mode, recalculate normal from each single vertex position
  24323. vertex_normal = BABYLON.Vector3.Normalize(pos_interp);
  24324. }
  24325. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24326. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24327. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24328. positions.push(pos_interp.x, pos_interp.y, pos_interp.z);
  24329. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24330. uvs.push(uv_interp.x, uv_interp.y);
  24331. // push each vertex has member of a face
  24332. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24333. indices.push(current_indice);
  24334. current_indice++;
  24335. };
  24336. for (var i2 = 0; i2 < subdivisions; i2++) {
  24337. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24338. // face : (i1,i2) for /\ :
  24339. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24340. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24341. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24342. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24343. if (i1 + i2 + 1 < subdivisions) {
  24344. // face : (i1,i2)' for \/ :
  24345. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24346. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24347. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24348. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24349. }
  24350. }
  24351. }
  24352. }
  24353. // Sides
  24354. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24355. // Result
  24356. var vertexData = new VertexData();
  24357. vertexData.indices = indices;
  24358. vertexData.positions = positions;
  24359. vertexData.normals = normals;
  24360. vertexData.uvs = uvs;
  24361. return vertexData;
  24362. };
  24363. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24364. VertexData.CreatePolyhedron = function (options) {
  24365. // provided polyhedron types :
  24366. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24367. // 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)
  24368. var polyhedra = [];
  24369. 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]] };
  24370. 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]] };
  24371. polyhedra[2] = {
  24372. 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]],
  24373. 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]]
  24374. };
  24375. polyhedra[3] = {
  24376. 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]],
  24377. 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]]
  24378. };
  24379. polyhedra[4] = {
  24380. 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]],
  24381. 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]]
  24382. };
  24383. 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]] };
  24384. 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]] };
  24385. 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]] };
  24386. 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]] };
  24387. 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]] };
  24388. 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]] };
  24389. 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]] };
  24390. 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]] };
  24391. 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]] };
  24392. polyhedra[14] = {
  24393. 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]],
  24394. 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]]
  24395. };
  24396. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24397. var size = options.size;
  24398. var sizeX = options.sizeX || size || 1;
  24399. var sizeY = options.sizeY || size || 1;
  24400. var sizeZ = options.sizeZ || size || 1;
  24401. var data = options.custom || polyhedra[type];
  24402. var nbfaces = data.face.length;
  24403. var faceUV = options.faceUV || new Array(nbfaces);
  24404. var faceColors = options.faceColors;
  24405. var flat = (options.flat === undefined) ? true : options.flat;
  24406. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24407. var positions = [];
  24408. var indices = [];
  24409. var normals = [];
  24410. var uvs = [];
  24411. var colors = [];
  24412. var index = 0;
  24413. var faceIdx = 0; // face cursor in the array "indexes"
  24414. var indexes = [];
  24415. var i = 0;
  24416. var f = 0;
  24417. var u, v, ang, x, y, tmp;
  24418. // default face colors and UV if undefined
  24419. if (flat) {
  24420. for (f = 0; f < nbfaces; f++) {
  24421. if (faceColors && faceColors[f] === undefined) {
  24422. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24423. }
  24424. if (faceUV && faceUV[f] === undefined) {
  24425. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24426. }
  24427. }
  24428. }
  24429. if (!flat) {
  24430. for (i = 0; i < data.vertex.length; i++) {
  24431. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24432. uvs.push(0, 0);
  24433. }
  24434. for (f = 0; f < nbfaces; f++) {
  24435. for (i = 0; i < data.face[f].length - 2; i++) {
  24436. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24437. }
  24438. }
  24439. }
  24440. else {
  24441. for (f = 0; f < nbfaces; f++) {
  24442. var fl = data.face[f].length; // number of vertices of the current face
  24443. ang = 2 * Math.PI / fl;
  24444. x = 0.5 * Math.tan(ang / 2);
  24445. y = 0.5;
  24446. // positions, uvs, colors
  24447. for (i = 0; i < fl; i++) {
  24448. // positions
  24449. 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);
  24450. indexes.push(index);
  24451. index++;
  24452. // uvs
  24453. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24454. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24455. uvs.push(u, v);
  24456. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24457. y = x * Math.sin(ang) + y * Math.cos(ang);
  24458. x = tmp;
  24459. // colors
  24460. if (faceColors) {
  24461. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24462. }
  24463. }
  24464. // indices from indexes
  24465. for (i = 0; i < fl - 2; i++) {
  24466. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24467. }
  24468. faceIdx += fl;
  24469. }
  24470. }
  24471. VertexData.ComputeNormals(positions, indices, normals);
  24472. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24473. var vertexData = new VertexData();
  24474. vertexData.positions = positions;
  24475. vertexData.indices = indices;
  24476. vertexData.normals = normals;
  24477. vertexData.uvs = uvs;
  24478. if (faceColors && flat) {
  24479. vertexData.colors = colors;
  24480. }
  24481. return vertexData;
  24482. };
  24483. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24484. VertexData.CreateTorusKnot = function (options) {
  24485. var indices = [];
  24486. var positions = [];
  24487. var normals = [];
  24488. var uvs = [];
  24489. var radius = options.radius || 2;
  24490. var tube = options.tube || 0.5;
  24491. var radialSegments = options.radialSegments || 32;
  24492. var tubularSegments = options.tubularSegments || 32;
  24493. var p = options.p || 2;
  24494. var q = options.q || 3;
  24495. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24496. // Helper
  24497. var getPos = function (angle) {
  24498. var cu = Math.cos(angle);
  24499. var su = Math.sin(angle);
  24500. var quOverP = q / p * angle;
  24501. var cs = Math.cos(quOverP);
  24502. var tx = radius * (2 + cs) * 0.5 * cu;
  24503. var ty = radius * (2 + cs) * su * 0.5;
  24504. var tz = radius * Math.sin(quOverP) * 0.5;
  24505. return new BABYLON.Vector3(tx, ty, tz);
  24506. };
  24507. // Vertices
  24508. var i;
  24509. var j;
  24510. for (i = 0; i <= radialSegments; i++) {
  24511. var modI = i % radialSegments;
  24512. var u = modI / radialSegments * 2 * p * Math.PI;
  24513. var p1 = getPos(u);
  24514. var p2 = getPos(u + 0.01);
  24515. var tang = p2.subtract(p1);
  24516. var n = p2.add(p1);
  24517. var bitan = BABYLON.Vector3.Cross(tang, n);
  24518. n = BABYLON.Vector3.Cross(bitan, tang);
  24519. bitan.normalize();
  24520. n.normalize();
  24521. for (j = 0; j < tubularSegments; j++) {
  24522. var modJ = j % tubularSegments;
  24523. var v = modJ / tubularSegments * 2 * Math.PI;
  24524. var cx = -tube * Math.cos(v);
  24525. var cy = tube * Math.sin(v);
  24526. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24527. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24528. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24529. uvs.push(i / radialSegments);
  24530. uvs.push(j / tubularSegments);
  24531. }
  24532. }
  24533. for (i = 0; i < radialSegments; i++) {
  24534. for (j = 0; j < tubularSegments; j++) {
  24535. var jNext = (j + 1) % tubularSegments;
  24536. var a = i * tubularSegments + j;
  24537. var b = (i + 1) * tubularSegments + j;
  24538. var c = (i + 1) * tubularSegments + jNext;
  24539. var d = i * tubularSegments + jNext;
  24540. indices.push(d);
  24541. indices.push(b);
  24542. indices.push(a);
  24543. indices.push(d);
  24544. indices.push(c);
  24545. indices.push(b);
  24546. }
  24547. }
  24548. // Normals
  24549. VertexData.ComputeNormals(positions, indices, normals);
  24550. // Sides
  24551. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24552. // Result
  24553. var vertexData = new VertexData();
  24554. vertexData.indices = indices;
  24555. vertexData.positions = positions;
  24556. vertexData.normals = normals;
  24557. vertexData.uvs = uvs;
  24558. return vertexData;
  24559. };
  24560. // Tools
  24561. /**
  24562. * @param {any} - positions (number[] or Float32Array)
  24563. * @param {any} - indices (number[] or Uint16Array)
  24564. * @param {any} - normals (number[] or Float32Array)
  24565. */
  24566. VertexData.ComputeNormals = function (positions, indices, normals) {
  24567. var index = 0;
  24568. var p1p2x = 0.0;
  24569. var p1p2y = 0.0;
  24570. var p1p2z = 0.0;
  24571. var p3p2x = 0.0;
  24572. var p3p2y = 0.0;
  24573. var p3p2z = 0.0;
  24574. var faceNormalx = 0.0;
  24575. var faceNormaly = 0.0;
  24576. var faceNormalz = 0.0;
  24577. var length = 0.0;
  24578. var i1 = 0;
  24579. var i2 = 0;
  24580. var i3 = 0;
  24581. for (index = 0; index < positions.length; index++) {
  24582. normals[index] = 0.0;
  24583. }
  24584. // indice triplet = 1 face
  24585. var nbFaces = indices.length / 3;
  24586. for (index = 0; index < nbFaces; index++) {
  24587. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24588. i2 = indices[index * 3 + 1];
  24589. i3 = indices[index * 3 + 2];
  24590. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24591. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24592. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24593. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24594. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24595. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24596. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24597. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24598. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24599. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24600. length = (length === 0) ? 1.0 : length;
  24601. faceNormalx /= length; // normalize this normal
  24602. faceNormaly /= length;
  24603. faceNormalz /= length;
  24604. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24605. normals[i1 * 3 + 1] += faceNormaly;
  24606. normals[i1 * 3 + 2] += faceNormalz;
  24607. normals[i2 * 3] += faceNormalx;
  24608. normals[i2 * 3 + 1] += faceNormaly;
  24609. normals[i2 * 3 + 2] += faceNormalz;
  24610. normals[i3 * 3] += faceNormalx;
  24611. normals[i3 * 3 + 1] += faceNormaly;
  24612. normals[i3 * 3 + 2] += faceNormalz;
  24613. }
  24614. // last normalization of each normal
  24615. for (index = 0; index < normals.length / 3; index++) {
  24616. faceNormalx = normals[index * 3];
  24617. faceNormaly = normals[index * 3 + 1];
  24618. faceNormalz = normals[index * 3 + 2];
  24619. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24620. length = (length === 0) ? 1.0 : length;
  24621. faceNormalx /= length;
  24622. faceNormaly /= length;
  24623. faceNormalz /= length;
  24624. normals[index * 3] = faceNormalx;
  24625. normals[index * 3 + 1] = faceNormaly;
  24626. normals[index * 3 + 2] = faceNormalz;
  24627. }
  24628. };
  24629. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24630. var li = indices.length;
  24631. var ln = normals.length;
  24632. var i;
  24633. var n;
  24634. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24635. switch (sideOrientation) {
  24636. case BABYLON.Mesh.FRONTSIDE:
  24637. // nothing changed
  24638. break;
  24639. case BABYLON.Mesh.BACKSIDE:
  24640. var tmp;
  24641. // indices
  24642. for (i = 0; i < li; i += 3) {
  24643. tmp = indices[i];
  24644. indices[i] = indices[i + 2];
  24645. indices[i + 2] = tmp;
  24646. }
  24647. // normals
  24648. for (n = 0; n < ln; n++) {
  24649. normals[n] = -normals[n];
  24650. }
  24651. break;
  24652. case BABYLON.Mesh.DOUBLESIDE:
  24653. // positions
  24654. var lp = positions.length;
  24655. var l = lp / 3;
  24656. for (var p = 0; p < lp; p++) {
  24657. positions[lp + p] = positions[p];
  24658. }
  24659. // indices
  24660. for (i = 0; i < li; i += 3) {
  24661. indices[i + li] = indices[i + 2] + l;
  24662. indices[i + 1 + li] = indices[i + 1] + l;
  24663. indices[i + 2 + li] = indices[i] + l;
  24664. }
  24665. // normals
  24666. for (n = 0; n < ln; n++) {
  24667. normals[ln + n] = -normals[n];
  24668. }
  24669. // uvs
  24670. var lu = uvs.length;
  24671. for (var u = 0; u < lu; u++) {
  24672. uvs[u + lu] = uvs[u];
  24673. }
  24674. break;
  24675. }
  24676. };
  24677. return VertexData;
  24678. })();
  24679. BABYLON.VertexData = VertexData;
  24680. })(BABYLON || (BABYLON = {}));
  24681. var BABYLON;
  24682. (function (BABYLON) {
  24683. var Tags = (function () {
  24684. function Tags() {
  24685. }
  24686. Tags.EnableFor = function (obj) {
  24687. obj._tags = obj._tags || {};
  24688. obj.hasTags = function () {
  24689. return Tags.HasTags(obj);
  24690. };
  24691. obj.addTags = function (tagsString) {
  24692. return Tags.AddTagsTo(obj, tagsString);
  24693. };
  24694. obj.removeTags = function (tagsString) {
  24695. return Tags.RemoveTagsFrom(obj, tagsString);
  24696. };
  24697. obj.matchesTagsQuery = function (tagsQuery) {
  24698. return Tags.MatchesQuery(obj, tagsQuery);
  24699. };
  24700. };
  24701. Tags.DisableFor = function (obj) {
  24702. delete obj._tags;
  24703. delete obj.hasTags;
  24704. delete obj.addTags;
  24705. delete obj.removeTags;
  24706. delete obj.matchesTagsQuery;
  24707. };
  24708. Tags.HasTags = function (obj) {
  24709. if (!obj._tags) {
  24710. return false;
  24711. }
  24712. return !BABYLON.Tools.IsEmpty(obj._tags);
  24713. };
  24714. Tags.GetTags = function (obj) {
  24715. if (!obj._tags) {
  24716. return null;
  24717. }
  24718. return obj._tags;
  24719. };
  24720. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24721. // a tag cannot start with '||', '&&', and '!'
  24722. // it cannot contain whitespaces
  24723. Tags.AddTagsTo = function (obj, tagsString) {
  24724. if (!tagsString) {
  24725. return;
  24726. }
  24727. if (typeof tagsString !== "string") {
  24728. return;
  24729. }
  24730. var tags = tagsString.split(" ");
  24731. for (var t in tags) {
  24732. Tags._AddTagTo(obj, tags[t]);
  24733. }
  24734. };
  24735. Tags._AddTagTo = function (obj, tag) {
  24736. tag = tag.trim();
  24737. if (tag === "" || tag === "true" || tag === "false") {
  24738. return;
  24739. }
  24740. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24741. return;
  24742. }
  24743. Tags.EnableFor(obj);
  24744. obj._tags[tag] = true;
  24745. };
  24746. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24747. if (!Tags.HasTags(obj)) {
  24748. return;
  24749. }
  24750. var tags = tagsString.split(" ");
  24751. for (var t in tags) {
  24752. Tags._RemoveTagFrom(obj, tags[t]);
  24753. }
  24754. };
  24755. Tags._RemoveTagFrom = function (obj, tag) {
  24756. delete obj._tags[tag];
  24757. };
  24758. Tags.MatchesQuery = function (obj, tagsQuery) {
  24759. if (tagsQuery === undefined) {
  24760. return true;
  24761. }
  24762. if (tagsQuery === "") {
  24763. return Tags.HasTags(obj);
  24764. }
  24765. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24766. };
  24767. return Tags;
  24768. })();
  24769. BABYLON.Tags = Tags;
  24770. })(BABYLON || (BABYLON = {}));
  24771. var BABYLON;
  24772. (function (BABYLON) {
  24773. var Internals;
  24774. (function (Internals) {
  24775. var AndOrNotEvaluator = (function () {
  24776. function AndOrNotEvaluator() {
  24777. }
  24778. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24779. if (!query.match(/\([^\(\)]*\)/g)) {
  24780. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24781. }
  24782. else {
  24783. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24784. // remove parenthesis
  24785. r = r.slice(1, r.length - 1);
  24786. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24787. });
  24788. }
  24789. if (query === "true") {
  24790. return true;
  24791. }
  24792. if (query === "false") {
  24793. return false;
  24794. }
  24795. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24796. };
  24797. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24798. evaluateCallback = evaluateCallback || (function (r) {
  24799. return r === "true" ? true : false;
  24800. });
  24801. var result;
  24802. var or = parenthesisContent.split("||");
  24803. for (var i in or) {
  24804. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24805. var and = ori.split("&&");
  24806. if (and.length > 1) {
  24807. for (var j = 0; j < and.length; ++j) {
  24808. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24809. if (andj !== "true" && andj !== "false") {
  24810. if (andj[0] === "!") {
  24811. result = !evaluateCallback(andj.substring(1));
  24812. }
  24813. else {
  24814. result = evaluateCallback(andj);
  24815. }
  24816. }
  24817. else {
  24818. result = andj === "true" ? true : false;
  24819. }
  24820. if (!result) {
  24821. ori = "false";
  24822. break;
  24823. }
  24824. }
  24825. }
  24826. if (result || ori === "true") {
  24827. result = true;
  24828. break;
  24829. }
  24830. // result equals false (or undefined)
  24831. if (ori !== "true" && ori !== "false") {
  24832. if (ori[0] === "!") {
  24833. result = !evaluateCallback(ori.substring(1));
  24834. }
  24835. else {
  24836. result = evaluateCallback(ori);
  24837. }
  24838. }
  24839. else {
  24840. result = ori === "true" ? true : false;
  24841. }
  24842. }
  24843. // the whole parenthesis scope is replaced by 'true' or 'false'
  24844. return result ? "true" : "false";
  24845. };
  24846. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24847. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24848. // remove whitespaces
  24849. r = r.replace(/[\s]/g, function () { return ""; });
  24850. return r.length % 2 ? "!" : "";
  24851. });
  24852. booleanString = booleanString.trim();
  24853. if (booleanString === "!true") {
  24854. booleanString = "false";
  24855. }
  24856. else if (booleanString === "!false") {
  24857. booleanString = "true";
  24858. }
  24859. return booleanString;
  24860. };
  24861. return AndOrNotEvaluator;
  24862. })();
  24863. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24865. })(BABYLON || (BABYLON = {}));
  24866. var BABYLON;
  24867. (function (BABYLON) {
  24868. var PostProcessRenderPass = (function () {
  24869. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24870. this._enabled = true;
  24871. this._refCount = 0;
  24872. this._name = name;
  24873. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24874. this.setRenderList(renderList);
  24875. this._renderTexture.onBeforeRender = beforeRender;
  24876. this._renderTexture.onAfterRender = afterRender;
  24877. this._scene = scene;
  24878. this._renderList = renderList;
  24879. }
  24880. // private
  24881. PostProcessRenderPass.prototype._incRefCount = function () {
  24882. if (this._refCount === 0) {
  24883. this._scene.customRenderTargets.push(this._renderTexture);
  24884. }
  24885. return ++this._refCount;
  24886. };
  24887. PostProcessRenderPass.prototype._decRefCount = function () {
  24888. this._refCount--;
  24889. if (this._refCount <= 0) {
  24890. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24891. }
  24892. return this._refCount;
  24893. };
  24894. PostProcessRenderPass.prototype._update = function () {
  24895. this.setRenderList(this._renderList);
  24896. };
  24897. // public
  24898. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24899. this._renderTexture.renderList = renderList;
  24900. };
  24901. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24902. return this._renderTexture;
  24903. };
  24904. return PostProcessRenderPass;
  24905. })();
  24906. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24907. })(BABYLON || (BABYLON = {}));
  24908. var BABYLON;
  24909. (function (BABYLON) {
  24910. var PostProcessRenderEffect = (function () {
  24911. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24912. this._engine = engine;
  24913. this._name = name;
  24914. this._singleInstance = singleInstance || true;
  24915. this._getPostProcess = getPostProcess;
  24916. this._cameras = [];
  24917. this._indicesForCamera = [];
  24918. this._postProcesses = {};
  24919. this._renderPasses = {};
  24920. this._renderEffectAsPasses = {};
  24921. }
  24922. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24923. get: function () {
  24924. for (var index in this._postProcesses) {
  24925. if (!this._postProcesses[index].isSupported) {
  24926. return false;
  24927. }
  24928. }
  24929. return true;
  24930. },
  24931. enumerable: true,
  24932. configurable: true
  24933. });
  24934. PostProcessRenderEffect.prototype._update = function () {
  24935. for (var renderPassName in this._renderPasses) {
  24936. this._renderPasses[renderPassName]._update();
  24937. }
  24938. };
  24939. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24940. this._renderPasses[renderPass._name] = renderPass;
  24941. this._linkParameters();
  24942. };
  24943. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24944. delete this._renderPasses[renderPass._name];
  24945. this._linkParameters();
  24946. };
  24947. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24948. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24949. this._linkParameters();
  24950. };
  24951. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24952. for (var renderPassName in this._renderPasses) {
  24953. if (renderPassName === passName) {
  24954. return this._renderPasses[passName];
  24955. }
  24956. }
  24957. };
  24958. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24959. this._renderPasses = {};
  24960. this._linkParameters();
  24961. };
  24962. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24963. var cameraKey;
  24964. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24965. for (var i = 0; i < _cam.length; i++) {
  24966. var camera = _cam[i];
  24967. var cameraName = camera.name;
  24968. if (this._singleInstance) {
  24969. cameraKey = 0;
  24970. }
  24971. else {
  24972. cameraKey = cameraName;
  24973. }
  24974. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24975. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24976. if (!this._indicesForCamera[cameraName]) {
  24977. this._indicesForCamera[cameraName] = [];
  24978. }
  24979. this._indicesForCamera[cameraName].push(index);
  24980. if (this._cameras.indexOf(camera) === -1) {
  24981. this._cameras[cameraName] = camera;
  24982. }
  24983. for (var passName in this._renderPasses) {
  24984. this._renderPasses[passName]._incRefCount();
  24985. }
  24986. }
  24987. this._linkParameters();
  24988. };
  24989. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24990. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24991. for (var i = 0; i < _cam.length; i++) {
  24992. var camera = _cam[i];
  24993. var cameraName = camera.name;
  24994. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24995. var index = this._cameras.indexOf(cameraName);
  24996. this._indicesForCamera.splice(index, 1);
  24997. this._cameras.splice(index, 1);
  24998. for (var passName in this._renderPasses) {
  24999. this._renderPasses[passName]._decRefCount();
  25000. }
  25001. }
  25002. };
  25003. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25004. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25005. for (var i = 0; i < _cam.length; i++) {
  25006. var camera = _cam[i];
  25007. var cameraName = camera.name;
  25008. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25009. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25010. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25011. }
  25012. }
  25013. for (var passName in this._renderPasses) {
  25014. this._renderPasses[passName]._incRefCount();
  25015. }
  25016. }
  25017. };
  25018. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25019. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25020. for (var i = 0; i < _cam.length; i++) {
  25021. var camera = _cam[i];
  25022. var cameraName = camera.Name;
  25023. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25024. for (var passName in this._renderPasses) {
  25025. this._renderPasses[passName]._decRefCount();
  25026. }
  25027. }
  25028. };
  25029. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25030. if (this._singleInstance) {
  25031. return this._postProcesses[0];
  25032. }
  25033. else {
  25034. return this._postProcesses[camera.name];
  25035. }
  25036. };
  25037. PostProcessRenderEffect.prototype._linkParameters = function () {
  25038. var _this = this;
  25039. for (var index in this._postProcesses) {
  25040. if (this.applyParameters) {
  25041. this.applyParameters(this._postProcesses[index]);
  25042. }
  25043. this._postProcesses[index].onBeforeRender = function (effect) {
  25044. _this._linkTextures(effect);
  25045. };
  25046. }
  25047. };
  25048. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25049. for (var renderPassName in this._renderPasses) {
  25050. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25051. }
  25052. for (var renderEffectName in this._renderEffectAsPasses) {
  25053. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25054. }
  25055. };
  25056. return PostProcessRenderEffect;
  25057. })();
  25058. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25059. })(BABYLON || (BABYLON = {}));
  25060. var BABYLON;
  25061. (function (BABYLON) {
  25062. var PostProcessRenderPipeline = (function () {
  25063. function PostProcessRenderPipeline(engine, name) {
  25064. this._engine = engine;
  25065. this._name = name;
  25066. this._renderEffects = {};
  25067. this._renderEffectsForIsolatedPass = {};
  25068. this._cameras = [];
  25069. }
  25070. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  25071. get: function () {
  25072. for (var renderEffectName in this._renderEffects) {
  25073. if (!this._renderEffects[renderEffectName].isSupported) {
  25074. return false;
  25075. }
  25076. }
  25077. return true;
  25078. },
  25079. enumerable: true,
  25080. configurable: true
  25081. });
  25082. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25083. this._renderEffects[renderEffect._name] = renderEffect;
  25084. };
  25085. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25086. var renderEffects = this._renderEffects[renderEffectName];
  25087. if (!renderEffects) {
  25088. return;
  25089. }
  25090. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25091. };
  25092. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25093. var renderEffects = this._renderEffects[renderEffectName];
  25094. if (!renderEffects) {
  25095. return;
  25096. }
  25097. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25098. };
  25099. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25100. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25101. var indicesToDelete = [];
  25102. var i;
  25103. for (i = 0; i < _cam.length; i++) {
  25104. var camera = _cam[i];
  25105. var cameraName = camera.name;
  25106. if (this._cameras.indexOf(camera) === -1) {
  25107. this._cameras[cameraName] = camera;
  25108. }
  25109. else if (unique) {
  25110. indicesToDelete.push(i);
  25111. }
  25112. }
  25113. for (i = 0; i < indicesToDelete.length; i++) {
  25114. cameras.splice(indicesToDelete[i], 1);
  25115. }
  25116. for (var renderEffectName in this._renderEffects) {
  25117. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25118. }
  25119. };
  25120. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25121. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25122. for (var renderEffectName in this._renderEffects) {
  25123. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25124. }
  25125. for (var i = 0; i < _cam.length; i++) {
  25126. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25127. }
  25128. };
  25129. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25130. var _this = this;
  25131. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25132. var pass = null;
  25133. var renderEffectName;
  25134. for (renderEffectName in this._renderEffects) {
  25135. pass = this._renderEffects[renderEffectName].getPass(passName);
  25136. if (pass != null) {
  25137. break;
  25138. }
  25139. }
  25140. if (pass === null) {
  25141. return;
  25142. }
  25143. for (renderEffectName in this._renderEffects) {
  25144. this._renderEffects[renderEffectName]._disable(_cam);
  25145. }
  25146. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25147. for (var i = 0; i < _cam.length; i++) {
  25148. var camera = _cam[i];
  25149. var cameraName = camera.name;
  25150. 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); });
  25151. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25152. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25153. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25154. }
  25155. };
  25156. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25157. var _this = this;
  25158. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25159. for (var i = 0; i < _cam.length; i++) {
  25160. var camera = _cam[i];
  25161. var cameraName = camera.name;
  25162. 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); });
  25163. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25164. }
  25165. for (var renderEffectName in this._renderEffects) {
  25166. this._renderEffects[renderEffectName]._enable(_cam);
  25167. }
  25168. };
  25169. PostProcessRenderPipeline.prototype._update = function () {
  25170. for (var renderEffectName in this._renderEffects) {
  25171. this._renderEffects[renderEffectName]._update();
  25172. }
  25173. for (var i = 0; i < this._cameras.length; i++) {
  25174. var cameraName = this._cameras[i].name;
  25175. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25176. this._renderEffectsForIsolatedPass[cameraName]._update();
  25177. }
  25178. }
  25179. };
  25180. PostProcessRenderPipeline.prototype.dispose = function () {
  25181. // Must be implemented by children
  25182. };
  25183. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25184. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25185. return PostProcessRenderPipeline;
  25186. })();
  25187. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25188. })(BABYLON || (BABYLON = {}));
  25189. var BABYLON;
  25190. (function (BABYLON) {
  25191. var PostProcessRenderPipelineManager = (function () {
  25192. function PostProcessRenderPipelineManager() {
  25193. this._renderPipelines = {};
  25194. }
  25195. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25196. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25197. };
  25198. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25199. var renderPipeline = this._renderPipelines[renderPipelineName];
  25200. if (!renderPipeline) {
  25201. return;
  25202. }
  25203. renderPipeline._attachCameras(cameras, unique);
  25204. };
  25205. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25206. var renderPipeline = this._renderPipelines[renderPipelineName];
  25207. if (!renderPipeline) {
  25208. return;
  25209. }
  25210. renderPipeline._detachCameras(cameras);
  25211. };
  25212. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25213. var renderPipeline = this._renderPipelines[renderPipelineName];
  25214. if (!renderPipeline) {
  25215. return;
  25216. }
  25217. renderPipeline._enableEffect(renderEffectName, cameras);
  25218. };
  25219. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25220. var renderPipeline = this._renderPipelines[renderPipelineName];
  25221. if (!renderPipeline) {
  25222. return;
  25223. }
  25224. renderPipeline._disableEffect(renderEffectName, cameras);
  25225. };
  25226. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25227. var renderPipeline = this._renderPipelines[renderPipelineName];
  25228. if (!renderPipeline) {
  25229. return;
  25230. }
  25231. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25232. };
  25233. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25234. var renderPipeline = this._renderPipelines[renderPipelineName];
  25235. if (!renderPipeline) {
  25236. return;
  25237. }
  25238. renderPipeline._disableDisplayOnlyPass(cameras);
  25239. };
  25240. PostProcessRenderPipelineManager.prototype.update = function () {
  25241. for (var renderPipelineName in this._renderPipelines) {
  25242. var pipeline = this._renderPipelines[renderPipelineName];
  25243. if (!pipeline.isSupported) {
  25244. pipeline.dispose();
  25245. delete this._renderPipelines[renderPipelineName];
  25246. }
  25247. else {
  25248. pipeline._update();
  25249. }
  25250. }
  25251. };
  25252. return PostProcessRenderPipelineManager;
  25253. })();
  25254. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25255. })(BABYLON || (BABYLON = {}));
  25256. var BABYLON;
  25257. (function (BABYLON) {
  25258. var BoundingBoxRenderer = (function () {
  25259. function BoundingBoxRenderer(scene) {
  25260. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25261. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25262. this.showBackLines = true;
  25263. this.renderList = new BABYLON.SmartArray(32);
  25264. this._scene = scene;
  25265. }
  25266. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25267. if (this._colorShader) {
  25268. return;
  25269. }
  25270. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25271. attributes: ["position"],
  25272. uniforms: ["worldViewProjection", "color"]
  25273. });
  25274. var engine = this._scene.getEngine();
  25275. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25276. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25277. 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]);
  25278. };
  25279. BoundingBoxRenderer.prototype.reset = function () {
  25280. this.renderList.reset();
  25281. };
  25282. BoundingBoxRenderer.prototype.render = function () {
  25283. if (this.renderList.length === 0) {
  25284. return;
  25285. }
  25286. this._prepareRessources();
  25287. if (!this._colorShader.isReady()) {
  25288. return;
  25289. }
  25290. var engine = this._scene.getEngine();
  25291. engine.setDepthWrite(false);
  25292. this._colorShader._preBind();
  25293. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25294. var boundingBox = this.renderList.data[boundingBoxIndex];
  25295. var min = boundingBox.minimum;
  25296. var max = boundingBox.maximum;
  25297. var diff = max.subtract(min);
  25298. var median = min.add(diff.scale(0.5));
  25299. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25300. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25301. .multiply(boundingBox.getWorldMatrix());
  25302. // VBOs
  25303. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25304. if (this.showBackLines) {
  25305. // Back
  25306. engine.setDepthFunctionToGreaterOrEqual();
  25307. this._scene.resetCachedMaterial();
  25308. this._colorShader.setColor4("color", this.backColor.toColor4());
  25309. this._colorShader.bind(worldMatrix);
  25310. // Draw order
  25311. engine.draw(false, 0, 24);
  25312. }
  25313. // Front
  25314. engine.setDepthFunctionToLess();
  25315. this._scene.resetCachedMaterial();
  25316. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25317. this._colorShader.bind(worldMatrix);
  25318. // Draw order
  25319. engine.draw(false, 0, 24);
  25320. }
  25321. this._colorShader.unbind();
  25322. engine.setDepthFunctionToLessOrEqual();
  25323. engine.setDepthWrite(true);
  25324. };
  25325. BoundingBoxRenderer.prototype.dispose = function () {
  25326. if (!this._colorShader) {
  25327. return;
  25328. }
  25329. this._colorShader.dispose();
  25330. this._vb.dispose();
  25331. this._scene.getEngine()._releaseBuffer(this._ib);
  25332. };
  25333. return BoundingBoxRenderer;
  25334. })();
  25335. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25336. })(BABYLON || (BABYLON = {}));
  25337. var BABYLON;
  25338. (function (BABYLON) {
  25339. var Condition = (function () {
  25340. function Condition(actionManager) {
  25341. this._actionManager = actionManager;
  25342. }
  25343. Condition.prototype.isValid = function () {
  25344. return true;
  25345. };
  25346. Condition.prototype._getProperty = function (propertyPath) {
  25347. return this._actionManager._getProperty(propertyPath);
  25348. };
  25349. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25350. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25351. };
  25352. return Condition;
  25353. })();
  25354. BABYLON.Condition = Condition;
  25355. var ValueCondition = (function (_super) {
  25356. __extends(ValueCondition, _super);
  25357. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25358. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25359. _super.call(this, actionManager);
  25360. this.propertyPath = propertyPath;
  25361. this.value = value;
  25362. this.operator = operator;
  25363. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25364. this._property = this._getProperty(this.propertyPath);
  25365. }
  25366. Object.defineProperty(ValueCondition, "IsEqual", {
  25367. get: function () {
  25368. return ValueCondition._IsEqual;
  25369. },
  25370. enumerable: true,
  25371. configurable: true
  25372. });
  25373. Object.defineProperty(ValueCondition, "IsDifferent", {
  25374. get: function () {
  25375. return ValueCondition._IsDifferent;
  25376. },
  25377. enumerable: true,
  25378. configurable: true
  25379. });
  25380. Object.defineProperty(ValueCondition, "IsGreater", {
  25381. get: function () {
  25382. return ValueCondition._IsGreater;
  25383. },
  25384. enumerable: true,
  25385. configurable: true
  25386. });
  25387. Object.defineProperty(ValueCondition, "IsLesser", {
  25388. get: function () {
  25389. return ValueCondition._IsLesser;
  25390. },
  25391. enumerable: true,
  25392. configurable: true
  25393. });
  25394. // Methods
  25395. ValueCondition.prototype.isValid = function () {
  25396. switch (this.operator) {
  25397. case ValueCondition.IsGreater:
  25398. return this._target[this._property] > this.value;
  25399. case ValueCondition.IsLesser:
  25400. return this._target[this._property] < this.value;
  25401. case ValueCondition.IsEqual:
  25402. case ValueCondition.IsDifferent:
  25403. var check;
  25404. if (this.value.equals) {
  25405. check = this.value.equals(this._target[this._property]);
  25406. }
  25407. else {
  25408. check = this.value === this._target[this._property];
  25409. }
  25410. return this.operator === ValueCondition.IsEqual ? check : !check;
  25411. }
  25412. return false;
  25413. };
  25414. // Statics
  25415. ValueCondition._IsEqual = 0;
  25416. ValueCondition._IsDifferent = 1;
  25417. ValueCondition._IsGreater = 2;
  25418. ValueCondition._IsLesser = 3;
  25419. return ValueCondition;
  25420. })(Condition);
  25421. BABYLON.ValueCondition = ValueCondition;
  25422. var PredicateCondition = (function (_super) {
  25423. __extends(PredicateCondition, _super);
  25424. function PredicateCondition(actionManager, predicate) {
  25425. _super.call(this, actionManager);
  25426. this.predicate = predicate;
  25427. }
  25428. PredicateCondition.prototype.isValid = function () {
  25429. return this.predicate();
  25430. };
  25431. return PredicateCondition;
  25432. })(Condition);
  25433. BABYLON.PredicateCondition = PredicateCondition;
  25434. var StateCondition = (function (_super) {
  25435. __extends(StateCondition, _super);
  25436. function StateCondition(actionManager, target, value) {
  25437. _super.call(this, actionManager);
  25438. this.value = value;
  25439. this._target = target;
  25440. }
  25441. // Methods
  25442. StateCondition.prototype.isValid = function () {
  25443. return this._target.state === this.value;
  25444. };
  25445. return StateCondition;
  25446. })(Condition);
  25447. BABYLON.StateCondition = StateCondition;
  25448. })(BABYLON || (BABYLON = {}));
  25449. var BABYLON;
  25450. (function (BABYLON) {
  25451. var Action = (function () {
  25452. function Action(triggerOptions, condition) {
  25453. this.triggerOptions = triggerOptions;
  25454. if (triggerOptions.parameter) {
  25455. this.trigger = triggerOptions.trigger;
  25456. this._triggerParameter = triggerOptions.parameter;
  25457. }
  25458. else {
  25459. this.trigger = triggerOptions;
  25460. }
  25461. this._nextActiveAction = this;
  25462. this._condition = condition;
  25463. }
  25464. // Methods
  25465. Action.prototype._prepare = function () {
  25466. };
  25467. Action.prototype.getTriggerParameter = function () {
  25468. return this._triggerParameter;
  25469. };
  25470. Action.prototype._executeCurrent = function (evt) {
  25471. if (this._nextActiveAction._condition) {
  25472. var condition = this._nextActiveAction._condition;
  25473. var currentRenderId = this._actionManager.getScene().getRenderId();
  25474. // We cache the current evaluation for the current frame
  25475. if (condition._evaluationId === currentRenderId) {
  25476. if (!condition._currentResult) {
  25477. return;
  25478. }
  25479. }
  25480. else {
  25481. condition._evaluationId = currentRenderId;
  25482. if (!condition.isValid()) {
  25483. condition._currentResult = false;
  25484. return;
  25485. }
  25486. condition._currentResult = true;
  25487. }
  25488. }
  25489. this._nextActiveAction.execute(evt);
  25490. if (this._nextActiveAction._child) {
  25491. if (!this._nextActiveAction._child._actionManager) {
  25492. this._nextActiveAction._child._actionManager = this._actionManager;
  25493. }
  25494. this._nextActiveAction = this._nextActiveAction._child;
  25495. }
  25496. else {
  25497. this._nextActiveAction = this;
  25498. }
  25499. };
  25500. Action.prototype.execute = function (evt) {
  25501. };
  25502. Action.prototype.then = function (action) {
  25503. this._child = action;
  25504. action._actionManager = this._actionManager;
  25505. action._prepare();
  25506. return action;
  25507. };
  25508. Action.prototype._getProperty = function (propertyPath) {
  25509. return this._actionManager._getProperty(propertyPath);
  25510. };
  25511. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25512. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25513. };
  25514. return Action;
  25515. })();
  25516. BABYLON.Action = Action;
  25517. })(BABYLON || (BABYLON = {}));
  25518. var BABYLON;
  25519. (function (BABYLON) {
  25520. /**
  25521. * ActionEvent is the event beint sent when an action is triggered.
  25522. */
  25523. var ActionEvent = (function () {
  25524. /**
  25525. * @constructor
  25526. * @param source The mesh or sprite that triggered the action.
  25527. * @param pointerX The X mouse cursor position at the time of the event
  25528. * @param pointerY The Y mouse cursor position at the time of the event
  25529. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25530. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25531. */
  25532. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25533. this.source = source;
  25534. this.pointerX = pointerX;
  25535. this.pointerY = pointerY;
  25536. this.meshUnderPointer = meshUnderPointer;
  25537. this.sourceEvent = sourceEvent;
  25538. this.additionalData = additionalData;
  25539. }
  25540. /**
  25541. * Helper function to auto-create an ActionEvent from a source mesh.
  25542. * @param source The source mesh that triggered the event
  25543. * @param evt {Event} The original (browser) event
  25544. */
  25545. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25546. var scene = source.getScene();
  25547. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25548. };
  25549. /**
  25550. * Helper function to auto-create an ActionEvent from a source mesh.
  25551. * @param source The source sprite that triggered the event
  25552. * @param scene Scene associated with the sprite
  25553. * @param evt {Event} The original (browser) event
  25554. */
  25555. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25556. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25557. };
  25558. /**
  25559. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25560. * @param scene the scene where the event occurred
  25561. * @param evt {Event} The original (browser) event
  25562. */
  25563. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25564. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25565. };
  25566. return ActionEvent;
  25567. })();
  25568. BABYLON.ActionEvent = ActionEvent;
  25569. /**
  25570. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25571. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25572. */
  25573. var ActionManager = (function () {
  25574. function ActionManager(scene) {
  25575. // Members
  25576. this.actions = new Array();
  25577. this._scene = scene;
  25578. scene._actionManagers.push(this);
  25579. }
  25580. Object.defineProperty(ActionManager, "NothingTrigger", {
  25581. get: function () {
  25582. return ActionManager._NothingTrigger;
  25583. },
  25584. enumerable: true,
  25585. configurable: true
  25586. });
  25587. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25588. get: function () {
  25589. return ActionManager._OnPickTrigger;
  25590. },
  25591. enumerable: true,
  25592. configurable: true
  25593. });
  25594. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25595. get: function () {
  25596. return ActionManager._OnLeftPickTrigger;
  25597. },
  25598. enumerable: true,
  25599. configurable: true
  25600. });
  25601. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25602. get: function () {
  25603. return ActionManager._OnRightPickTrigger;
  25604. },
  25605. enumerable: true,
  25606. configurable: true
  25607. });
  25608. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25609. get: function () {
  25610. return ActionManager._OnCenterPickTrigger;
  25611. },
  25612. enumerable: true,
  25613. configurable: true
  25614. });
  25615. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25616. get: function () {
  25617. return ActionManager._OnPointerOverTrigger;
  25618. },
  25619. enumerable: true,
  25620. configurable: true
  25621. });
  25622. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25623. get: function () {
  25624. return ActionManager._OnPointerOutTrigger;
  25625. },
  25626. enumerable: true,
  25627. configurable: true
  25628. });
  25629. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25630. get: function () {
  25631. return ActionManager._OnEveryFrameTrigger;
  25632. },
  25633. enumerable: true,
  25634. configurable: true
  25635. });
  25636. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25637. get: function () {
  25638. return ActionManager._OnIntersectionEnterTrigger;
  25639. },
  25640. enumerable: true,
  25641. configurable: true
  25642. });
  25643. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25644. get: function () {
  25645. return ActionManager._OnIntersectionExitTrigger;
  25646. },
  25647. enumerable: true,
  25648. configurable: true
  25649. });
  25650. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25651. get: function () {
  25652. return ActionManager._OnKeyDownTrigger;
  25653. },
  25654. enumerable: true,
  25655. configurable: true
  25656. });
  25657. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25658. get: function () {
  25659. return ActionManager._OnKeyUpTrigger;
  25660. },
  25661. enumerable: true,
  25662. configurable: true
  25663. });
  25664. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25665. get: function () {
  25666. return ActionManager._OnPickUpTrigger;
  25667. },
  25668. enumerable: true,
  25669. configurable: true
  25670. });
  25671. // Methods
  25672. ActionManager.prototype.dispose = function () {
  25673. var index = this._scene._actionManagers.indexOf(this);
  25674. if (index > -1) {
  25675. this._scene._actionManagers.splice(index, 1);
  25676. }
  25677. };
  25678. ActionManager.prototype.getScene = function () {
  25679. return this._scene;
  25680. };
  25681. /**
  25682. * Does this action manager handles actions of any of the given triggers
  25683. * @param {number[]} triggers - the triggers to be tested
  25684. * @return {boolean} whether one (or more) of the triggers is handeled
  25685. */
  25686. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25687. for (var index = 0; index < this.actions.length; index++) {
  25688. var action = this.actions[index];
  25689. if (triggers.indexOf(action.trigger) > -1) {
  25690. return true;
  25691. }
  25692. }
  25693. return false;
  25694. };
  25695. /**
  25696. * Does this action manager handles actions of a given trigger
  25697. * @param {number} trigger - the trigger to be tested
  25698. * @return {boolean} whether the trigger is handeled
  25699. */
  25700. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25701. for (var index = 0; index < this.actions.length; index++) {
  25702. var action = this.actions[index];
  25703. if (action.trigger === trigger) {
  25704. return true;
  25705. }
  25706. }
  25707. return false;
  25708. };
  25709. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25710. /**
  25711. * Does this action manager has pointer triggers
  25712. * @return {boolean} whether or not it has pointer triggers
  25713. */
  25714. get: function () {
  25715. for (var index = 0; index < this.actions.length; index++) {
  25716. var action = this.actions[index];
  25717. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25718. return true;
  25719. }
  25720. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25721. return true;
  25722. }
  25723. }
  25724. return false;
  25725. },
  25726. enumerable: true,
  25727. configurable: true
  25728. });
  25729. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25730. /**
  25731. * Does this action manager has pick triggers
  25732. * @return {boolean} whether or not it has pick triggers
  25733. */
  25734. get: function () {
  25735. for (var index = 0; index < this.actions.length; index++) {
  25736. var action = this.actions[index];
  25737. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25738. return true;
  25739. }
  25740. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25741. return true;
  25742. }
  25743. }
  25744. return false;
  25745. },
  25746. enumerable: true,
  25747. configurable: true
  25748. });
  25749. /**
  25750. * Registers an action to this action manager
  25751. * @param {BABYLON.Action} action - the action to be registered
  25752. * @return {BABYLON.Action} the action amended (prepared) after registration
  25753. */
  25754. ActionManager.prototype.registerAction = function (action) {
  25755. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25756. if (this.getScene().actionManager !== this) {
  25757. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25758. return null;
  25759. }
  25760. }
  25761. this.actions.push(action);
  25762. action._actionManager = this;
  25763. action._prepare();
  25764. return action;
  25765. };
  25766. /**
  25767. * Process a specific trigger
  25768. * @param {number} trigger - the trigger to process
  25769. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25770. */
  25771. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25772. for (var index = 0; index < this.actions.length; index++) {
  25773. var action = this.actions[index];
  25774. if (action.trigger === trigger) {
  25775. if (trigger === ActionManager.OnKeyUpTrigger
  25776. || trigger === ActionManager.OnKeyDownTrigger) {
  25777. var parameter = action.getTriggerParameter();
  25778. if (parameter) {
  25779. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25780. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25781. if (actualkey !== parameter.toLowerCase()) {
  25782. continue;
  25783. }
  25784. }
  25785. }
  25786. action._executeCurrent(evt);
  25787. }
  25788. }
  25789. };
  25790. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25791. var properties = propertyPath.split(".");
  25792. for (var index = 0; index < properties.length - 1; index++) {
  25793. target = target[properties[index]];
  25794. }
  25795. return target;
  25796. };
  25797. ActionManager.prototype._getProperty = function (propertyPath) {
  25798. var properties = propertyPath.split(".");
  25799. return properties[properties.length - 1];
  25800. };
  25801. // Statics
  25802. ActionManager._NothingTrigger = 0;
  25803. ActionManager._OnPickTrigger = 1;
  25804. ActionManager._OnLeftPickTrigger = 2;
  25805. ActionManager._OnRightPickTrigger = 3;
  25806. ActionManager._OnCenterPickTrigger = 4;
  25807. ActionManager._OnPointerOverTrigger = 5;
  25808. ActionManager._OnPointerOutTrigger = 6;
  25809. ActionManager._OnEveryFrameTrigger = 7;
  25810. ActionManager._OnIntersectionEnterTrigger = 8;
  25811. ActionManager._OnIntersectionExitTrigger = 9;
  25812. ActionManager._OnKeyDownTrigger = 10;
  25813. ActionManager._OnKeyUpTrigger = 11;
  25814. ActionManager._OnPickUpTrigger = 12;
  25815. return ActionManager;
  25816. })();
  25817. BABYLON.ActionManager = ActionManager;
  25818. })(BABYLON || (BABYLON = {}));
  25819. var BABYLON;
  25820. (function (BABYLON) {
  25821. var InterpolateValueAction = (function (_super) {
  25822. __extends(InterpolateValueAction, _super);
  25823. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25824. if (duration === void 0) { duration = 1000; }
  25825. _super.call(this, triggerOptions, condition);
  25826. this.propertyPath = propertyPath;
  25827. this.value = value;
  25828. this.duration = duration;
  25829. this.stopOtherAnimations = stopOtherAnimations;
  25830. this.onInterpolationDone = onInterpolationDone;
  25831. this._target = target;
  25832. }
  25833. InterpolateValueAction.prototype._prepare = function () {
  25834. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25835. this._property = this._getProperty(this.propertyPath);
  25836. };
  25837. InterpolateValueAction.prototype.execute = function () {
  25838. var scene = this._actionManager.getScene();
  25839. var keys = [
  25840. {
  25841. frame: 0,
  25842. value: this._target[this._property]
  25843. }, {
  25844. frame: 100,
  25845. value: this.value
  25846. }
  25847. ];
  25848. var dataType;
  25849. if (typeof this.value === "number") {
  25850. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25851. }
  25852. else if (this.value instanceof BABYLON.Color3) {
  25853. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25854. }
  25855. else if (this.value instanceof BABYLON.Vector3) {
  25856. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25857. }
  25858. else if (this.value instanceof BABYLON.Matrix) {
  25859. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25860. }
  25861. else if (this.value instanceof BABYLON.Quaternion) {
  25862. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25863. }
  25864. else {
  25865. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25866. return;
  25867. }
  25868. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25869. animation.setKeys(keys);
  25870. if (this.stopOtherAnimations) {
  25871. scene.stopAnimation(this._target);
  25872. }
  25873. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25874. };
  25875. return InterpolateValueAction;
  25876. })(BABYLON.Action);
  25877. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25878. })(BABYLON || (BABYLON = {}));
  25879. var BABYLON;
  25880. (function (BABYLON) {
  25881. var SwitchBooleanAction = (function (_super) {
  25882. __extends(SwitchBooleanAction, _super);
  25883. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25884. _super.call(this, triggerOptions, condition);
  25885. this.propertyPath = propertyPath;
  25886. this._target = target;
  25887. }
  25888. SwitchBooleanAction.prototype._prepare = function () {
  25889. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25890. this._property = this._getProperty(this.propertyPath);
  25891. };
  25892. SwitchBooleanAction.prototype.execute = function () {
  25893. this._target[this._property] = !this._target[this._property];
  25894. };
  25895. return SwitchBooleanAction;
  25896. })(BABYLON.Action);
  25897. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25898. var SetStateAction = (function (_super) {
  25899. __extends(SetStateAction, _super);
  25900. function SetStateAction(triggerOptions, target, value, condition) {
  25901. _super.call(this, triggerOptions, condition);
  25902. this.value = value;
  25903. this._target = target;
  25904. }
  25905. SetStateAction.prototype.execute = function () {
  25906. this._target.state = this.value;
  25907. };
  25908. return SetStateAction;
  25909. })(BABYLON.Action);
  25910. BABYLON.SetStateAction = SetStateAction;
  25911. var SetValueAction = (function (_super) {
  25912. __extends(SetValueAction, _super);
  25913. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25914. _super.call(this, triggerOptions, condition);
  25915. this.propertyPath = propertyPath;
  25916. this.value = value;
  25917. this._target = target;
  25918. }
  25919. SetValueAction.prototype._prepare = function () {
  25920. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25921. this._property = this._getProperty(this.propertyPath);
  25922. };
  25923. SetValueAction.prototype.execute = function () {
  25924. this._target[this._property] = this.value;
  25925. };
  25926. return SetValueAction;
  25927. })(BABYLON.Action);
  25928. BABYLON.SetValueAction = SetValueAction;
  25929. var IncrementValueAction = (function (_super) {
  25930. __extends(IncrementValueAction, _super);
  25931. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25932. _super.call(this, triggerOptions, condition);
  25933. this.propertyPath = propertyPath;
  25934. this.value = value;
  25935. this._target = target;
  25936. }
  25937. IncrementValueAction.prototype._prepare = function () {
  25938. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25939. this._property = this._getProperty(this.propertyPath);
  25940. if (typeof this._target[this._property] !== "number") {
  25941. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25942. }
  25943. };
  25944. IncrementValueAction.prototype.execute = function () {
  25945. this._target[this._property] += this.value;
  25946. };
  25947. return IncrementValueAction;
  25948. })(BABYLON.Action);
  25949. BABYLON.IncrementValueAction = IncrementValueAction;
  25950. var PlayAnimationAction = (function (_super) {
  25951. __extends(PlayAnimationAction, _super);
  25952. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25953. _super.call(this, triggerOptions, condition);
  25954. this.from = from;
  25955. this.to = to;
  25956. this.loop = loop;
  25957. this._target = target;
  25958. }
  25959. PlayAnimationAction.prototype._prepare = function () {
  25960. };
  25961. PlayAnimationAction.prototype.execute = function () {
  25962. var scene = this._actionManager.getScene();
  25963. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25964. };
  25965. return PlayAnimationAction;
  25966. })(BABYLON.Action);
  25967. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25968. var StopAnimationAction = (function (_super) {
  25969. __extends(StopAnimationAction, _super);
  25970. function StopAnimationAction(triggerOptions, target, condition) {
  25971. _super.call(this, triggerOptions, condition);
  25972. this._target = target;
  25973. }
  25974. StopAnimationAction.prototype._prepare = function () {
  25975. };
  25976. StopAnimationAction.prototype.execute = function () {
  25977. var scene = this._actionManager.getScene();
  25978. scene.stopAnimation(this._target);
  25979. };
  25980. return StopAnimationAction;
  25981. })(BABYLON.Action);
  25982. BABYLON.StopAnimationAction = StopAnimationAction;
  25983. var DoNothingAction = (function (_super) {
  25984. __extends(DoNothingAction, _super);
  25985. function DoNothingAction(triggerOptions, condition) {
  25986. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25987. _super.call(this, triggerOptions, condition);
  25988. }
  25989. DoNothingAction.prototype.execute = function () {
  25990. };
  25991. return DoNothingAction;
  25992. })(BABYLON.Action);
  25993. BABYLON.DoNothingAction = DoNothingAction;
  25994. var CombineAction = (function (_super) {
  25995. __extends(CombineAction, _super);
  25996. function CombineAction(triggerOptions, children, condition) {
  25997. _super.call(this, triggerOptions, condition);
  25998. this.children = children;
  25999. }
  26000. CombineAction.prototype._prepare = function () {
  26001. for (var index = 0; index < this.children.length; index++) {
  26002. this.children[index]._actionManager = this._actionManager;
  26003. this.children[index]._prepare();
  26004. }
  26005. };
  26006. CombineAction.prototype.execute = function (evt) {
  26007. for (var index = 0; index < this.children.length; index++) {
  26008. this.children[index].execute(evt);
  26009. }
  26010. };
  26011. return CombineAction;
  26012. })(BABYLON.Action);
  26013. BABYLON.CombineAction = CombineAction;
  26014. var ExecuteCodeAction = (function (_super) {
  26015. __extends(ExecuteCodeAction, _super);
  26016. function ExecuteCodeAction(triggerOptions, func, condition) {
  26017. _super.call(this, triggerOptions, condition);
  26018. this.func = func;
  26019. }
  26020. ExecuteCodeAction.prototype.execute = function (evt) {
  26021. this.func(evt);
  26022. };
  26023. return ExecuteCodeAction;
  26024. })(BABYLON.Action);
  26025. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26026. var SetParentAction = (function (_super) {
  26027. __extends(SetParentAction, _super);
  26028. function SetParentAction(triggerOptions, target, parent, condition) {
  26029. _super.call(this, triggerOptions, condition);
  26030. this._target = target;
  26031. this._parent = parent;
  26032. }
  26033. SetParentAction.prototype._prepare = function () {
  26034. };
  26035. SetParentAction.prototype.execute = function () {
  26036. if (this._target.parent === this._parent) {
  26037. return;
  26038. }
  26039. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26040. invertParentWorldMatrix.invert();
  26041. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26042. this._target.parent = this._parent;
  26043. };
  26044. return SetParentAction;
  26045. })(BABYLON.Action);
  26046. BABYLON.SetParentAction = SetParentAction;
  26047. var PlaySoundAction = (function (_super) {
  26048. __extends(PlaySoundAction, _super);
  26049. function PlaySoundAction(triggerOptions, sound, condition) {
  26050. _super.call(this, triggerOptions, condition);
  26051. this._sound = sound;
  26052. }
  26053. PlaySoundAction.prototype._prepare = function () {
  26054. };
  26055. PlaySoundAction.prototype.execute = function () {
  26056. if (this._sound !== undefined)
  26057. this._sound.play();
  26058. };
  26059. return PlaySoundAction;
  26060. })(BABYLON.Action);
  26061. BABYLON.PlaySoundAction = PlaySoundAction;
  26062. var StopSoundAction = (function (_super) {
  26063. __extends(StopSoundAction, _super);
  26064. function StopSoundAction(triggerOptions, sound, condition) {
  26065. _super.call(this, triggerOptions, condition);
  26066. this._sound = sound;
  26067. }
  26068. StopSoundAction.prototype._prepare = function () {
  26069. };
  26070. StopSoundAction.prototype.execute = function () {
  26071. if (this._sound !== undefined)
  26072. this._sound.stop();
  26073. };
  26074. return StopSoundAction;
  26075. })(BABYLON.Action);
  26076. BABYLON.StopSoundAction = StopSoundAction;
  26077. })(BABYLON || (BABYLON = {}));
  26078. var BABYLON;
  26079. (function (BABYLON) {
  26080. var Geometry = (function () {
  26081. function Geometry(id, scene, vertexData, updatable, mesh) {
  26082. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26083. this._totalVertices = 0;
  26084. this._isDisposed = false;
  26085. this.id = id;
  26086. this._engine = scene.getEngine();
  26087. this._meshes = [];
  26088. this._scene = scene;
  26089. //Init vertex buffer cache
  26090. this._vertexBuffers = {};
  26091. this._indices = [];
  26092. // vertexData
  26093. if (vertexData) {
  26094. this.setAllVerticesData(vertexData, updatable);
  26095. }
  26096. else {
  26097. this._totalVertices = 0;
  26098. this._indices = [];
  26099. }
  26100. // applyToMesh
  26101. if (mesh) {
  26102. this.applyToMesh(mesh);
  26103. mesh.computeWorldMatrix(true);
  26104. }
  26105. }
  26106. Object.defineProperty(Geometry.prototype, "extend", {
  26107. get: function () {
  26108. return this._extend;
  26109. },
  26110. enumerable: true,
  26111. configurable: true
  26112. });
  26113. Geometry.prototype.getScene = function () {
  26114. return this._scene;
  26115. };
  26116. Geometry.prototype.getEngine = function () {
  26117. return this._engine;
  26118. };
  26119. Geometry.prototype.isReady = function () {
  26120. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26121. };
  26122. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26123. vertexData.applyToGeometry(this, updatable);
  26124. this.notifyUpdate();
  26125. };
  26126. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26127. if (this._vertexBuffers[kind]) {
  26128. this._vertexBuffers[kind].dispose();
  26129. }
  26130. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26131. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26132. stride = this._vertexBuffers[kind].getStrideSize();
  26133. this._totalVertices = data.length / stride;
  26134. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26135. var meshes = this._meshes;
  26136. var numOfMeshes = meshes.length;
  26137. for (var index = 0; index < numOfMeshes; index++) {
  26138. var mesh = meshes[index];
  26139. mesh._resetPointsArrayCache();
  26140. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26141. mesh._createGlobalSubMesh();
  26142. mesh.computeWorldMatrix(true);
  26143. }
  26144. }
  26145. this.notifyUpdate(kind);
  26146. };
  26147. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26148. var vertexBuffer = this.getVertexBuffer(kind);
  26149. if (!vertexBuffer) {
  26150. return;
  26151. }
  26152. vertexBuffer.updateDirectly(data, offset);
  26153. this.notifyUpdate(kind);
  26154. };
  26155. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26156. var vertexBuffer = this.getVertexBuffer(kind);
  26157. if (!vertexBuffer) {
  26158. return;
  26159. }
  26160. vertexBuffer.update(data);
  26161. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26162. var stride = vertexBuffer.getStrideSize();
  26163. this._totalVertices = data.length / stride;
  26164. if (updateExtends) {
  26165. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26166. }
  26167. var meshes = this._meshes;
  26168. var numOfMeshes = meshes.length;
  26169. for (var index = 0; index < numOfMeshes; index++) {
  26170. var mesh = meshes[index];
  26171. mesh._resetPointsArrayCache();
  26172. if (updateExtends) {
  26173. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26174. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26175. var subMesh = mesh.subMeshes[subIndex];
  26176. subMesh.refreshBoundingInfo();
  26177. }
  26178. }
  26179. }
  26180. }
  26181. this.notifyUpdate(kind);
  26182. };
  26183. Geometry.prototype.getTotalVertices = function () {
  26184. if (!this.isReady()) {
  26185. return 0;
  26186. }
  26187. return this._totalVertices;
  26188. };
  26189. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26190. var vertexBuffer = this.getVertexBuffer(kind);
  26191. if (!vertexBuffer) {
  26192. return null;
  26193. }
  26194. var orig = vertexBuffer.getData();
  26195. if (!copyWhenShared || this._meshes.length === 1) {
  26196. return orig;
  26197. }
  26198. else {
  26199. var len = orig.length;
  26200. var copy = [];
  26201. for (var i = 0; i < len; i++) {
  26202. copy.push(orig[i]);
  26203. }
  26204. return copy;
  26205. }
  26206. };
  26207. Geometry.prototype.getVertexBuffer = function (kind) {
  26208. if (!this.isReady()) {
  26209. return null;
  26210. }
  26211. return this._vertexBuffers[kind];
  26212. };
  26213. Geometry.prototype.getVertexBuffers = function () {
  26214. if (!this.isReady()) {
  26215. return null;
  26216. }
  26217. return this._vertexBuffers;
  26218. };
  26219. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26220. if (!this._vertexBuffers) {
  26221. if (this._delayInfo) {
  26222. return this._delayInfo.indexOf(kind) !== -1;
  26223. }
  26224. return false;
  26225. }
  26226. return this._vertexBuffers[kind] !== undefined;
  26227. };
  26228. Geometry.prototype.getVerticesDataKinds = function () {
  26229. var result = [];
  26230. var kind;
  26231. if (!this._vertexBuffers && this._delayInfo) {
  26232. for (kind in this._delayInfo) {
  26233. result.push(kind);
  26234. }
  26235. }
  26236. else {
  26237. for (kind in this._vertexBuffers) {
  26238. result.push(kind);
  26239. }
  26240. }
  26241. return result;
  26242. };
  26243. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26244. if (this._indexBuffer) {
  26245. this._engine._releaseBuffer(this._indexBuffer);
  26246. }
  26247. this._indices = indices;
  26248. if (this._meshes.length !== 0 && this._indices) {
  26249. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26250. }
  26251. if (totalVertices !== undefined) {
  26252. this._totalVertices = totalVertices;
  26253. }
  26254. var meshes = this._meshes;
  26255. var numOfMeshes = meshes.length;
  26256. for (var index = 0; index < numOfMeshes; index++) {
  26257. meshes[index]._createGlobalSubMesh();
  26258. }
  26259. this.notifyUpdate();
  26260. };
  26261. Geometry.prototype.getTotalIndices = function () {
  26262. if (!this.isReady()) {
  26263. return 0;
  26264. }
  26265. return this._indices.length;
  26266. };
  26267. Geometry.prototype.getIndices = function (copyWhenShared) {
  26268. if (!this.isReady()) {
  26269. return null;
  26270. }
  26271. var orig = this._indices;
  26272. if (!copyWhenShared || this._meshes.length === 1) {
  26273. return orig;
  26274. }
  26275. else {
  26276. var len = orig.length;
  26277. var copy = [];
  26278. for (var i = 0; i < len; i++) {
  26279. copy.push(orig[i]);
  26280. }
  26281. return copy;
  26282. }
  26283. };
  26284. Geometry.prototype.getIndexBuffer = function () {
  26285. if (!this.isReady()) {
  26286. return null;
  26287. }
  26288. return this._indexBuffer;
  26289. };
  26290. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26291. var meshes = this._meshes;
  26292. var index = meshes.indexOf(mesh);
  26293. if (index === -1) {
  26294. return;
  26295. }
  26296. for (var kind in this._vertexBuffers) {
  26297. this._vertexBuffers[kind].dispose();
  26298. }
  26299. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26300. this._indexBuffer = null;
  26301. }
  26302. meshes.splice(index, 1);
  26303. mesh._geometry = null;
  26304. if (meshes.length === 0 && shouldDispose) {
  26305. this.dispose();
  26306. }
  26307. };
  26308. Geometry.prototype.applyToMesh = function (mesh) {
  26309. if (mesh._geometry === this) {
  26310. return;
  26311. }
  26312. var previousGeometry = mesh._geometry;
  26313. if (previousGeometry) {
  26314. previousGeometry.releaseForMesh(mesh);
  26315. }
  26316. var meshes = this._meshes;
  26317. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26318. mesh._geometry = this;
  26319. this._scene.pushGeometry(this);
  26320. meshes.push(mesh);
  26321. if (this.isReady()) {
  26322. this._applyToMesh(mesh);
  26323. }
  26324. else {
  26325. mesh._boundingInfo = this._boundingInfo;
  26326. }
  26327. };
  26328. Geometry.prototype._applyToMesh = function (mesh) {
  26329. var numOfMeshes = this._meshes.length;
  26330. // vertexBuffers
  26331. for (var kind in this._vertexBuffers) {
  26332. if (numOfMeshes === 1) {
  26333. this._vertexBuffers[kind].create();
  26334. }
  26335. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26336. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26337. mesh._resetPointsArrayCache();
  26338. if (!this._extend) {
  26339. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26340. }
  26341. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26342. mesh._createGlobalSubMesh();
  26343. //bounding info was just created again, world matrix should be applied again.
  26344. mesh._updateBoundingInfo();
  26345. }
  26346. }
  26347. // indexBuffer
  26348. if (numOfMeshes === 1 && this._indices) {
  26349. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26350. }
  26351. if (this._indexBuffer) {
  26352. this._indexBuffer.references = numOfMeshes;
  26353. }
  26354. };
  26355. Geometry.prototype.notifyUpdate = function (kind) {
  26356. if (this.onGeometryUpdated) {
  26357. this.onGeometryUpdated(this, kind);
  26358. }
  26359. };
  26360. Geometry.prototype.load = function (scene, onLoaded) {
  26361. var _this = this;
  26362. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26363. return;
  26364. }
  26365. if (this.isReady()) {
  26366. if (onLoaded) {
  26367. onLoaded();
  26368. }
  26369. return;
  26370. }
  26371. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26372. scene._addPendingData(this);
  26373. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26374. _this._delayLoadingFunction(JSON.parse(data), _this);
  26375. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26376. _this._delayInfo = [];
  26377. scene._removePendingData(_this);
  26378. var meshes = _this._meshes;
  26379. var numOfMeshes = meshes.length;
  26380. for (var index = 0; index < numOfMeshes; index++) {
  26381. _this._applyToMesh(meshes[index]);
  26382. }
  26383. if (onLoaded) {
  26384. onLoaded();
  26385. }
  26386. }, function () { }, scene.database);
  26387. };
  26388. Geometry.prototype.isDisposed = function () {
  26389. return this._isDisposed;
  26390. };
  26391. Geometry.prototype.dispose = function () {
  26392. var meshes = this._meshes;
  26393. var numOfMeshes = meshes.length;
  26394. var index;
  26395. for (index = 0; index < numOfMeshes; index++) {
  26396. this.releaseForMesh(meshes[index]);
  26397. }
  26398. this._meshes = [];
  26399. for (var kind in this._vertexBuffers) {
  26400. this._vertexBuffers[kind].dispose();
  26401. }
  26402. this._vertexBuffers = [];
  26403. this._totalVertices = 0;
  26404. if (this._indexBuffer) {
  26405. this._engine._releaseBuffer(this._indexBuffer);
  26406. }
  26407. this._indexBuffer = null;
  26408. this._indices = [];
  26409. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26410. this.delayLoadingFile = null;
  26411. this._delayLoadingFunction = null;
  26412. this._delayInfo = [];
  26413. this._boundingInfo = null;
  26414. this._scene.removeGeometry(this);
  26415. this._isDisposed = true;
  26416. };
  26417. Geometry.prototype.copy = function (id) {
  26418. var vertexData = new BABYLON.VertexData();
  26419. vertexData.indices = [];
  26420. var indices = this.getIndices();
  26421. for (var index = 0; index < indices.length; index++) {
  26422. vertexData.indices.push(indices[index]);
  26423. }
  26424. var updatable = false;
  26425. var stopChecking = false;
  26426. var kind;
  26427. for (kind in this._vertexBuffers) {
  26428. // using slice() to make a copy of the array and not just reference it
  26429. var data = this.getVerticesData(kind);
  26430. if (data instanceof Float32Array) {
  26431. vertexData.set(new Float32Array(data), kind);
  26432. }
  26433. else {
  26434. vertexData.set(data.slice(0), kind);
  26435. }
  26436. if (!stopChecking) {
  26437. updatable = this.getVertexBuffer(kind).isUpdatable();
  26438. stopChecking = !updatable;
  26439. }
  26440. }
  26441. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26442. geometry.delayLoadState = this.delayLoadState;
  26443. geometry.delayLoadingFile = this.delayLoadingFile;
  26444. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26445. for (kind in this._delayInfo) {
  26446. geometry._delayInfo = geometry._delayInfo || [];
  26447. geometry._delayInfo.push(kind);
  26448. }
  26449. // Bounding info
  26450. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26451. return geometry;
  26452. };
  26453. // Statics
  26454. Geometry.ExtractFromMesh = function (mesh, id) {
  26455. var geometry = mesh._geometry;
  26456. if (!geometry) {
  26457. return null;
  26458. }
  26459. return geometry.copy(id);
  26460. };
  26461. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26462. // be aware Math.random() could cause collisions
  26463. Geometry.RandomId = function () {
  26464. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26465. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26466. return v.toString(16);
  26467. });
  26468. };
  26469. return Geometry;
  26470. })();
  26471. BABYLON.Geometry = Geometry;
  26472. /////// Primitives //////////////////////////////////////////////
  26473. var Geometry;
  26474. (function (Geometry) {
  26475. var Primitives;
  26476. (function (Primitives) {
  26477. /// Abstract class
  26478. var _Primitive = (function (_super) {
  26479. __extends(_Primitive, _super);
  26480. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26481. this._beingRegenerated = true;
  26482. this._canBeRegenerated = canBeRegenerated;
  26483. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26484. this._beingRegenerated = false;
  26485. }
  26486. _Primitive.prototype.canBeRegenerated = function () {
  26487. return this._canBeRegenerated;
  26488. };
  26489. _Primitive.prototype.regenerate = function () {
  26490. if (!this._canBeRegenerated) {
  26491. return;
  26492. }
  26493. this._beingRegenerated = true;
  26494. this.setAllVerticesData(this._regenerateVertexData(), false);
  26495. this._beingRegenerated = false;
  26496. };
  26497. _Primitive.prototype.asNewGeometry = function (id) {
  26498. return _super.prototype.copy.call(this, id);
  26499. };
  26500. // overrides
  26501. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26502. if (!this._beingRegenerated) {
  26503. return;
  26504. }
  26505. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26506. };
  26507. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26508. if (!this._beingRegenerated) {
  26509. return;
  26510. }
  26511. _super.prototype.setVerticesData.call(this, kind, data, false);
  26512. };
  26513. // to override
  26514. // protected
  26515. _Primitive.prototype._regenerateVertexData = function () {
  26516. throw new Error("Abstract method");
  26517. };
  26518. _Primitive.prototype.copy = function (id) {
  26519. throw new Error("Must be overriden in sub-classes.");
  26520. };
  26521. return _Primitive;
  26522. })(Geometry);
  26523. Primitives._Primitive = _Primitive;
  26524. var Ribbon = (function (_super) {
  26525. __extends(Ribbon, _super);
  26526. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26527. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26528. this.pathArray = pathArray;
  26529. this.closeArray = closeArray;
  26530. this.closePath = closePath;
  26531. this.offset = offset;
  26532. this.side = side;
  26533. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26534. }
  26535. Ribbon.prototype._regenerateVertexData = function () {
  26536. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26537. };
  26538. Ribbon.prototype.copy = function (id) {
  26539. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26540. };
  26541. return Ribbon;
  26542. })(_Primitive);
  26543. Primitives.Ribbon = Ribbon;
  26544. var Box = (function (_super) {
  26545. __extends(Box, _super);
  26546. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26547. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26548. this.size = size;
  26549. this.side = side;
  26550. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26551. }
  26552. Box.prototype._regenerateVertexData = function () {
  26553. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26554. };
  26555. Box.prototype.copy = function (id) {
  26556. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26557. };
  26558. return Box;
  26559. })(_Primitive);
  26560. Primitives.Box = Box;
  26561. var Sphere = (function (_super) {
  26562. __extends(Sphere, _super);
  26563. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26564. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26565. this.segments = segments;
  26566. this.diameter = diameter;
  26567. this.side = side;
  26568. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26569. }
  26570. Sphere.prototype._regenerateVertexData = function () {
  26571. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26572. };
  26573. Sphere.prototype.copy = function (id) {
  26574. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26575. };
  26576. return Sphere;
  26577. })(_Primitive);
  26578. Primitives.Sphere = Sphere;
  26579. var Disc = (function (_super) {
  26580. __extends(Disc, _super);
  26581. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26582. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26583. this.radius = radius;
  26584. this.tessellation = tessellation;
  26585. this.side = side;
  26586. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26587. }
  26588. Disc.prototype._regenerateVertexData = function () {
  26589. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26590. };
  26591. Disc.prototype.copy = function (id) {
  26592. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26593. };
  26594. return Disc;
  26595. })(_Primitive);
  26596. Primitives.Disc = Disc;
  26597. var Cylinder = (function (_super) {
  26598. __extends(Cylinder, _super);
  26599. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26600. if (subdivisions === void 0) { subdivisions = 1; }
  26601. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26602. this.height = height;
  26603. this.diameterTop = diameterTop;
  26604. this.diameterBottom = diameterBottom;
  26605. this.tessellation = tessellation;
  26606. this.subdivisions = subdivisions;
  26607. this.side = side;
  26608. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26609. }
  26610. Cylinder.prototype._regenerateVertexData = function () {
  26611. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26612. };
  26613. Cylinder.prototype.copy = function (id) {
  26614. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26615. };
  26616. return Cylinder;
  26617. })(_Primitive);
  26618. Primitives.Cylinder = Cylinder;
  26619. var Torus = (function (_super) {
  26620. __extends(Torus, _super);
  26621. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26622. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26623. this.diameter = diameter;
  26624. this.thickness = thickness;
  26625. this.tessellation = tessellation;
  26626. this.side = side;
  26627. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26628. }
  26629. Torus.prototype._regenerateVertexData = function () {
  26630. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26631. };
  26632. Torus.prototype.copy = function (id) {
  26633. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26634. };
  26635. return Torus;
  26636. })(_Primitive);
  26637. Primitives.Torus = Torus;
  26638. var Ground = (function (_super) {
  26639. __extends(Ground, _super);
  26640. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26641. this.width = width;
  26642. this.height = height;
  26643. this.subdivisions = subdivisions;
  26644. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26645. }
  26646. Ground.prototype._regenerateVertexData = function () {
  26647. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26648. };
  26649. Ground.prototype.copy = function (id) {
  26650. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26651. };
  26652. return Ground;
  26653. })(_Primitive);
  26654. Primitives.Ground = Ground;
  26655. var TiledGround = (function (_super) {
  26656. __extends(TiledGround, _super);
  26657. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26658. this.xmin = xmin;
  26659. this.zmin = zmin;
  26660. this.xmax = xmax;
  26661. this.zmax = zmax;
  26662. this.subdivisions = subdivisions;
  26663. this.precision = precision;
  26664. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26665. }
  26666. TiledGround.prototype._regenerateVertexData = function () {
  26667. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26668. };
  26669. TiledGround.prototype.copy = function (id) {
  26670. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26671. };
  26672. return TiledGround;
  26673. })(_Primitive);
  26674. Primitives.TiledGround = TiledGround;
  26675. var Plane = (function (_super) {
  26676. __extends(Plane, _super);
  26677. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26678. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26679. this.size = size;
  26680. this.side = side;
  26681. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26682. }
  26683. Plane.prototype._regenerateVertexData = function () {
  26684. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26685. };
  26686. Plane.prototype.copy = function (id) {
  26687. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26688. };
  26689. return Plane;
  26690. })(_Primitive);
  26691. Primitives.Plane = Plane;
  26692. var TorusKnot = (function (_super) {
  26693. __extends(TorusKnot, _super);
  26694. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26695. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26696. this.radius = radius;
  26697. this.tube = tube;
  26698. this.radialSegments = radialSegments;
  26699. this.tubularSegments = tubularSegments;
  26700. this.p = p;
  26701. this.q = q;
  26702. this.side = side;
  26703. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26704. }
  26705. TorusKnot.prototype._regenerateVertexData = function () {
  26706. 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 });
  26707. };
  26708. TorusKnot.prototype.copy = function (id) {
  26709. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26710. };
  26711. return TorusKnot;
  26712. })(_Primitive);
  26713. Primitives.TorusKnot = TorusKnot;
  26714. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26715. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26716. })(BABYLON || (BABYLON = {}));
  26717. var BABYLON;
  26718. (function (BABYLON) {
  26719. var GroundMesh = (function (_super) {
  26720. __extends(GroundMesh, _super);
  26721. function GroundMesh(name, scene) {
  26722. _super.call(this, name, scene);
  26723. this.generateOctree = false;
  26724. this._worldInverse = new BABYLON.Matrix();
  26725. }
  26726. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26727. get: function () {
  26728. return this._subdivisions;
  26729. },
  26730. enumerable: true,
  26731. configurable: true
  26732. });
  26733. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26734. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26735. this._subdivisions = chunksCount;
  26736. this.subdivide(this._subdivisions);
  26737. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26738. };
  26739. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26740. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26741. this.getWorldMatrix().invertToRef(this._worldInverse);
  26742. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26743. var pickInfo = this.intersects(ray);
  26744. if (pickInfo.hit) {
  26745. return pickInfo.pickedPoint.y;
  26746. }
  26747. return 0;
  26748. };
  26749. return GroundMesh;
  26750. })(BABYLON.Mesh);
  26751. BABYLON.GroundMesh = GroundMesh;
  26752. })(BABYLON || (BABYLON = {}));
  26753. var BABYLON;
  26754. (function (BABYLON) {
  26755. var LinesMesh = (function (_super) {
  26756. __extends(LinesMesh, _super);
  26757. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26758. if (parent === void 0) { parent = null; }
  26759. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26760. this.color = new BABYLON.Color3(1, 1, 1);
  26761. this.alpha = 1;
  26762. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26763. attributes: ["position"],
  26764. uniforms: ["worldViewProjection", "color"],
  26765. needAlphaBlending: true
  26766. });
  26767. }
  26768. Object.defineProperty(LinesMesh.prototype, "material", {
  26769. get: function () {
  26770. return this._colorShader;
  26771. },
  26772. enumerable: true,
  26773. configurable: true
  26774. });
  26775. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26776. get: function () {
  26777. return false;
  26778. },
  26779. enumerable: true,
  26780. configurable: true
  26781. });
  26782. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26783. get: function () {
  26784. return false;
  26785. },
  26786. enumerable: true,
  26787. configurable: true
  26788. });
  26789. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26790. var engine = this.getScene().getEngine();
  26791. var indexToBind = this._geometry.getIndexBuffer();
  26792. // VBOs
  26793. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26794. // Color
  26795. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26796. };
  26797. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26798. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26799. return;
  26800. }
  26801. var engine = this.getScene().getEngine();
  26802. // Draw order
  26803. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26804. };
  26805. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26806. return null;
  26807. };
  26808. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26809. this._colorShader.dispose();
  26810. _super.prototype.dispose.call(this, doNotRecurse);
  26811. };
  26812. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  26813. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  26814. };
  26815. return LinesMesh;
  26816. })(BABYLON.Mesh);
  26817. BABYLON.LinesMesh = LinesMesh;
  26818. })(BABYLON || (BABYLON = {}));
  26819. var BABYLON;
  26820. (function (BABYLON) {
  26821. var DebugLayer = (function () {
  26822. function DebugLayer(scene) {
  26823. var _this = this;
  26824. this._transformationMatrix = BABYLON.Matrix.Identity();
  26825. this._enabled = false;
  26826. this._labelsEnabled = false;
  26827. this._displayStatistics = true;
  26828. this._displayTree = false;
  26829. this._displayLogs = false;
  26830. this._identityMatrix = BABYLON.Matrix.Identity();
  26831. this.axisRatio = 0.02;
  26832. this.accentColor = "orange";
  26833. this._scene = scene;
  26834. this._syncPositions = function () {
  26835. var engine = _this._scene.getEngine();
  26836. var canvasRect = engine.getRenderingCanvasClientRect();
  26837. if (_this._showUI) {
  26838. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26839. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26840. _this._statsDiv.style.width = "400px";
  26841. _this._statsDiv.style.height = "auto";
  26842. _this._statsSubsetDiv.style.maxHeight = "240px";
  26843. _this._optionsDiv.style.left = "0px";
  26844. _this._optionsDiv.style.top = "10px";
  26845. _this._optionsDiv.style.width = "200px";
  26846. _this._optionsDiv.style.height = "auto";
  26847. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26848. _this._logDiv.style.left = "0px";
  26849. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26850. _this._logDiv.style.width = "600px";
  26851. _this._logDiv.style.height = "160px";
  26852. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26853. _this._treeDiv.style.top = "10px";
  26854. _this._treeDiv.style.width = "300px";
  26855. _this._treeDiv.style.height = "auto";
  26856. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26857. }
  26858. _this._globalDiv.style.left = canvasRect.left + "px";
  26859. _this._globalDiv.style.top = canvasRect.top + "px";
  26860. _this._drawingCanvas.style.left = "0px";
  26861. _this._drawingCanvas.style.top = "0px";
  26862. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26863. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26864. var devicePixelRatio = window.devicePixelRatio || 1;
  26865. var context = _this._drawingContext;
  26866. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  26867. context.mozBackingStorePixelRatio ||
  26868. context.msBackingStorePixelRatio ||
  26869. context.oBackingStorePixelRatio ||
  26870. context.backingStorePixelRatio || 1;
  26871. _this._ratio = devicePixelRatio / backingStoreRatio;
  26872. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26873. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26874. };
  26875. this._onCanvasClick = function (evt) {
  26876. _this._clickPosition = {
  26877. x: evt.clientX * _this._ratio,
  26878. y: evt.clientY * _this._ratio
  26879. };
  26880. };
  26881. this._syncUI = function () {
  26882. if (_this._showUI) {
  26883. if (_this._displayStatistics) {
  26884. _this._displayStats();
  26885. _this._statsDiv.style.display = "";
  26886. }
  26887. else {
  26888. _this._statsDiv.style.display = "none";
  26889. }
  26890. if (_this._displayLogs) {
  26891. _this._logDiv.style.display = "";
  26892. }
  26893. else {
  26894. _this._logDiv.style.display = "none";
  26895. }
  26896. if (_this._displayTree) {
  26897. _this._treeDiv.style.display = "";
  26898. if (_this._needToRefreshMeshesTree) {
  26899. _this._needToRefreshMeshesTree = false;
  26900. _this._refreshMeshesTreeContent();
  26901. }
  26902. }
  26903. else {
  26904. _this._treeDiv.style.display = "none";
  26905. }
  26906. }
  26907. };
  26908. this._syncData = function () {
  26909. if (_this._labelsEnabled || !_this._showUI) {
  26910. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26911. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26912. var engine = _this._scene.getEngine();
  26913. var viewport = _this._camera.viewport;
  26914. var globalViewport = viewport.toGlobal(engine);
  26915. // Meshes
  26916. var meshes = _this._camera.getActiveMeshes();
  26917. var index;
  26918. var projectedPosition;
  26919. for (index = 0; index < meshes.length; index++) {
  26920. var mesh = meshes.data[index];
  26921. var position = mesh.getBoundingInfo().boundingSphere.center;
  26922. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26923. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26924. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26925. }
  26926. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26927. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  26928. }
  26929. }
  26930. // Cameras
  26931. var cameras = _this._scene.cameras;
  26932. for (index = 0; index < cameras.length; index++) {
  26933. var camera = cameras[index];
  26934. if (camera === _this._camera) {
  26935. continue;
  26936. }
  26937. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26938. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26939. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26940. _this._camera.detachControl(engine.getRenderingCanvas());
  26941. _this._camera = camera;
  26942. _this._camera.attachControl(engine.getRenderingCanvas());
  26943. }, function () { return "purple"; });
  26944. }
  26945. }
  26946. // Lights
  26947. var lights = _this._scene.lights;
  26948. for (index = 0; index < lights.length; index++) {
  26949. var light = lights[index];
  26950. if (light.position) {
  26951. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26952. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26953. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26954. light.setEnabled(!light.isEnabled());
  26955. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  26956. }
  26957. }
  26958. }
  26959. }
  26960. _this._clickPosition = undefined;
  26961. };
  26962. }
  26963. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26964. while (this._treeSubsetDiv.hasChildNodes()) {
  26965. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26966. }
  26967. // Add meshes
  26968. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26969. sortedArray.sort(function (a, b) {
  26970. if (a.name === b.name) {
  26971. return 0;
  26972. }
  26973. return (a.name > b.name) ? 1 : -1;
  26974. });
  26975. for (var index = 0; index < sortedArray.length; index++) {
  26976. var mesh = sortedArray[index];
  26977. if (!mesh.isEnabled()) {
  26978. continue;
  26979. }
  26980. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26981. m.isVisible = element.checked;
  26982. }, mesh);
  26983. }
  26984. };
  26985. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26986. this._drawingContext.beginPath();
  26987. this._drawingContext.moveTo(zero.x, zero.y);
  26988. this._drawingContext.lineTo(unit.x, unit.y);
  26989. this._drawingContext.strokeStyle = color;
  26990. this._drawingContext.lineWidth = 4;
  26991. this._drawingContext.stroke();
  26992. this._drawingContext.font = "normal 14px Segoe UI";
  26993. this._drawingContext.fillStyle = color;
  26994. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26995. };
  26996. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26997. var position = mesh.getBoundingInfo().boundingSphere.center;
  26998. var worldMatrix = mesh.getWorldMatrix();
  26999. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27000. var unit = (unprojectedVector.subtract(position)).length();
  27001. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27002. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27003. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27004. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27005. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27006. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27007. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27008. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27009. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27010. };
  27011. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27012. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27013. this._drawingContext.font = "normal 12px Segoe UI";
  27014. var textMetrics = this._drawingContext.measureText(text);
  27015. var centerX = projectedPosition.x - textMetrics.width / 2;
  27016. var centerY = projectedPosition.y;
  27017. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27018. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27019. onClick();
  27020. }
  27021. this._drawingContext.beginPath();
  27022. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27023. this._drawingContext.fillStyle = getFillStyle();
  27024. this._drawingContext.globalAlpha = 0.5;
  27025. this._drawingContext.fill();
  27026. this._drawingContext.globalAlpha = 1.0;
  27027. this._drawingContext.strokeStyle = '#FFFFFF';
  27028. this._drawingContext.lineWidth = 1;
  27029. this._drawingContext.stroke();
  27030. this._drawingContext.fillStyle = "#FFFFFF";
  27031. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27032. this._drawingContext.beginPath();
  27033. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27034. this._drawingContext.fill();
  27035. }
  27036. };
  27037. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27038. if (!this._clickPosition) {
  27039. return false;
  27040. }
  27041. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27042. return false;
  27043. }
  27044. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27045. return false;
  27046. }
  27047. return true;
  27048. };
  27049. DebugLayer.prototype.isVisible = function () {
  27050. return this._enabled;
  27051. };
  27052. DebugLayer.prototype.hide = function () {
  27053. if (!this._enabled) {
  27054. return;
  27055. }
  27056. this._enabled = false;
  27057. var engine = this._scene.getEngine();
  27058. this._scene.unregisterBeforeRender(this._syncData);
  27059. this._scene.unregisterAfterRender(this._syncUI);
  27060. this._rootElement.removeChild(this._globalDiv);
  27061. this._scene.forceShowBoundingBoxes = false;
  27062. this._scene.forceWireframe = false;
  27063. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27064. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27065. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27066. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27067. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27068. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27069. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27070. BABYLON.StandardMaterial.LightmapEnabled = true;
  27071. this._scene.shadowsEnabled = true;
  27072. this._scene.particlesEnabled = true;
  27073. this._scene.postProcessesEnabled = true;
  27074. this._scene.collisionsEnabled = true;
  27075. this._scene.lightsEnabled = true;
  27076. this._scene.texturesEnabled = true;
  27077. this._scene.lensFlaresEnabled = true;
  27078. this._scene.proceduralTexturesEnabled = true;
  27079. this._scene.renderTargetsEnabled = true;
  27080. this._scene.probesEnabled = true;
  27081. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27082. };
  27083. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  27084. if (showUI === void 0) { showUI = true; }
  27085. if (camera === void 0) { camera = null; }
  27086. if (rootElement === void 0) { rootElement = null; }
  27087. if (this._enabled) {
  27088. return;
  27089. }
  27090. this._enabled = true;
  27091. if (camera) {
  27092. this._camera = camera;
  27093. }
  27094. else {
  27095. this._camera = this._scene.activeCamera;
  27096. }
  27097. this._showUI = showUI;
  27098. var engine = this._scene.getEngine();
  27099. this._globalDiv = document.createElement("div");
  27100. this._rootElement = rootElement || document.body;
  27101. this._rootElement.appendChild(this._globalDiv);
  27102. this._generateDOMelements();
  27103. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27104. this._syncPositions();
  27105. this._scene.registerBeforeRender(this._syncData);
  27106. this._scene.registerAfterRender(this._syncUI);
  27107. };
  27108. DebugLayer.prototype._clearLabels = function () {
  27109. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27110. for (var index = 0; index < this._scene.meshes.length; index++) {
  27111. var mesh = this._scene.meshes[index];
  27112. mesh.renderOverlay = false;
  27113. }
  27114. };
  27115. DebugLayer.prototype._generateheader = function (root, text) {
  27116. var header = document.createElement("div");
  27117. header.innerHTML = text + "&nbsp;";
  27118. header.style.textAlign = "right";
  27119. header.style.width = "100%";
  27120. header.style.color = "white";
  27121. header.style.backgroundColor = "Black";
  27122. header.style.padding = "5px 5px 4px 0px";
  27123. header.style.marginLeft = "-5px";
  27124. header.style.fontWeight = "bold";
  27125. root.appendChild(header);
  27126. };
  27127. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27128. var label = document.createElement("label");
  27129. label.innerHTML = title;
  27130. label.style.color = color;
  27131. root.appendChild(label);
  27132. root.appendChild(document.createElement("br"));
  27133. };
  27134. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27135. if (tag === void 0) { tag = null; }
  27136. var label = document.createElement("label");
  27137. var boundingBoxesCheckbox = document.createElement("input");
  27138. boundingBoxesCheckbox.type = "checkbox";
  27139. boundingBoxesCheckbox.checked = initialState;
  27140. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27141. task(evt.target, tag);
  27142. });
  27143. label.appendChild(boundingBoxesCheckbox);
  27144. var container = document.createElement("span");
  27145. var leftPart = document.createElement("span");
  27146. var rightPart = document.createElement("span");
  27147. rightPart.style.cssFloat = "right";
  27148. leftPart.innerHTML = leftTitle;
  27149. rightPart.innerHTML = rightTitle;
  27150. rightPart.style.fontSize = "12px";
  27151. rightPart.style.maxWidth = "200px";
  27152. container.appendChild(leftPart);
  27153. container.appendChild(rightPart);
  27154. label.appendChild(container);
  27155. root.appendChild(label);
  27156. root.appendChild(document.createElement("br"));
  27157. };
  27158. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27159. if (tag === void 0) { tag = null; }
  27160. var label = document.createElement("label");
  27161. var checkBox = document.createElement("input");
  27162. checkBox.type = "checkbox";
  27163. checkBox.checked = initialState;
  27164. checkBox.addEventListener("change", function (evt) {
  27165. task(evt.target, tag);
  27166. });
  27167. label.appendChild(checkBox);
  27168. label.appendChild(document.createTextNode(title));
  27169. root.appendChild(label);
  27170. root.appendChild(document.createElement("br"));
  27171. };
  27172. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27173. if (tag === void 0) { tag = null; }
  27174. var button = document.createElement("button");
  27175. button.innerHTML = title;
  27176. button.style.height = "24px";
  27177. button.style.width = "150px";
  27178. button.style.marginBottom = "5px";
  27179. button.style.color = "#444444";
  27180. button.style.border = "1px solid white";
  27181. button.className = "debugLayerButton";
  27182. button.addEventListener("click", function (evt) {
  27183. task(evt.target, tag);
  27184. });
  27185. root.appendChild(button);
  27186. root.appendChild(document.createElement("br"));
  27187. };
  27188. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27189. if (tag === void 0) { tag = null; }
  27190. var label = document.createElement("label");
  27191. var boundingBoxesRadio = document.createElement("input");
  27192. boundingBoxesRadio.type = "radio";
  27193. boundingBoxesRadio.name = name;
  27194. boundingBoxesRadio.checked = initialState;
  27195. boundingBoxesRadio.addEventListener("change", function (evt) {
  27196. task(evt.target, tag);
  27197. });
  27198. label.appendChild(boundingBoxesRadio);
  27199. label.appendChild(document.createTextNode(title));
  27200. root.appendChild(label);
  27201. root.appendChild(document.createElement("br"));
  27202. };
  27203. DebugLayer.prototype._generateDOMelements = function () {
  27204. var _this = this;
  27205. this._globalDiv.id = "DebugLayer";
  27206. this._globalDiv.style.position = "absolute";
  27207. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27208. this._globalDiv.style.fontSize = "14px";
  27209. this._globalDiv.style.color = "white";
  27210. // Drawing canvas
  27211. this._drawingCanvas = document.createElement("canvas");
  27212. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27213. this._drawingCanvas.style.position = "absolute";
  27214. this._drawingCanvas.style.pointerEvents = "none";
  27215. this._drawingCanvas.style.backgroundColor = "transparent";
  27216. this._drawingContext = this._drawingCanvas.getContext("2d");
  27217. this._globalDiv.appendChild(this._drawingCanvas);
  27218. if (this._showUI) {
  27219. var background = "rgba(128, 128, 128, 0.4)";
  27220. var border = "rgb(180, 180, 180) solid 1px";
  27221. // Stats
  27222. this._statsDiv = document.createElement("div");
  27223. this._statsDiv.id = "DebugLayerStats";
  27224. this._statsDiv.style.border = border;
  27225. this._statsDiv.style.position = "absolute";
  27226. this._statsDiv.style.background = background;
  27227. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27228. this._generateheader(this._statsDiv, "STATISTICS");
  27229. this._statsSubsetDiv = document.createElement("div");
  27230. this._statsSubsetDiv.style.paddingTop = "5px";
  27231. this._statsSubsetDiv.style.paddingBottom = "5px";
  27232. this._statsSubsetDiv.style.overflowY = "auto";
  27233. this._statsDiv.appendChild(this._statsSubsetDiv);
  27234. // Tree
  27235. this._treeDiv = document.createElement("div");
  27236. this._treeDiv.id = "DebugLayerTree";
  27237. this._treeDiv.style.border = border;
  27238. this._treeDiv.style.position = "absolute";
  27239. this._treeDiv.style.background = background;
  27240. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27241. this._treeDiv.style.display = "none";
  27242. this._generateheader(this._treeDiv, "MESHES TREE");
  27243. this._treeSubsetDiv = document.createElement("div");
  27244. this._treeSubsetDiv.style.paddingTop = "5px";
  27245. this._treeSubsetDiv.style.paddingRight = "5px";
  27246. this._treeSubsetDiv.style.overflowY = "auto";
  27247. this._treeSubsetDiv.style.maxHeight = "300px";
  27248. this._treeDiv.appendChild(this._treeSubsetDiv);
  27249. this._needToRefreshMeshesTree = true;
  27250. // Logs
  27251. this._logDiv = document.createElement("div");
  27252. this._logDiv.style.border = border;
  27253. this._logDiv.id = "DebugLayerLogs";
  27254. this._logDiv.style.position = "absolute";
  27255. this._logDiv.style.background = background;
  27256. this._logDiv.style.padding = "0px 0px 0px 5px";
  27257. this._logDiv.style.display = "none";
  27258. this._generateheader(this._logDiv, "LOGS");
  27259. this._logSubsetDiv = document.createElement("div");
  27260. this._logSubsetDiv.style.height = "127px";
  27261. this._logSubsetDiv.style.paddingTop = "5px";
  27262. this._logSubsetDiv.style.overflowY = "auto";
  27263. this._logSubsetDiv.style.fontSize = "12px";
  27264. this._logSubsetDiv.style.fontFamily = "consolas";
  27265. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27266. this._logDiv.appendChild(this._logSubsetDiv);
  27267. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27268. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27269. };
  27270. // Options
  27271. this._optionsDiv = document.createElement("div");
  27272. this._optionsDiv.id = "DebugLayerOptions";
  27273. this._optionsDiv.style.border = border;
  27274. this._optionsDiv.style.position = "absolute";
  27275. this._optionsDiv.style.background = background;
  27276. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27277. this._optionsDiv.style.overflowY = "auto";
  27278. this._generateheader(this._optionsDiv, "OPTIONS");
  27279. this._optionsSubsetDiv = document.createElement("div");
  27280. this._optionsSubsetDiv.style.paddingTop = "5px";
  27281. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27282. this._optionsSubsetDiv.style.overflowY = "auto";
  27283. this._optionsSubsetDiv.style.maxHeight = "200px";
  27284. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27285. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27286. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27287. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27288. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27289. _this._displayTree = element.checked;
  27290. _this._needToRefreshMeshesTree = true;
  27291. });
  27292. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27293. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27294. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27295. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27296. _this._labelsEnabled = element.checked;
  27297. if (!_this._labelsEnabled) {
  27298. _this._clearLabels();
  27299. }
  27300. });
  27301. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27302. if (element.checked) {
  27303. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27304. }
  27305. else {
  27306. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27307. }
  27308. });
  27309. ;
  27310. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27311. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27312. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27313. if (element.checked) {
  27314. _this._scene.forceWireframe = false;
  27315. _this._scene.forcePointsCloud = false;
  27316. }
  27317. });
  27318. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27319. if (element.checked) {
  27320. _this._scene.forceWireframe = true;
  27321. _this._scene.forcePointsCloud = false;
  27322. }
  27323. });
  27324. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27325. if (element.checked) {
  27326. _this._scene.forceWireframe = false;
  27327. _this._scene.forcePointsCloud = true;
  27328. }
  27329. });
  27330. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27331. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27332. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27333. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27334. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27335. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27336. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27337. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27338. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27339. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27340. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27341. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27342. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27343. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27344. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27345. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27346. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27347. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27348. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27349. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27350. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27351. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27352. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27353. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27354. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27355. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27356. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27357. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27358. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27359. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27360. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27361. if (element.checked) {
  27362. _this._scene.headphone = true;
  27363. }
  27364. });
  27365. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27366. if (element.checked) {
  27367. _this._scene.headphone = false;
  27368. }
  27369. });
  27370. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27371. _this._scene.audioEnabled = !element.checked;
  27372. });
  27373. }
  27374. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27375. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27376. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27377. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27378. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27379. this._globalDiv.appendChild(this._statsDiv);
  27380. this._globalDiv.appendChild(this._logDiv);
  27381. this._globalDiv.appendChild(this._optionsDiv);
  27382. this._globalDiv.appendChild(this._treeDiv);
  27383. }
  27384. };
  27385. DebugLayer.prototype._displayStats = function () {
  27386. var scene = this._scene;
  27387. var engine = scene.getEngine();
  27388. var glInfo = engine.getGlInfo();
  27389. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27390. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27391. + "<b>Count</b><br>"
  27392. + "Total meshes: " + scene.meshes.length + "<br>"
  27393. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27394. + "Total materials: " + scene.materials.length + "<br>"
  27395. + "Total textures: " + scene.textures.length + "<br>"
  27396. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27397. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27398. + "Active bones: " + scene.getActiveBones() + "<br>"
  27399. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27400. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27401. + "<b>Duration</b><br>"
  27402. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27403. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27404. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27405. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27406. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27407. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27408. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27409. + "</div>"
  27410. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27411. + "<b>Extensions</b><br>"
  27412. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27413. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27414. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27415. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27416. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27417. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  27418. + "<b>Caps.</b><br>"
  27419. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27420. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27421. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27422. + "</div><br>"
  27423. + "<b>Info</b><br>"
  27424. + glInfo.version + "<br>"
  27425. + glInfo.renderer + "<br>";
  27426. if (this.customStatsFunction) {
  27427. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27428. }
  27429. };
  27430. return DebugLayer;
  27431. })();
  27432. BABYLON.DebugLayer = DebugLayer;
  27433. })(BABYLON || (BABYLON = {}));
  27434. var BABYLON;
  27435. (function (BABYLON) {
  27436. var DefaultLoadingScreen = (function () {
  27437. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27438. var _this = this;
  27439. if (_loadingText === void 0) { _loadingText = ""; }
  27440. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27441. this._renderingCanvas = _renderingCanvas;
  27442. this._loadingText = _loadingText;
  27443. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27444. // Resize
  27445. this._resizeLoadingUI = function () {
  27446. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27447. _this._loadingDiv.style.position = "absolute";
  27448. _this._loadingDiv.style.left = canvasRect.left + "px";
  27449. _this._loadingDiv.style.top = canvasRect.top + "px";
  27450. _this._loadingDiv.style.width = canvasRect.width + "px";
  27451. _this._loadingDiv.style.height = canvasRect.height + "px";
  27452. };
  27453. }
  27454. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27455. var _this = this;
  27456. this._loadingDiv = document.createElement("div");
  27457. this._loadingDiv.id = "babylonjsLoadingDiv";
  27458. this._loadingDiv.style.opacity = "0";
  27459. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27460. // Loading text
  27461. this._loadingTextDiv = document.createElement("div");
  27462. this._loadingTextDiv.style.position = "absolute";
  27463. this._loadingTextDiv.style.left = "0";
  27464. this._loadingTextDiv.style.top = "50%";
  27465. this._loadingTextDiv.style.marginTop = "80px";
  27466. this._loadingTextDiv.style.width = "100%";
  27467. this._loadingTextDiv.style.height = "20px";
  27468. this._loadingTextDiv.style.fontFamily = "Arial";
  27469. this._loadingTextDiv.style.fontSize = "14px";
  27470. this._loadingTextDiv.style.color = "white";
  27471. this._loadingTextDiv.style.textAlign = "center";
  27472. this._loadingTextDiv.innerHTML = "Loading";
  27473. this._loadingDiv.appendChild(this._loadingTextDiv);
  27474. //set the predefined text
  27475. this._loadingTextDiv.innerHTML = this._loadingText;
  27476. // Loading img
  27477. var imgBack = new Image();
  27478. 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==";
  27479. imgBack.style.position = "absolute";
  27480. imgBack.style.left = "50%";
  27481. imgBack.style.top = "50%";
  27482. imgBack.style.marginLeft = "-50px";
  27483. imgBack.style.marginTop = "-50px";
  27484. imgBack.style.transition = "transform 1.0s ease";
  27485. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27486. var deg = 360;
  27487. var onTransitionEnd = function () {
  27488. deg += 360;
  27489. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27490. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27491. };
  27492. imgBack.addEventListener("transitionend", onTransitionEnd);
  27493. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27494. this._loadingDiv.appendChild(imgBack);
  27495. // front image
  27496. var imgFront = new Image();
  27497. 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=";
  27498. imgFront.style.position = "absolute";
  27499. imgFront.style.left = "50%";
  27500. imgFront.style.top = "50%";
  27501. imgFront.style.marginLeft = "-50px";
  27502. imgFront.style.marginTop = "-50px";
  27503. this._loadingDiv.appendChild(imgFront);
  27504. this._resizeLoadingUI();
  27505. window.addEventListener("resize", this._resizeLoadingUI);
  27506. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27507. document.body.appendChild(this._loadingDiv);
  27508. setTimeout(function () {
  27509. _this._loadingDiv.style.opacity = "1";
  27510. imgBack.style.transform = "rotateZ(360deg)";
  27511. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27512. }, 0);
  27513. };
  27514. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27515. var _this = this;
  27516. if (!this._loadingDiv) {
  27517. return;
  27518. }
  27519. var onTransitionEnd = function () {
  27520. if (!_this._loadingDiv) {
  27521. return;
  27522. }
  27523. document.body.removeChild(_this._loadingDiv);
  27524. window.removeEventListener("resize", _this._resizeLoadingUI);
  27525. _this._loadingDiv = null;
  27526. };
  27527. this._loadingDiv.style.opacity = "0";
  27528. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27529. };
  27530. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27531. set: function (text) {
  27532. this._loadingText = text;
  27533. if (this._loadingTextDiv) {
  27534. this._loadingTextDiv.innerHTML = this._loadingText;
  27535. }
  27536. },
  27537. enumerable: true,
  27538. configurable: true
  27539. });
  27540. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27541. get: function () {
  27542. return this._loadingDivBackgroundColor;
  27543. },
  27544. set: function (color) {
  27545. this._loadingDivBackgroundColor = color;
  27546. if (!this._loadingDiv) {
  27547. return;
  27548. }
  27549. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27550. },
  27551. enumerable: true,
  27552. configurable: true
  27553. });
  27554. return DefaultLoadingScreen;
  27555. })();
  27556. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27557. })(BABYLON || (BABYLON = {}));
  27558. var BABYLON;
  27559. (function (BABYLON) {
  27560. var SIMDVector3 = (function () {
  27561. function SIMDVector3() {
  27562. }
  27563. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27564. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27565. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27566. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27567. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27568. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27569. 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));
  27570. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27571. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27572. };
  27573. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27574. var v0 = SIMD.float32x4.splat(x);
  27575. var v1 = SIMD.float32x4.splat(y);
  27576. var v2 = SIMD.float32x4.splat(z);
  27577. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27578. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27579. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27580. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27581. 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));
  27582. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27583. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27584. };
  27585. return SIMDVector3;
  27586. })();
  27587. BABYLON.SIMDVector3 = SIMDVector3;
  27588. var SIMDMatrix = (function () {
  27589. function SIMDMatrix() {
  27590. }
  27591. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  27592. if (offset === void 0) { offset = 0; }
  27593. var tm = this.m;
  27594. var om = other.m;
  27595. var om0 = SIMD.float32x4.load(om, 0);
  27596. var om1 = SIMD.float32x4.load(om, 4);
  27597. var om2 = SIMD.float32x4.load(om, 8);
  27598. var om3 = SIMD.float32x4.load(om, 12);
  27599. var tm0 = SIMD.float32x4.load(tm, 0);
  27600. 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)))));
  27601. var tm1 = SIMD.float32x4.load(tm, 4);
  27602. 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)))));
  27603. var tm2 = SIMD.float32x4.load(tm, 8);
  27604. 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)))));
  27605. var tm3 = SIMD.float32x4.load(tm, 12);
  27606. 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)))));
  27607. };
  27608. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27609. var src = this.m;
  27610. var dest = other.m;
  27611. var row0, row1, row2, row3;
  27612. var tmp1;
  27613. var minor0, minor1, minor2, minor3;
  27614. var det;
  27615. // Load the 4 rows
  27616. var src0 = SIMD.float32x4.load(src, 0);
  27617. var src1 = SIMD.float32x4.load(src, 4);
  27618. var src2 = SIMD.float32x4.load(src, 8);
  27619. var src3 = SIMD.float32x4.load(src, 12);
  27620. // Transpose the source matrix. Sort of. Not a true transpose operation
  27621. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27622. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27623. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27624. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27625. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27626. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27627. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27628. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27629. // This is a true transposition, but it will lead to an incorrect result
  27630. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27631. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27632. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27633. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27634. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27635. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27636. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27637. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27638. // ----
  27639. tmp1 = SIMD.float32x4.mul(row2, row3);
  27640. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27641. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27642. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27643. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27644. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27645. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27646. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27647. // ----
  27648. tmp1 = SIMD.float32x4.mul(row1, row2);
  27649. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27650. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27651. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27652. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27653. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27654. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27655. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27656. // ----
  27657. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27658. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27659. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27660. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27661. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27662. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27663. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27664. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27665. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27666. // ----
  27667. tmp1 = SIMD.float32x4.mul(row0, row1);
  27668. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27669. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27670. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27671. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27672. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27673. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27674. // ----
  27675. tmp1 = SIMD.float32x4.mul(row0, row3);
  27676. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27677. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27678. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27679. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27680. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27681. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27682. // ----
  27683. tmp1 = SIMD.float32x4.mul(row0, row2);
  27684. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27685. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27686. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27687. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27688. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27689. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27690. // Compute determinant
  27691. det = SIMD.float32x4.mul(row0, minor0);
  27692. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27693. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27694. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27695. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27696. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27697. // These shuffles aren't necessary if the faulty transposition is done
  27698. // up at the top of this function.
  27699. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27700. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27701. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27702. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27703. // Compute final values by multiplying with 1/det
  27704. minor0 = SIMD.float32x4.mul(det, minor0);
  27705. minor1 = SIMD.float32x4.mul(det, minor1);
  27706. minor2 = SIMD.float32x4.mul(det, minor2);
  27707. minor3 = SIMD.float32x4.mul(det, minor3);
  27708. SIMD.float32x4.store(dest, 0, minor0);
  27709. SIMD.float32x4.store(dest, 4, minor1);
  27710. SIMD.float32x4.store(dest, 8, minor2);
  27711. SIMD.float32x4.store(dest, 12, minor3);
  27712. return this;
  27713. };
  27714. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27715. var out = result.m;
  27716. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27717. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27718. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27719. // cc.kmVec3Subtract(f, pCenter, pEye);
  27720. var f = SIMD.float32x4.sub(center, eye);
  27721. // cc.kmVec3Normalize(f, f);
  27722. var tmp = SIMD.float32x4.mul(f, f);
  27723. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27724. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27725. // cc.kmVec3Assign(up, pUp);
  27726. // cc.kmVec3Normalize(up, up);
  27727. tmp = SIMD.float32x4.mul(up, up);
  27728. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27729. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27730. // cc.kmVec3Cross(s, f, up);
  27731. 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)));
  27732. // cc.kmVec3Normalize(s, s);
  27733. tmp = SIMD.float32x4.mul(s, s);
  27734. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27735. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27736. // cc.kmVec3Cross(u, s, f);
  27737. 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)));
  27738. // cc.kmVec3Normalize(s, s);
  27739. tmp = SIMD.float32x4.mul(s, s);
  27740. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27741. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27742. var zero = SIMD.float32x4.splat(0.0);
  27743. s = SIMD.float32x4.neg(s);
  27744. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  27745. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  27746. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27747. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  27748. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  27749. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  27750. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27751. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  27752. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  27753. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  27754. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  27755. var b3 = SIMD.float32x4.neg(eye);
  27756. b3 = SIMD.float32x4.withW(b3, 1.0);
  27757. 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)))));
  27758. 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)))));
  27759. 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)))));
  27760. 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)))));
  27761. };
  27762. return SIMDMatrix;
  27763. })();
  27764. BABYLON.SIMDMatrix = SIMDMatrix;
  27765. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  27766. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  27767. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  27768. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  27769. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  27770. var SIMDHelper = (function () {
  27771. function SIMDHelper() {
  27772. }
  27773. Object.defineProperty(SIMDHelper, "IsEnabled", {
  27774. get: function () {
  27775. return SIMDHelper._isEnabled;
  27776. },
  27777. enumerable: true,
  27778. configurable: true
  27779. });
  27780. SIMDHelper.DisableSIMD = function () {
  27781. // Replace functions
  27782. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  27783. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  27784. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  27785. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  27786. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  27787. SIMDHelper._isEnabled = false;
  27788. };
  27789. SIMDHelper.EnableSIMD = function () {
  27790. if (window.SIMD === undefined) {
  27791. return;
  27792. }
  27793. // Replace functions
  27794. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  27795. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  27796. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  27797. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  27798. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  27799. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  27800. get: function () { return this._data[0]; },
  27801. set: function (value) {
  27802. if (!this._data) {
  27803. this._data = new Float32Array(3);
  27804. }
  27805. this._data[0] = value;
  27806. }
  27807. });
  27808. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  27809. get: function () { return this._data[1]; },
  27810. set: function (value) {
  27811. this._data[1] = value;
  27812. }
  27813. });
  27814. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  27815. get: function () { return this._data[2]; },
  27816. set: function (value) {
  27817. this._data[2] = value;
  27818. }
  27819. });
  27820. SIMDHelper._isEnabled = true;
  27821. };
  27822. SIMDHelper._isEnabled = false;
  27823. return SIMDHelper;
  27824. })();
  27825. BABYLON.SIMDHelper = SIMDHelper;
  27826. })(BABYLON || (BABYLON = {}));
  27827. var BABYLON;
  27828. (function (BABYLON) {
  27829. var ShaderMaterial = (function (_super) {
  27830. __extends(ShaderMaterial, _super);
  27831. function ShaderMaterial(name, scene, shaderPath, options) {
  27832. _super.call(this, name, scene);
  27833. this._textures = new Array();
  27834. this._floats = new Array();
  27835. this._floatsArrays = {};
  27836. this._colors3 = new Array();
  27837. this._colors4 = new Array();
  27838. this._vectors2 = new Array();
  27839. this._vectors3 = new Array();
  27840. this._vectors4 = new Array();
  27841. this._matrices = new Array();
  27842. this._matrices3x3 = new Array();
  27843. this._matrices2x2 = new Array();
  27844. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  27845. this._shaderPath = shaderPath;
  27846. options.needAlphaBlending = options.needAlphaBlending || false;
  27847. options.needAlphaTesting = options.needAlphaTesting || false;
  27848. options.attributes = options.attributes || ["position", "normal", "uv"];
  27849. options.uniforms = options.uniforms || ["worldViewProjection"];
  27850. options.samplers = options.samplers || [];
  27851. options.defines = options.defines || [];
  27852. this._options = options;
  27853. }
  27854. ShaderMaterial.prototype.needAlphaBlending = function () {
  27855. return this._options.needAlphaBlending;
  27856. };
  27857. ShaderMaterial.prototype.needAlphaTesting = function () {
  27858. return this._options.needAlphaTesting;
  27859. };
  27860. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  27861. if (this._options.uniforms.indexOf(uniformName) === -1) {
  27862. this._options.uniforms.push(uniformName);
  27863. }
  27864. };
  27865. ShaderMaterial.prototype.setTexture = function (name, texture) {
  27866. if (this._options.samplers.indexOf(name) === -1) {
  27867. this._options.samplers.push(name);
  27868. }
  27869. this._textures[name] = texture;
  27870. return this;
  27871. };
  27872. ShaderMaterial.prototype.setFloat = function (name, value) {
  27873. this._checkUniform(name);
  27874. this._floats[name] = value;
  27875. return this;
  27876. };
  27877. ShaderMaterial.prototype.setFloats = function (name, value) {
  27878. this._checkUniform(name);
  27879. this._floatsArrays[name] = value;
  27880. return this;
  27881. };
  27882. ShaderMaterial.prototype.setColor3 = function (name, value) {
  27883. this._checkUniform(name);
  27884. this._colors3[name] = value;
  27885. return this;
  27886. };
  27887. ShaderMaterial.prototype.setColor4 = function (name, value) {
  27888. this._checkUniform(name);
  27889. this._colors4[name] = value;
  27890. return this;
  27891. };
  27892. ShaderMaterial.prototype.setVector2 = function (name, value) {
  27893. this._checkUniform(name);
  27894. this._vectors2[name] = value;
  27895. return this;
  27896. };
  27897. ShaderMaterial.prototype.setVector3 = function (name, value) {
  27898. this._checkUniform(name);
  27899. this._vectors3[name] = value;
  27900. return this;
  27901. };
  27902. ShaderMaterial.prototype.setVector4 = function (name, value) {
  27903. this._checkUniform(name);
  27904. this._vectors4[name] = value;
  27905. return this;
  27906. };
  27907. ShaderMaterial.prototype.setMatrix = function (name, value) {
  27908. this._checkUniform(name);
  27909. this._matrices[name] = value;
  27910. return this;
  27911. };
  27912. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  27913. this._checkUniform(name);
  27914. this._matrices3x3[name] = value;
  27915. return this;
  27916. };
  27917. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  27918. this._checkUniform(name);
  27919. this._matrices2x2[name] = value;
  27920. return this;
  27921. };
  27922. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  27923. var scene = this.getScene();
  27924. var engine = scene.getEngine();
  27925. if (!this.checkReadyOnEveryCall) {
  27926. if (this._renderId === scene.getRenderId()) {
  27927. return true;
  27928. }
  27929. }
  27930. // Instances
  27931. var defines = [];
  27932. var fallbacks = new BABYLON.EffectFallbacks();
  27933. if (useInstances) {
  27934. defines.push("#define INSTANCES");
  27935. }
  27936. for (var index = 0; index < this._options.defines.length; index++) {
  27937. defines.push(this._options.defines[index]);
  27938. }
  27939. // Bones
  27940. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27941. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  27942. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27943. fallbacks.addCPUSkinningFallback(0, mesh);
  27944. }
  27945. // Alpha test
  27946. if (engine.getAlphaTesting()) {
  27947. defines.push("#define ALPHATEST");
  27948. }
  27949. var previousEffect = this._effect;
  27950. var join = defines.join("\n");
  27951. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  27952. if (!this._effect.isReady()) {
  27953. return false;
  27954. }
  27955. if (previousEffect !== this._effect) {
  27956. scene.resetCachedMaterial();
  27957. }
  27958. this._renderId = scene.getRenderId();
  27959. return true;
  27960. };
  27961. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27962. var scene = this.getScene();
  27963. if (this._options.uniforms.indexOf("world") !== -1) {
  27964. this._effect.setMatrix("world", world);
  27965. }
  27966. if (this._options.uniforms.indexOf("worldView") !== -1) {
  27967. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  27968. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  27969. }
  27970. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  27971. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  27972. }
  27973. };
  27974. ShaderMaterial.prototype.bind = function (world, mesh) {
  27975. // Std values
  27976. this.bindOnlyWorldMatrix(world);
  27977. if (this.getScene().getCachedMaterial() !== this) {
  27978. if (this._options.uniforms.indexOf("view") !== -1) {
  27979. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  27980. }
  27981. if (this._options.uniforms.indexOf("projection") !== -1) {
  27982. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  27983. }
  27984. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  27985. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27986. }
  27987. // Bones
  27988. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27989. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27990. }
  27991. // Texture
  27992. for (var name in this._textures) {
  27993. this._effect.setTexture(name, this._textures[name]);
  27994. }
  27995. // Float
  27996. for (name in this._floats) {
  27997. this._effect.setFloat(name, this._floats[name]);
  27998. }
  27999. // Float s
  28000. for (name in this._floatsArrays) {
  28001. this._effect.setArray(name, this._floatsArrays[name]);
  28002. }
  28003. // Color3
  28004. for (name in this._colors3) {
  28005. this._effect.setColor3(name, this._colors3[name]);
  28006. }
  28007. // Color4
  28008. for (name in this._colors4) {
  28009. var color = this._colors4[name];
  28010. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28011. }
  28012. // Vector2
  28013. for (name in this._vectors2) {
  28014. this._effect.setVector2(name, this._vectors2[name]);
  28015. }
  28016. // Vector3
  28017. for (name in this._vectors3) {
  28018. this._effect.setVector3(name, this._vectors3[name]);
  28019. }
  28020. // Vector4
  28021. for (name in this._vectors4) {
  28022. this._effect.setVector4(name, this._vectors4[name]);
  28023. }
  28024. // Matrix
  28025. for (name in this._matrices) {
  28026. this._effect.setMatrix(name, this._matrices[name]);
  28027. }
  28028. // Matrix 3x3
  28029. for (name in this._matrices3x3) {
  28030. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28031. }
  28032. // Matrix 2x2
  28033. for (name in this._matrices2x2) {
  28034. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28035. }
  28036. }
  28037. _super.prototype.bind.call(this, world, mesh);
  28038. };
  28039. ShaderMaterial.prototype.clone = function (name) {
  28040. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28041. return newShaderMaterial;
  28042. };
  28043. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28044. for (var name in this._textures) {
  28045. this._textures[name].dispose();
  28046. }
  28047. this._textures = [];
  28048. _super.prototype.dispose.call(this, forceDisposeEffect);
  28049. };
  28050. return ShaderMaterial;
  28051. })(BABYLON.Material);
  28052. BABYLON.ShaderMaterial = ShaderMaterial;
  28053. })(BABYLON || (BABYLON = {}));
  28054. var BABYLON;
  28055. (function (BABYLON) {
  28056. var Internals;
  28057. (function (Internals) {
  28058. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  28059. // All values and structures referenced from:
  28060. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  28061. var DDS_MAGIC = 0x20534444;
  28062. 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;
  28063. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  28064. 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;
  28065. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  28066. function FourCCToInt32(value) {
  28067. return value.charCodeAt(0) +
  28068. (value.charCodeAt(1) << 8) +
  28069. (value.charCodeAt(2) << 16) +
  28070. (value.charCodeAt(3) << 24);
  28071. }
  28072. function Int32ToFourCC(value) {
  28073. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  28074. }
  28075. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  28076. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  28077. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  28078. var headerLengthInt = 31; // The header length in 32 bit ints
  28079. // Offsets into the header array
  28080. var off_magic = 0;
  28081. var off_size = 1;
  28082. var off_flags = 2;
  28083. var off_height = 3;
  28084. var off_width = 4;
  28085. var off_mipmapCount = 7;
  28086. var off_pfFlags = 20;
  28087. var off_pfFourCC = 21;
  28088. var off_RGBbpp = 22;
  28089. var off_RMask = 23;
  28090. var off_GMask = 24;
  28091. var off_BMask = 25;
  28092. var off_AMask = 26;
  28093. var off_caps1 = 27;
  28094. var off_caps2 = 28;
  28095. ;
  28096. var DDSTools = (function () {
  28097. function DDSTools() {
  28098. }
  28099. DDSTools.GetDDSInfo = function (arrayBuffer) {
  28100. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  28101. var mipmapCount = 1;
  28102. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  28103. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28104. }
  28105. return {
  28106. width: header[off_width],
  28107. height: header[off_height],
  28108. mipmapCount: mipmapCount,
  28109. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  28110. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  28111. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  28112. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  28113. };
  28114. };
  28115. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28116. var byteArray = new Uint8Array(dataLength);
  28117. var srcData = new Uint8Array(arrayBuffer);
  28118. var index = 0;
  28119. for (var y = height - 1; y >= 0; y--) {
  28120. for (var x = 0; x < width; x++) {
  28121. var srcPos = dataOffset + (x + y * width) * 4;
  28122. byteArray[index + 2] = srcData[srcPos];
  28123. byteArray[index + 1] = srcData[srcPos + 1];
  28124. byteArray[index] = srcData[srcPos + 2];
  28125. byteArray[index + 3] = srcData[srcPos + 3];
  28126. index += 4;
  28127. }
  28128. }
  28129. return byteArray;
  28130. };
  28131. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28132. var byteArray = new Uint8Array(dataLength);
  28133. var srcData = new Uint8Array(arrayBuffer);
  28134. var index = 0;
  28135. for (var y = height - 1; y >= 0; y--) {
  28136. for (var x = 0; x < width; x++) {
  28137. var srcPos = dataOffset + (x + y * width) * 3;
  28138. byteArray[index + 2] = srcData[srcPos];
  28139. byteArray[index + 1] = srcData[srcPos + 1];
  28140. byteArray[index] = srcData[srcPos + 2];
  28141. index += 3;
  28142. }
  28143. }
  28144. return byteArray;
  28145. };
  28146. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28147. var byteArray = new Uint8Array(dataLength);
  28148. var srcData = new Uint8Array(arrayBuffer);
  28149. var index = 0;
  28150. for (var y = height - 1; y >= 0; y--) {
  28151. for (var x = 0; x < width; x++) {
  28152. var srcPos = dataOffset + (x + y * width);
  28153. byteArray[index] = srcData[srcPos];
  28154. index++;
  28155. }
  28156. }
  28157. return byteArray;
  28158. };
  28159. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  28160. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  28161. if (header[off_magic] != DDS_MAGIC) {
  28162. BABYLON.Tools.Error("Invalid magic number in DDS header");
  28163. return;
  28164. }
  28165. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  28166. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  28167. return;
  28168. }
  28169. if (info.isFourCC) {
  28170. fourCC = header[off_pfFourCC];
  28171. switch (fourCC) {
  28172. case FOURCC_DXT1:
  28173. blockBytes = 8;
  28174. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  28175. break;
  28176. case FOURCC_DXT3:
  28177. blockBytes = 16;
  28178. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  28179. break;
  28180. case FOURCC_DXT5:
  28181. blockBytes = 16;
  28182. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  28183. break;
  28184. default:
  28185. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  28186. return;
  28187. }
  28188. }
  28189. mipmapCount = 1;
  28190. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  28191. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28192. }
  28193. var bpp = header[off_RGBbpp];
  28194. for (var face = 0; face < faces; face++) {
  28195. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  28196. width = header[off_width];
  28197. height = header[off_height];
  28198. dataOffset = header[off_size] + 4;
  28199. for (i = 0; i < mipmapCount; ++i) {
  28200. if (info.isRGB) {
  28201. if (bpp === 24) {
  28202. dataLength = width * height * 3;
  28203. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28204. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  28205. }
  28206. else {
  28207. dataLength = width * height * 4;
  28208. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28209. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  28210. }
  28211. }
  28212. else if (info.isLuminance) {
  28213. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  28214. var unpaddedRowSize = width;
  28215. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  28216. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  28217. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28218. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  28219. }
  28220. else {
  28221. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  28222. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  28223. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  28224. }
  28225. dataOffset += dataLength;
  28226. width *= 0.5;
  28227. height *= 0.5;
  28228. width = Math.max(1.0, width);
  28229. height = Math.max(1.0, height);
  28230. }
  28231. }
  28232. };
  28233. return DDSTools;
  28234. })();
  28235. Internals.DDSTools = DDSTools;
  28236. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28237. })(BABYLON || (BABYLON = {}));
  28238. var BABYLON;
  28239. (function (BABYLON) {
  28240. var CannonJSPlugin = (function () {
  28241. function CannonJSPlugin() {
  28242. this._registeredMeshes = [];
  28243. this._physicsMaterials = [];
  28244. this.updateBodyPosition = function (mesh) {
  28245. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28246. var registeredMesh = this._registeredMeshes[index];
  28247. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28248. var body = registeredMesh.body;
  28249. var center = mesh.getBoundingInfo().boundingBox.center;
  28250. body.position.set(center.x, center.y, center.z);
  28251. body.quaternion.copy(mesh.rotationQuaternion);
  28252. if (registeredMesh.deltaRotation) {
  28253. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28254. body.quaternion = body.quaternion.mult(tmpQ);
  28255. }
  28256. if (registeredMesh.heightmap) {
  28257. //calculate the correct body position:
  28258. var rotationQuaternion = mesh.rotationQuaternion;
  28259. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28260. mesh.computeWorldMatrix(true);
  28261. //get original center with no rotation
  28262. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28263. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28264. //rotation is back
  28265. mesh.rotationQuaternion = rotationQuaternion;
  28266. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28267. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28268. mesh.setPivotMatrix(p);
  28269. mesh.computeWorldMatrix(true);
  28270. //calculate the translation
  28271. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28272. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28273. //add it inverted to the delta
  28274. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28275. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28276. mesh.setPivotMatrix(oldPivot);
  28277. mesh.computeWorldMatrix(true);
  28278. }
  28279. return;
  28280. }
  28281. }
  28282. };
  28283. }
  28284. CannonJSPlugin.prototype.initialize = function (iterations) {
  28285. if (iterations === void 0) { iterations = 10; }
  28286. this._world = new CANNON.World();
  28287. this._world.broadphase = new CANNON.NaiveBroadphase();
  28288. this._world.solver.iterations = iterations;
  28289. };
  28290. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28291. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28292. };
  28293. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28294. var _this = this;
  28295. this._world.step(delta);
  28296. this._registeredMeshes.forEach(function (registeredMesh) {
  28297. // Body position
  28298. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28299. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28300. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28301. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28302. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28303. if (registeredMesh.deltaRotation) {
  28304. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28305. }
  28306. //is the physics collision callback is set?
  28307. if (registeredMesh.mesh.onPhysicsCollide) {
  28308. if (!registeredMesh.collisionFunction) {
  28309. registeredMesh.collisionFunction = function (e) {
  28310. //find the mesh that collided with the registered mesh
  28311. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28312. if (_this._registeredMeshes[idx].body == e.body) {
  28313. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh);
  28314. }
  28315. }
  28316. };
  28317. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  28318. }
  28319. }
  28320. else {
  28321. //unregister, in case the function was removed for some reason
  28322. if (registeredMesh.collisionFunction) {
  28323. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  28324. }
  28325. }
  28326. });
  28327. };
  28328. CannonJSPlugin.prototype.setGravity = function (gravity) {
  28329. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  28330. };
  28331. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28332. this.unregisterMesh(mesh);
  28333. if (!mesh.rotationQuaternion) {
  28334. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28335. }
  28336. mesh.computeWorldMatrix(true);
  28337. var shape = this._createShape(mesh, impostor);
  28338. return this._createRigidBodyFromShape(shape, mesh, options);
  28339. };
  28340. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  28341. //get the correct bounding box
  28342. var oldQuaternion = mesh.rotationQuaternion;
  28343. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28344. mesh.computeWorldMatrix(true);
  28345. var returnValue;
  28346. switch (impostor) {
  28347. case BABYLON.PhysicsEngine.SphereImpostor:
  28348. var bbox = mesh.getBoundingInfo().boundingBox;
  28349. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28350. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28351. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28352. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28353. break;
  28354. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28355. case BABYLON.PhysicsEngine.CylinderImpostor:
  28356. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28357. case BABYLON.PhysicsEngine.BoxImpostor:
  28358. bbox = mesh.getBoundingInfo().boundingBox;
  28359. var min = bbox.minimumWorld;
  28360. var max = bbox.maximumWorld;
  28361. var box = max.subtract(min).scale(0.5);
  28362. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28363. break;
  28364. case BABYLON.PhysicsEngine.PlaneImpostor:
  28365. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28366. returnValue = new CANNON.Plane();
  28367. break;
  28368. case BABYLON.PhysicsEngine.MeshImpostor:
  28369. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28370. var rawFaces = mesh.getIndices();
  28371. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28372. break;
  28373. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28374. returnValue = this._createHeightmap(mesh);
  28375. break;
  28376. }
  28377. mesh.rotationQuaternion = oldQuaternion;
  28378. return returnValue;
  28379. };
  28380. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28381. var verts = [], faces = [];
  28382. mesh.computeWorldMatrix(true);
  28383. //reuse this variable
  28384. var transformed = BABYLON.Vector3.Zero();
  28385. // Get vertices
  28386. for (var i = 0; i < rawVerts.length; i += 3) {
  28387. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28388. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28389. }
  28390. // Get faces
  28391. for (var j = 0; j < rawFaces.length; j += 3) {
  28392. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28393. }
  28394. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28395. return shape;
  28396. };
  28397. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28398. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28399. var matrix = [];
  28400. //For now pointDepth will not be used and will be automatically calculated.
  28401. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28402. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28403. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28404. var elementSize = dim * 2 / arraySize;
  28405. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28406. for (var i = 0; i < pos.length; i = i + 3) {
  28407. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28408. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28409. var y = pos[i + 1] + minY;
  28410. if (!matrix[x]) {
  28411. matrix[x] = [];
  28412. }
  28413. if (!matrix[x][z]) {
  28414. matrix[x][z] = y;
  28415. }
  28416. matrix[x][z] = Math.max(y, matrix[x][z]);
  28417. }
  28418. for (var x = 0; x <= arraySize; ++x) {
  28419. if (!matrix[x]) {
  28420. var loc = 1;
  28421. while (!matrix[(x + loc) % arraySize]) {
  28422. loc++;
  28423. }
  28424. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28425. }
  28426. for (var z = 0; z <= arraySize; ++z) {
  28427. if (!matrix[x][z]) {
  28428. var loc = 1;
  28429. var newValue;
  28430. while (newValue === undefined) {
  28431. newValue = matrix[x][(z + loc++) % arraySize];
  28432. }
  28433. matrix[x][z] = newValue;
  28434. }
  28435. }
  28436. }
  28437. var shape = new CANNON.Heightfield(matrix, {
  28438. elementSize: elementSize
  28439. });
  28440. //For future reference, needed for body transformation
  28441. shape.minY = minY;
  28442. return shape;
  28443. };
  28444. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28445. var index;
  28446. var mat;
  28447. for (index = 0; index < this._physicsMaterials.length; index++) {
  28448. mat = this._physicsMaterials[index];
  28449. if (mat.friction === friction && mat.restitution === restitution) {
  28450. return mat;
  28451. }
  28452. }
  28453. var currentMat = new CANNON.Material("mat");
  28454. this._physicsMaterials.push(currentMat);
  28455. for (index = 0; index < this._physicsMaterials.length; index++) {
  28456. mat = this._physicsMaterials[index];
  28457. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28458. this._world.addContactMaterial(contactMaterial);
  28459. }
  28460. return currentMat;
  28461. };
  28462. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28463. if (!mesh.rotationQuaternion) {
  28464. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28465. }
  28466. // The delta between the mesh position and the mesh bounding box center
  28467. var bbox = mesh.getBoundingInfo().boundingBox;
  28468. var deltaPosition = mesh.position.subtract(bbox.center);
  28469. var deltaRotation;
  28470. var material = this._addMaterial(options.friction, options.restitution);
  28471. var body = new CANNON.Body({
  28472. mass: options.mass,
  28473. material: material,
  28474. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28475. });
  28476. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28477. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  28478. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28479. //-90 DEG in X, precalculated
  28480. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28481. body.quaternion = body.quaternion.mult(tmpQ);
  28482. //Invert! (Precalculated, 90 deg in X)
  28483. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  28484. }
  28485. //If it is a heightfield, if should be centered.
  28486. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28487. //calculate the correct body position:
  28488. var rotationQuaternion = mesh.rotationQuaternion;
  28489. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28490. mesh.computeWorldMatrix(true);
  28491. //get original center with no rotation
  28492. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28493. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28494. //rotation is back
  28495. mesh.rotationQuaternion = rotationQuaternion;
  28496. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28497. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28498. mesh.setPivotMatrix(p);
  28499. mesh.computeWorldMatrix(true);
  28500. //calculate the translation
  28501. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28502. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28503. //add it inverted to the delta
  28504. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28505. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28506. mesh.setPivotMatrix(oldPivot);
  28507. mesh.computeWorldMatrix(true);
  28508. }
  28509. //add the shape
  28510. body.addShape(shape);
  28511. this._world.add(body);
  28512. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  28513. return body;
  28514. };
  28515. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28516. var initialMesh = parts[0].mesh;
  28517. this.unregisterMesh(initialMesh);
  28518. initialMesh.computeWorldMatrix(true);
  28519. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28520. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  28521. for (var index = 1; index < parts.length; index++) {
  28522. var mesh = parts[index].mesh;
  28523. mesh.computeWorldMatrix(true);
  28524. var shape = this._createShape(mesh, parts[index].impostor);
  28525. var localPosition = mesh.position;
  28526. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28527. }
  28528. return body;
  28529. };
  28530. CannonJSPlugin.prototype._unbindBody = function (body) {
  28531. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28532. var registeredMesh = this._registeredMeshes[index];
  28533. if (registeredMesh.body === body) {
  28534. this._world.remove(registeredMesh.body);
  28535. registeredMesh.body = null;
  28536. registeredMesh.delta = null;
  28537. registeredMesh.deltaRotation = null;
  28538. }
  28539. }
  28540. };
  28541. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28542. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28543. var registeredMesh = this._registeredMeshes[index];
  28544. if (registeredMesh.mesh === mesh) {
  28545. // Remove body
  28546. if (registeredMesh.body) {
  28547. this._unbindBody(registeredMesh.body);
  28548. }
  28549. this._registeredMeshes.splice(index, 1);
  28550. return;
  28551. }
  28552. }
  28553. };
  28554. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28555. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28556. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28557. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28558. var registeredMesh = this._registeredMeshes[index];
  28559. if (registeredMesh.mesh === mesh) {
  28560. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28561. return;
  28562. }
  28563. }
  28564. };
  28565. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28566. var body1 = null, body2 = null;
  28567. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28568. var registeredMesh = this._registeredMeshes[index];
  28569. if (registeredMesh.mesh === mesh1) {
  28570. body1 = registeredMesh.body;
  28571. }
  28572. else if (registeredMesh.mesh === mesh2) {
  28573. body2 = registeredMesh.body;
  28574. }
  28575. }
  28576. if (!body1 || !body2) {
  28577. return false;
  28578. }
  28579. 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));
  28580. this._world.addConstraint(constraint);
  28581. return true;
  28582. };
  28583. CannonJSPlugin.prototype.dispose = function () {
  28584. while (this._registeredMeshes.length) {
  28585. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28586. }
  28587. };
  28588. CannonJSPlugin.prototype.isSupported = function () {
  28589. return window.CANNON !== undefined;
  28590. };
  28591. CannonJSPlugin.prototype.getWorldObject = function () {
  28592. return this._world;
  28593. };
  28594. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28595. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28596. var registeredMesh = this._registeredMeshes[index];
  28597. if (registeredMesh.mesh === mesh) {
  28598. return registeredMesh.body;
  28599. }
  28600. }
  28601. return null;
  28602. };
  28603. return CannonJSPlugin;
  28604. })();
  28605. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28606. })(BABYLON || (BABYLON = {}));
  28607. var BABYLON;
  28608. (function (BABYLON) {
  28609. var OimoJSPlugin = (function () {
  28610. function OimoJSPlugin() {
  28611. this._registeredMeshes = [];
  28612. /**
  28613. * Update the body position according to the mesh position
  28614. * @param mesh
  28615. */
  28616. this.updateBodyPosition = function (mesh) {
  28617. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28618. var registeredMesh = this._registeredMeshes[index];
  28619. var body = registeredMesh.body.body;
  28620. var updated = false;
  28621. var newPosition;
  28622. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28623. mesh.computeWorldMatrix(true);
  28624. newPosition = mesh.getBoundingInfo().boundingBox.center;
  28625. updated = true;
  28626. }
  28627. else if (registeredMesh.mesh.parent === mesh) {
  28628. mesh.computeWorldMatrix(true);
  28629. registeredMesh.mesh.computeWorldMatrix(true);
  28630. newPosition = registeredMesh.mesh.getAbsolutePosition();
  28631. updated = true;
  28632. }
  28633. if (updated) {
  28634. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  28635. body.setQuaternion(mesh.rotationQuaternion);
  28636. body.sleeping = false;
  28637. //force Oimo to update the body's position
  28638. body.updatePosition(1);
  28639. }
  28640. }
  28641. };
  28642. }
  28643. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28644. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28645. };
  28646. OimoJSPlugin.prototype.initialize = function (iterations) {
  28647. this._world = new OIMO.World(null, null, iterations);
  28648. this._world.clear();
  28649. };
  28650. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28651. this._world.gravity = gravity;
  28652. };
  28653. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28654. this.unregisterMesh(mesh);
  28655. if (!mesh.rotationQuaternion) {
  28656. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28657. }
  28658. mesh.computeWorldMatrix(true);
  28659. var bbox = mesh.getBoundingInfo().boundingBox;
  28660. // The delta between the mesh position and the mesh bounding box center
  28661. var deltaPosition = mesh.position.subtract(bbox.center);
  28662. //calculate rotation to fit Oimo's needs (Euler...)
  28663. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28664. //get the correct bounding box
  28665. var oldQuaternion = mesh.rotationQuaternion;
  28666. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28667. mesh.computeWorldMatrix(true);
  28668. var bodyConfig = {
  28669. name: mesh.uniqueId,
  28670. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28671. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  28672. move: options.mass != 0,
  28673. config: [options.mass, options.friction, options.restitution],
  28674. world: this._world
  28675. };
  28676. // register mesh
  28677. switch (impostor) {
  28678. case BABYLON.PhysicsEngine.SphereImpostor:
  28679. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28680. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28681. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28682. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28683. bodyConfig.type = 'sphere';
  28684. bodyConfig.size = [size];
  28685. break;
  28686. case BABYLON.PhysicsEngine.PlaneImpostor:
  28687. //Oimo "fakes" a cylinder as a box, so why don't we!
  28688. case BABYLON.PhysicsEngine.CylinderImpostor:
  28689. case BABYLON.PhysicsEngine.BoxImpostor:
  28690. var min = bbox.minimumWorld;
  28691. var max = bbox.maximumWorld;
  28692. var box = max.subtract(min);
  28693. var sizeX = this._checkWithEpsilon(box.x);
  28694. var sizeY = this._checkWithEpsilon(box.y);
  28695. var sizeZ = this._checkWithEpsilon(box.z);
  28696. bodyConfig.type = 'box';
  28697. bodyConfig.size = [sizeX, sizeY, sizeZ];
  28698. break;
  28699. }
  28700. var body = new OIMO.Body(bodyConfig);
  28701. //We have to access the rigid body's properties to set the quaternion.
  28702. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28703. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  28704. //TEST
  28705. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  28706. //update the internal rotation matrix
  28707. //body.body.syncShapes();
  28708. this._registeredMeshes.push({
  28709. mesh: mesh,
  28710. body: body,
  28711. delta: deltaPosition
  28712. });
  28713. //for the sake of consistency.
  28714. mesh.rotationQuaternion = oldQuaternion;
  28715. return body;
  28716. };
  28717. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28718. var types = [], sizes = [], positions = [], rotations = [];
  28719. var initialMesh = parts[0].mesh;
  28720. for (var index = 0; index < parts.length; index++) {
  28721. var part = parts[index];
  28722. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  28723. types.push(bodyParameters.type);
  28724. sizes.push.apply(sizes, bodyParameters.size);
  28725. positions.push.apply(positions, bodyParameters.pos);
  28726. rotations.push.apply(rotations, bodyParameters.rot);
  28727. }
  28728. var body = new OIMO.Body({
  28729. name: initialMesh.uniqueId,
  28730. type: types,
  28731. size: sizes,
  28732. pos: positions,
  28733. rot: rotations,
  28734. move: options.mass != 0,
  28735. config: [options.mass, options.friction, options.restitution],
  28736. world: this._world
  28737. });
  28738. //Reset the body's rotation to be of the initial mesh's.
  28739. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  28740. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  28741. this._registeredMeshes.push({
  28742. mesh: initialMesh,
  28743. body: body
  28744. });
  28745. return body;
  28746. };
  28747. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  28748. var mesh = part.mesh;
  28749. if (!mesh.rotationQuaternion) {
  28750. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28751. }
  28752. // We need the bounding box/sphere info to compute the physics body
  28753. mesh.computeWorldMatrix(true);
  28754. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28755. var bodyParameters = {
  28756. name: mesh.uniqueId,
  28757. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  28758. //A bug in Oimo (Body class) prevents us from using rot directly.
  28759. rot: [0, 0, 0],
  28760. //For future reference, if the bug will ever be fixed.
  28761. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  28762. };
  28763. var oldQuaternion = mesh.rotationQuaternion;
  28764. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28765. mesh.computeWorldMatrix(true);
  28766. switch (part.impostor) {
  28767. case BABYLON.PhysicsEngine.SphereImpostor:
  28768. var bbox = mesh.getBoundingInfo().boundingBox;
  28769. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28770. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28771. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28772. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28773. bodyParameters.type = 'sphere';
  28774. bodyParameters.size = [size, size, size];
  28775. break;
  28776. case BABYLON.PhysicsEngine.PlaneImpostor:
  28777. case BABYLON.PhysicsEngine.CylinderImpostor:
  28778. case BABYLON.PhysicsEngine.BoxImpostor:
  28779. bbox = mesh.getBoundingInfo().boundingBox;
  28780. var min = bbox.minimumWorld;
  28781. var max = bbox.maximumWorld;
  28782. var box = max.subtract(min);
  28783. var sizeX = this._checkWithEpsilon(box.x);
  28784. var sizeY = this._checkWithEpsilon(box.y);
  28785. var sizeZ = this._checkWithEpsilon(box.z);
  28786. bodyParameters.type = 'box';
  28787. bodyParameters.size = [sizeX, sizeY, sizeZ];
  28788. break;
  28789. }
  28790. mesh.rotationQuaternion = oldQuaternion;
  28791. return bodyParameters;
  28792. };
  28793. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  28794. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28795. var registeredMesh = this._registeredMeshes[index];
  28796. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28797. if (registeredMesh.body) {
  28798. this._world.removeRigidBody(registeredMesh.body.body);
  28799. this._unbindBody(registeredMesh.body);
  28800. }
  28801. this._registeredMeshes.splice(index, 1);
  28802. return;
  28803. }
  28804. }
  28805. };
  28806. OimoJSPlugin.prototype._unbindBody = function (body) {
  28807. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28808. var registeredMesh = this._registeredMeshes[index];
  28809. if (registeredMesh.body === body) {
  28810. registeredMesh.body = null;
  28811. }
  28812. }
  28813. };
  28814. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28815. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28816. var registeredMesh = this._registeredMeshes[index];
  28817. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28818. // Get object mass to have a behaviour similar to cannon.js
  28819. var mass = registeredMesh.body.body.massInfo.mass;
  28820. // The force is scaled with the mass of object
  28821. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  28822. return;
  28823. }
  28824. }
  28825. };
  28826. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  28827. var body1 = null, body2 = null;
  28828. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28829. var registeredMesh = this._registeredMeshes[index];
  28830. if (registeredMesh.mesh === mesh1) {
  28831. body1 = registeredMesh.body.body;
  28832. }
  28833. else if (registeredMesh.mesh === mesh2) {
  28834. body2 = registeredMesh.body.body;
  28835. }
  28836. }
  28837. if (!body1 || !body2) {
  28838. return false;
  28839. }
  28840. if (!options) {
  28841. options = {};
  28842. }
  28843. new OIMO.Link({
  28844. type: options.type,
  28845. body1: body1,
  28846. body2: body2,
  28847. min: options.min,
  28848. max: options.max,
  28849. axe1: options.axe1,
  28850. axe2: options.axe2,
  28851. pos1: [pivot1.x, pivot1.y, pivot1.z],
  28852. pos2: [pivot2.x, pivot2.y, pivot2.z],
  28853. collision: options.collision,
  28854. spring: options.spring,
  28855. world: this._world
  28856. });
  28857. return true;
  28858. };
  28859. OimoJSPlugin.prototype.dispose = function () {
  28860. this._world.clear();
  28861. while (this._registeredMeshes.length) {
  28862. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28863. }
  28864. };
  28865. OimoJSPlugin.prototype.isSupported = function () {
  28866. return OIMO !== undefined;
  28867. };
  28868. OimoJSPlugin.prototype.getWorldObject = function () {
  28869. return this._world;
  28870. };
  28871. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28872. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28873. var registeredMesh = this._registeredMeshes[index];
  28874. if (registeredMesh.mesh === mesh) {
  28875. return registeredMesh.body;
  28876. }
  28877. }
  28878. return null;
  28879. };
  28880. OimoJSPlugin.prototype._getLastShape = function (body) {
  28881. var lastShape = body.shapes;
  28882. while (lastShape.next) {
  28883. lastShape = lastShape.next;
  28884. }
  28885. return lastShape;
  28886. };
  28887. OimoJSPlugin.prototype.runOneStep = function (time) {
  28888. this._world.step();
  28889. // Update the position of all registered meshes
  28890. var i = this._registeredMeshes.length;
  28891. var m;
  28892. while (i--) {
  28893. var body = this._registeredMeshes[i].body.body;
  28894. var mesh = this._registeredMeshes[i].mesh;
  28895. if (!this._registeredMeshes[i].delta) {
  28896. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  28897. }
  28898. if (!body.sleeping) {
  28899. //TODO check that
  28900. if (body.shapes.next) {
  28901. var parentShape = this._getLastShape(body);
  28902. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  28903. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  28904. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  28905. }
  28906. else {
  28907. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  28908. }
  28909. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  28910. mesh.computeWorldMatrix();
  28911. }
  28912. //check if the collide callback is set.
  28913. if (mesh.onPhysicsCollide) {
  28914. var meshUniqueName = mesh.uniqueId;
  28915. var contact = this._world.contacts;
  28916. while (contact !== null) {
  28917. //is this body colliding with any other?
  28918. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  28919. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  28920. //get the mesh and execute the callback
  28921. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  28922. if (otherMesh)
  28923. mesh.onPhysicsCollide(otherMesh);
  28924. }
  28925. contact = contact.next;
  28926. }
  28927. }
  28928. }
  28929. };
  28930. return OimoJSPlugin;
  28931. })();
  28932. BABYLON.OimoJSPlugin = OimoJSPlugin;
  28933. })(BABYLON || (BABYLON = {}));
  28934. var BABYLON;
  28935. (function (BABYLON) {
  28936. var DisplayPassPostProcess = (function (_super) {
  28937. __extends(DisplayPassPostProcess, _super);
  28938. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28939. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28940. }
  28941. return DisplayPassPostProcess;
  28942. })(BABYLON.PostProcess);
  28943. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28944. })(BABYLON || (BABYLON = {}));
  28945. var BABYLON;
  28946. (function (BABYLON) {
  28947. var SimplificationSettings = (function () {
  28948. function SimplificationSettings(quality, distance, optimizeMesh) {
  28949. this.quality = quality;
  28950. this.distance = distance;
  28951. this.optimizeMesh = optimizeMesh;
  28952. }
  28953. return SimplificationSettings;
  28954. })();
  28955. BABYLON.SimplificationSettings = SimplificationSettings;
  28956. var SimplificationQueue = (function () {
  28957. function SimplificationQueue() {
  28958. this.running = false;
  28959. this._simplificationArray = [];
  28960. }
  28961. SimplificationQueue.prototype.addTask = function (task) {
  28962. this._simplificationArray.push(task);
  28963. };
  28964. SimplificationQueue.prototype.executeNext = function () {
  28965. var task = this._simplificationArray.pop();
  28966. if (task) {
  28967. this.running = true;
  28968. this.runSimplification(task);
  28969. }
  28970. else {
  28971. this.running = false;
  28972. }
  28973. };
  28974. SimplificationQueue.prototype.runSimplification = function (task) {
  28975. var _this = this;
  28976. if (task.parallelProcessing) {
  28977. //parallel simplifier
  28978. task.settings.forEach(function (setting) {
  28979. var simplifier = _this.getSimplifier(task);
  28980. simplifier.simplify(setting, function (newMesh) {
  28981. task.mesh.addLODLevel(setting.distance, newMesh);
  28982. newMesh.isVisible = true;
  28983. //check if it is the last
  28984. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28985. //all done, run the success callback.
  28986. task.successCallback();
  28987. }
  28988. _this.executeNext();
  28989. });
  28990. });
  28991. }
  28992. else {
  28993. //single simplifier.
  28994. var simplifier = this.getSimplifier(task);
  28995. var runDecimation = function (setting, callback) {
  28996. simplifier.simplify(setting, function (newMesh) {
  28997. task.mesh.addLODLevel(setting.distance, newMesh);
  28998. newMesh.isVisible = true;
  28999. //run the next quality level
  29000. callback();
  29001. });
  29002. };
  29003. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29004. runDecimation(task.settings[loop.index], function () {
  29005. loop.executeNext();
  29006. });
  29007. }, function () {
  29008. //execution ended, run the success callback.
  29009. if (task.successCallback) {
  29010. task.successCallback();
  29011. }
  29012. _this.executeNext();
  29013. });
  29014. }
  29015. };
  29016. SimplificationQueue.prototype.getSimplifier = function (task) {
  29017. switch (task.simplificationType) {
  29018. case SimplificationType.QUADRATIC:
  29019. default:
  29020. return new QuadraticErrorSimplification(task.mesh);
  29021. }
  29022. };
  29023. return SimplificationQueue;
  29024. })();
  29025. BABYLON.SimplificationQueue = SimplificationQueue;
  29026. /**
  29027. * The implemented types of simplification.
  29028. * At the moment only Quadratic Error Decimation is implemented.
  29029. */
  29030. (function (SimplificationType) {
  29031. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29032. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29033. var SimplificationType = BABYLON.SimplificationType;
  29034. var DecimationTriangle = (function () {
  29035. function DecimationTriangle(vertices) {
  29036. this.vertices = vertices;
  29037. this.error = new Array(4);
  29038. this.deleted = false;
  29039. this.isDirty = false;
  29040. this.deletePending = false;
  29041. this.borderFactor = 0;
  29042. }
  29043. return DecimationTriangle;
  29044. })();
  29045. BABYLON.DecimationTriangle = DecimationTriangle;
  29046. var DecimationVertex = (function () {
  29047. function DecimationVertex(position, id) {
  29048. this.position = position;
  29049. this.id = id;
  29050. this.isBorder = true;
  29051. this.q = new QuadraticMatrix();
  29052. this.triangleCount = 0;
  29053. this.triangleStart = 0;
  29054. this.originalOffsets = [];
  29055. }
  29056. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29057. this.position.copyFrom(newPosition);
  29058. };
  29059. return DecimationVertex;
  29060. })();
  29061. BABYLON.DecimationVertex = DecimationVertex;
  29062. var QuadraticMatrix = (function () {
  29063. function QuadraticMatrix(data) {
  29064. this.data = new Array(10);
  29065. for (var i = 0; i < 10; ++i) {
  29066. if (data && data[i]) {
  29067. this.data[i] = data[i];
  29068. }
  29069. else {
  29070. this.data[i] = 0;
  29071. }
  29072. }
  29073. }
  29074. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29075. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  29076. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  29077. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  29078. return det;
  29079. };
  29080. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29081. for (var i = 0; i < 10; ++i) {
  29082. this.data[i] += matrix.data[i];
  29083. }
  29084. };
  29085. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29086. for (var i = 0; i < 10; ++i) {
  29087. this.data[i] += data[i];
  29088. }
  29089. };
  29090. QuadraticMatrix.prototype.add = function (matrix) {
  29091. var m = new QuadraticMatrix();
  29092. for (var i = 0; i < 10; ++i) {
  29093. m.data[i] = this.data[i] + matrix.data[i];
  29094. }
  29095. return m;
  29096. };
  29097. QuadraticMatrix.FromData = function (a, b, c, d) {
  29098. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29099. };
  29100. //returning an array to avoid garbage collection
  29101. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29102. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29103. };
  29104. return QuadraticMatrix;
  29105. })();
  29106. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29107. var Reference = (function () {
  29108. function Reference(vertexId, triangleId) {
  29109. this.vertexId = vertexId;
  29110. this.triangleId = triangleId;
  29111. }
  29112. return Reference;
  29113. })();
  29114. BABYLON.Reference = Reference;
  29115. /**
  29116. * An implementation of the Quadratic Error simplification algorithm.
  29117. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29118. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29119. * @author RaananW
  29120. */
  29121. var QuadraticErrorSimplification = (function () {
  29122. function QuadraticErrorSimplification(_mesh) {
  29123. this._mesh = _mesh;
  29124. this.initialized = false;
  29125. this.syncIterations = 5000;
  29126. this.aggressiveness = 7;
  29127. this.decimationIterations = 100;
  29128. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29129. }
  29130. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29131. var _this = this;
  29132. this.initDecimatedMesh();
  29133. //iterating through the submeshes array, one after the other.
  29134. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29135. _this.initWithMesh(loop.index, function () {
  29136. _this.runDecimation(settings, loop.index, function () {
  29137. loop.executeNext();
  29138. });
  29139. }, settings.optimizeMesh);
  29140. }, function () {
  29141. setTimeout(function () {
  29142. successCallback(_this._reconstructedMesh);
  29143. }, 0);
  29144. });
  29145. };
  29146. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29147. var _this = this;
  29148. var gCount = 0;
  29149. triangle.vertices.forEach(function (vertex) {
  29150. var count = 0;
  29151. var vPos = vertex.position;
  29152. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29153. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29154. ++count;
  29155. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  29156. ++count;
  29157. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  29158. ++count;
  29159. if (count > 1) {
  29160. ++gCount;
  29161. }
  29162. ;
  29163. });
  29164. if (gCount > 1) {
  29165. console.log(triangle, gCount);
  29166. }
  29167. return gCount > 1;
  29168. };
  29169. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29170. var _this = this;
  29171. var targetCount = ~~(this.triangles.length * settings.quality);
  29172. var deletedTriangles = 0;
  29173. var triangleCount = this.triangles.length;
  29174. var iterationFunction = function (iteration, callback) {
  29175. setTimeout(function () {
  29176. if (iteration % 5 === 0) {
  29177. _this.updateMesh(iteration === 0);
  29178. }
  29179. for (var i = 0; i < _this.triangles.length; ++i) {
  29180. _this.triangles[i].isDirty = false;
  29181. }
  29182. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29183. var trianglesIterator = function (i) {
  29184. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29185. var t = _this.triangles[tIdx];
  29186. if (!t)
  29187. return;
  29188. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29189. return;
  29190. }
  29191. for (var j = 0; j < 3; ++j) {
  29192. if (t.error[j] < threshold) {
  29193. var deleted0 = [];
  29194. var deleted1 = [];
  29195. var v0 = t.vertices[j];
  29196. var v1 = t.vertices[(j + 1) % 3];
  29197. if (v0.isBorder !== v1.isBorder)
  29198. continue;
  29199. var p = BABYLON.Vector3.Zero();
  29200. var n = BABYLON.Vector3.Zero();
  29201. var uv = BABYLON.Vector2.Zero();
  29202. var color = new BABYLON.Color4(0, 0, 0, 1);
  29203. _this.calculateError(v0, v1, p, n, uv, color);
  29204. var delTr = [];
  29205. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29206. continue;
  29207. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29208. continue;
  29209. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29210. continue;
  29211. var uniqueArray = [];
  29212. delTr.forEach(function (deletedT) {
  29213. if (uniqueArray.indexOf(deletedT) === -1) {
  29214. deletedT.deletePending = true;
  29215. uniqueArray.push(deletedT);
  29216. }
  29217. });
  29218. if (uniqueArray.length % 2 !== 0) {
  29219. continue;
  29220. }
  29221. v0.q = v1.q.add(v0.q);
  29222. v0.updatePosition(p);
  29223. var tStart = _this.references.length;
  29224. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29225. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29226. var tCount = _this.references.length - tStart;
  29227. if (tCount <= v0.triangleCount) {
  29228. if (tCount) {
  29229. for (var c = 0; c < tCount; c++) {
  29230. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29231. }
  29232. }
  29233. }
  29234. else {
  29235. v0.triangleStart = tStart;
  29236. }
  29237. v0.triangleCount = tCount;
  29238. break;
  29239. }
  29240. }
  29241. };
  29242. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  29243. }, 0);
  29244. };
  29245. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29246. if (triangleCount - deletedTriangles <= targetCount)
  29247. loop.breakLoop();
  29248. else {
  29249. iterationFunction(loop.index, function () {
  29250. loop.executeNext();
  29251. });
  29252. }
  29253. }, function () {
  29254. setTimeout(function () {
  29255. //reconstruct this part of the mesh
  29256. _this.reconstructMesh(submeshIndex);
  29257. successCallback();
  29258. }, 0);
  29259. });
  29260. };
  29261. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29262. var _this = this;
  29263. this.vertices = [];
  29264. this.triangles = [];
  29265. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29266. var indices = this._mesh.getIndices();
  29267. var submesh = this._mesh.subMeshes[submeshIndex];
  29268. var findInVertices = function (positionToSearch) {
  29269. if (optimizeMesh) {
  29270. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29271. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29272. return _this.vertices[ii];
  29273. }
  29274. }
  29275. }
  29276. return null;
  29277. };
  29278. var vertexReferences = [];
  29279. var vertexInit = function (i) {
  29280. var offset = i + submesh.verticesStart;
  29281. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29282. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29283. vertex.originalOffsets.push(offset);
  29284. if (vertex.id === _this.vertices.length) {
  29285. _this.vertices.push(vertex);
  29286. }
  29287. vertexReferences.push(vertex.id);
  29288. };
  29289. //var totalVertices = mesh.getTotalVertices();
  29290. var totalVertices = submesh.verticesCount;
  29291. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29292. var indicesInit = function (i) {
  29293. var offset = (submesh.indexStart / 3) + i;
  29294. var pos = (offset * 3);
  29295. var i0 = indices[pos + 0];
  29296. var i1 = indices[pos + 1];
  29297. var i2 = indices[pos + 2];
  29298. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29299. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29300. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29301. var triangle = new DecimationTriangle([v0, v1, v2]);
  29302. triangle.originalOffset = pos;
  29303. _this.triangles.push(triangle);
  29304. };
  29305. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29306. _this.init(callback);
  29307. });
  29308. });
  29309. };
  29310. QuadraticErrorSimplification.prototype.init = function (callback) {
  29311. var _this = this;
  29312. var triangleInit1 = function (i) {
  29313. var t = _this.triangles[i];
  29314. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29315. for (var j = 0; j < 3; j++) {
  29316. 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))));
  29317. }
  29318. };
  29319. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29320. var triangleInit2 = function (i) {
  29321. var t = _this.triangles[i];
  29322. for (var j = 0; j < 3; ++j) {
  29323. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29324. }
  29325. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29326. };
  29327. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29328. _this.initialized = true;
  29329. callback();
  29330. });
  29331. });
  29332. };
  29333. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29334. var newTriangles = [];
  29335. var i;
  29336. for (i = 0; i < this.vertices.length; ++i) {
  29337. this.vertices[i].triangleCount = 0;
  29338. }
  29339. var t;
  29340. var j;
  29341. for (i = 0; i < this.triangles.length; ++i) {
  29342. if (!this.triangles[i].deleted) {
  29343. t = this.triangles[i];
  29344. for (j = 0; j < 3; ++j) {
  29345. t.vertices[j].triangleCount = 1;
  29346. }
  29347. newTriangles.push(t);
  29348. }
  29349. }
  29350. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  29351. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  29352. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  29353. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  29354. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29355. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29356. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29357. var vertexCount = 0;
  29358. for (i = 0; i < this.vertices.length; ++i) {
  29359. var vertex = this.vertices[i];
  29360. vertex.id = vertexCount;
  29361. if (vertex.triangleCount) {
  29362. vertex.originalOffsets.forEach(function (originalOffset) {
  29363. newPositionData.push(vertex.position.x);
  29364. newPositionData.push(vertex.position.y);
  29365. newPositionData.push(vertex.position.z);
  29366. newNormalData.push(normalData[originalOffset * 3]);
  29367. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29368. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29369. if (uvs && uvs.length) {
  29370. newUVsData.push(uvs[(originalOffset * 2)]);
  29371. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29372. }
  29373. else if (colorsData && colorsData.length) {
  29374. newColorsData.push(colorsData[(originalOffset * 4)]);
  29375. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29376. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29377. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29378. }
  29379. ++vertexCount;
  29380. });
  29381. }
  29382. }
  29383. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29384. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29385. var submeshesArray = this._reconstructedMesh.subMeshes;
  29386. this._reconstructedMesh.subMeshes = [];
  29387. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29388. var originalIndices = this._mesh.getIndices();
  29389. for (i = 0; i < newTriangles.length; ++i) {
  29390. t = newTriangles[i]; //now get the new referencing point for each vertex
  29391. [0, 1, 2].forEach(function (idx) {
  29392. var id = originalIndices[t.originalOffset + idx];
  29393. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29394. if (offset < 0)
  29395. offset = 0;
  29396. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29397. });
  29398. }
  29399. //overwriting the old vertex buffers and indices.
  29400. this._reconstructedMesh.setIndices(newIndicesArray);
  29401. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29402. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29403. if (newUVsData.length > 0)
  29404. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29405. if (newColorsData.length > 0)
  29406. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29407. //create submesh
  29408. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29409. if (submeshIndex > 0) {
  29410. this._reconstructedMesh.subMeshes = [];
  29411. submeshesArray.forEach(function (submesh) {
  29412. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29413. });
  29414. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29415. }
  29416. };
  29417. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29418. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29419. this._reconstructedMesh.material = this._mesh.material;
  29420. this._reconstructedMesh.parent = this._mesh.parent;
  29421. this._reconstructedMesh.isVisible = false;
  29422. };
  29423. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29424. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29425. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29426. if (t.deleted)
  29427. continue;
  29428. var s = this.references[vertex1.triangleStart + i].vertexId;
  29429. var v1 = t.vertices[(s + 1) % 3];
  29430. var v2 = t.vertices[(s + 2) % 3];
  29431. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29432. deletedArray[i] = true;
  29433. delTr.push(t);
  29434. continue;
  29435. }
  29436. var d1 = v1.position.subtract(point);
  29437. d1 = d1.normalize();
  29438. var d2 = v2.position.subtract(point);
  29439. d2 = d2.normalize();
  29440. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29441. return true;
  29442. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29443. deletedArray[i] = false;
  29444. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29445. return true;
  29446. }
  29447. return false;
  29448. };
  29449. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29450. var newDeleted = deletedTriangles;
  29451. for (var i = 0; i < vertex.triangleCount; ++i) {
  29452. var ref = this.references[vertex.triangleStart + i];
  29453. var t = this.triangles[ref.triangleId];
  29454. if (t.deleted)
  29455. continue;
  29456. if (deletedArray[i] && t.deletePending) {
  29457. t.deleted = true;
  29458. newDeleted++;
  29459. continue;
  29460. }
  29461. t.vertices[ref.vertexId] = origVertex;
  29462. t.isDirty = true;
  29463. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29464. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29465. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29466. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29467. this.references.push(ref);
  29468. }
  29469. return newDeleted;
  29470. };
  29471. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29472. for (var i = 0; i < this.vertices.length; ++i) {
  29473. var vCount = [];
  29474. var vId = [];
  29475. var v = this.vertices[i];
  29476. var j;
  29477. for (j = 0; j < v.triangleCount; ++j) {
  29478. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29479. for (var ii = 0; ii < 3; ii++) {
  29480. var ofs = 0;
  29481. var vv = triangle.vertices[ii];
  29482. while (ofs < vCount.length) {
  29483. if (vId[ofs] === vv.id)
  29484. break;
  29485. ++ofs;
  29486. }
  29487. if (ofs === vCount.length) {
  29488. vCount.push(1);
  29489. vId.push(vv.id);
  29490. }
  29491. else {
  29492. vCount[ofs]++;
  29493. }
  29494. }
  29495. }
  29496. for (j = 0; j < vCount.length; ++j) {
  29497. if (vCount[j] === 1) {
  29498. this.vertices[vId[j]].isBorder = true;
  29499. }
  29500. else {
  29501. this.vertices[vId[j]].isBorder = false;
  29502. }
  29503. }
  29504. }
  29505. };
  29506. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29507. if (identifyBorders === void 0) { identifyBorders = false; }
  29508. var i;
  29509. if (!identifyBorders) {
  29510. var newTrianglesVector = [];
  29511. for (i = 0; i < this.triangles.length; ++i) {
  29512. if (!this.triangles[i].deleted) {
  29513. newTrianglesVector.push(this.triangles[i]);
  29514. }
  29515. }
  29516. this.triangles = newTrianglesVector;
  29517. }
  29518. for (i = 0; i < this.vertices.length; ++i) {
  29519. this.vertices[i].triangleCount = 0;
  29520. this.vertices[i].triangleStart = 0;
  29521. }
  29522. var t;
  29523. var j;
  29524. var v;
  29525. for (i = 0; i < this.triangles.length; ++i) {
  29526. t = this.triangles[i];
  29527. for (j = 0; j < 3; ++j) {
  29528. v = t.vertices[j];
  29529. v.triangleCount++;
  29530. }
  29531. }
  29532. var tStart = 0;
  29533. for (i = 0; i < this.vertices.length; ++i) {
  29534. this.vertices[i].triangleStart = tStart;
  29535. tStart += this.vertices[i].triangleCount;
  29536. this.vertices[i].triangleCount = 0;
  29537. }
  29538. var newReferences = new Array(this.triangles.length * 3);
  29539. for (i = 0; i < this.triangles.length; ++i) {
  29540. t = this.triangles[i];
  29541. for (j = 0; j < 3; ++j) {
  29542. v = t.vertices[j];
  29543. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29544. v.triangleCount++;
  29545. }
  29546. }
  29547. this.references = newReferences;
  29548. if (identifyBorders) {
  29549. this.identifyBorder();
  29550. }
  29551. };
  29552. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29553. var x = point.x;
  29554. var y = point.y;
  29555. var z = point.z;
  29556. 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
  29557. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29558. };
  29559. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29560. var q = vertex1.q.add(vertex2.q);
  29561. var border = vertex1.isBorder && vertex2.isBorder;
  29562. var error = 0;
  29563. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29564. if (qDet !== 0 && !border) {
  29565. if (!pointResult) {
  29566. pointResult = BABYLON.Vector3.Zero();
  29567. }
  29568. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29569. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29570. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29571. error = this.vertexError(q, pointResult);
  29572. }
  29573. else {
  29574. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29575. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29576. var error1 = this.vertexError(q, vertex1.position);
  29577. var error2 = this.vertexError(q, vertex2.position);
  29578. var error3 = this.vertexError(q, p3);
  29579. error = Math.min(error1, error2, error3);
  29580. if (error === error1) {
  29581. if (pointResult) {
  29582. pointResult.copyFrom(vertex1.position);
  29583. }
  29584. }
  29585. else if (error === error2) {
  29586. if (pointResult) {
  29587. pointResult.copyFrom(vertex2.position);
  29588. }
  29589. }
  29590. else {
  29591. if (pointResult) {
  29592. pointResult.copyFrom(p3);
  29593. }
  29594. }
  29595. }
  29596. return error;
  29597. };
  29598. return QuadraticErrorSimplification;
  29599. })();
  29600. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29601. })(BABYLON || (BABYLON = {}));
  29602. var BABYLON;
  29603. (function (BABYLON) {
  29604. var serializeLight = function (light) {
  29605. var serializationObject = {};
  29606. serializationObject.name = light.name;
  29607. serializationObject.id = light.id;
  29608. serializationObject.tags = BABYLON.Tags.GetTags(light);
  29609. if (light instanceof BABYLON.PointLight) {
  29610. serializationObject.type = 0;
  29611. serializationObject.position = (light).position.asArray();
  29612. }
  29613. else if (light instanceof BABYLON.DirectionalLight) {
  29614. serializationObject.type = 1;
  29615. var directionalLight = light;
  29616. serializationObject.position = directionalLight.position.asArray();
  29617. serializationObject.direction = directionalLight.direction.asArray();
  29618. }
  29619. else if (light instanceof BABYLON.SpotLight) {
  29620. serializationObject.type = 2;
  29621. var spotLight = light;
  29622. serializationObject.position = spotLight.position.asArray();
  29623. serializationObject.direction = spotLight.position.asArray();
  29624. serializationObject.angle = spotLight.angle;
  29625. serializationObject.exponent = spotLight.exponent;
  29626. }
  29627. else if (light instanceof BABYLON.HemisphericLight) {
  29628. serializationObject.type = 3;
  29629. var hemisphericLight = light;
  29630. serializationObject.direction = hemisphericLight.direction.asArray();
  29631. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  29632. }
  29633. if (light.intensity) {
  29634. serializationObject.intensity = light.intensity;
  29635. }
  29636. serializationObject.range = light.range;
  29637. serializationObject.diffuse = light.diffuse.asArray();
  29638. serializationObject.specular = light.specular.asArray();
  29639. return serializationObject;
  29640. };
  29641. var serializeFresnelParameter = function (fresnelParameter) {
  29642. var serializationObject = {};
  29643. serializationObject.isEnabled = fresnelParameter.isEnabled;
  29644. serializationObject.leftColor = fresnelParameter.leftColor;
  29645. serializationObject.rightColor = fresnelParameter.rightColor;
  29646. serializationObject.bias = fresnelParameter.bias;
  29647. serializationObject.power = fresnelParameter.power;
  29648. return serializationObject;
  29649. };
  29650. var serializeAnimation;
  29651. var appendAnimations = function (source, destination) {
  29652. if (source.animations) {
  29653. destination.animations = [];
  29654. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29655. var animation = source.animations[animationIndex];
  29656. destination.animations.push(serializeAnimation(animation));
  29657. }
  29658. }
  29659. };
  29660. var serializeCamera = function (camera) {
  29661. var serializationObject = {};
  29662. serializationObject.name = camera.name;
  29663. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  29664. serializationObject.id = camera.id;
  29665. serializationObject.position = camera.position.asArray();
  29666. // Parent
  29667. if (camera.parent) {
  29668. serializationObject.parentId = camera.parent.id;
  29669. }
  29670. serializationObject.fov = camera.fov;
  29671. serializationObject.minZ = camera.minZ;
  29672. serializationObject.maxZ = camera.maxZ;
  29673. serializationObject.inertia = camera.inertia;
  29674. //setting the type
  29675. if (camera instanceof BABYLON.FreeCamera) {
  29676. serializationObject.type = "FreeCamera";
  29677. }
  29678. else if (camera instanceof BABYLON.ArcRotateCamera) {
  29679. serializationObject.type = "ArcRotateCamera";
  29680. }
  29681. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29682. serializationObject.type = "AnaglyphArcRotateCamera";
  29683. }
  29684. else if (camera instanceof BABYLON.GamepadCamera) {
  29685. serializationObject.type = "GamepadCamera";
  29686. }
  29687. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  29688. serializationObject.type = "AnaglyphFreeCamera";
  29689. }
  29690. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  29691. serializationObject.type = "DeviceOrientationCamera";
  29692. }
  29693. else if (camera instanceof BABYLON.FollowCamera) {
  29694. serializationObject.type = "FollowCamera";
  29695. }
  29696. else if (camera instanceof BABYLON.TouchCamera) {
  29697. serializationObject.type = "TouchCamera";
  29698. }
  29699. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  29700. serializationObject.type = "VirtualJoysticksCamera";
  29701. }
  29702. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  29703. serializationObject.type = "WebVRFreeCamera";
  29704. }
  29705. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  29706. serializationObject.type = "VRDeviceOrientationFreeCamera";
  29707. }
  29708. //special properties of specific cameras
  29709. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29710. var arcCamera = camera;
  29711. serializationObject.alpha = arcCamera.alpha;
  29712. serializationObject.beta = arcCamera.beta;
  29713. serializationObject.radius = arcCamera.radius;
  29714. if (arcCamera.target && arcCamera.target.id) {
  29715. serializationObject.lockedTargetId = arcCamera.target.id;
  29716. }
  29717. }
  29718. else if (camera instanceof BABYLON.FollowCamera) {
  29719. var followCam = camera;
  29720. serializationObject.radius = followCam.radius;
  29721. serializationObject.heightOffset = followCam.heightOffset;
  29722. serializationObject.rotationOffset = followCam.rotationOffset;
  29723. }
  29724. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29725. //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.
  29726. if (camera['_interaxialDistance'] !== undefined) {
  29727. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  29728. }
  29729. }
  29730. //general properties that not all cameras have. The [] is due to typescript's type safety
  29731. if (camera['speed'] !== undefined) {
  29732. serializationObject.speed = camera['speed'];
  29733. }
  29734. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  29735. serializationObject.target = camera['target'].asArray();
  29736. }
  29737. // Target
  29738. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  29739. serializationObject.rotation = camera['rotation'].asArray();
  29740. }
  29741. // Locked target
  29742. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  29743. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  29744. }
  29745. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  29746. serializationObject.applyGravity = camera['applyGravity'] || false;
  29747. if (camera['ellipsoid']) {
  29748. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  29749. }
  29750. // Animations
  29751. appendAnimations(camera, serializationObject);
  29752. // Layer mask
  29753. serializationObject.layerMask = camera.layerMask;
  29754. return serializationObject;
  29755. };
  29756. serializeAnimation = function (animation) {
  29757. var serializationObject = {};
  29758. serializationObject.name = animation.name;
  29759. serializationObject.property = animation.targetProperty;
  29760. serializationObject.framePerSecond = animation.framePerSecond;
  29761. serializationObject.dataType = animation.dataType;
  29762. serializationObject.loopBehavior = animation.loopMode;
  29763. var dataType = animation.dataType;
  29764. serializationObject.keys = [];
  29765. var keys = animation.getKeys();
  29766. for (var index = 0; index < keys.length; index++) {
  29767. var animationKey = keys[index];
  29768. var key = {};
  29769. key.frame = animationKey.frame;
  29770. switch (dataType) {
  29771. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  29772. key.values = [animationKey.value];
  29773. break;
  29774. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  29775. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  29776. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  29777. key.values = animationKey.value.asArray();
  29778. break;
  29779. }
  29780. serializationObject.keys.push(key);
  29781. }
  29782. return serializationObject;
  29783. };
  29784. var serializeMultiMaterial = function (material) {
  29785. var serializationObject = {};
  29786. serializationObject.name = material.name;
  29787. serializationObject.id = material.id;
  29788. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29789. serializationObject.materials = [];
  29790. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  29791. var subMat = material.subMaterials[matIndex];
  29792. if (subMat) {
  29793. serializationObject.materials.push(subMat.id);
  29794. }
  29795. else {
  29796. serializationObject.materials.push(null);
  29797. }
  29798. }
  29799. return serializationObject;
  29800. };
  29801. var serializeTexture;
  29802. var serializeMaterial = function (material) {
  29803. var serializationObject = {};
  29804. serializationObject.name = material.name;
  29805. serializationObject.ambient = material.ambientColor.asArray();
  29806. serializationObject.diffuse = material.diffuseColor.asArray();
  29807. serializationObject.specular = material.specularColor.asArray();
  29808. serializationObject.specularPower = material.specularPower;
  29809. serializationObject.emissive = material.emissiveColor.asArray();
  29810. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  29811. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  29812. serializationObject.alpha = material.alpha;
  29813. serializationObject.id = material.id;
  29814. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29815. serializationObject.backFaceCulling = material.backFaceCulling;
  29816. if (material.diffuseTexture) {
  29817. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  29818. }
  29819. if (material.diffuseFresnelParameters) {
  29820. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  29821. }
  29822. if (material.ambientTexture) {
  29823. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  29824. }
  29825. if (material.opacityTexture) {
  29826. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  29827. }
  29828. if (material.opacityFresnelParameters) {
  29829. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  29830. }
  29831. if (material.reflectionTexture) {
  29832. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  29833. }
  29834. if (material.reflectionFresnelParameters) {
  29835. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  29836. }
  29837. if (material.emissiveTexture) {
  29838. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  29839. }
  29840. if (material.lightmapTexture) {
  29841. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  29842. serializationObject.useLightmapAsShadowmap = material.useLightmapAsShadowmap;
  29843. }
  29844. if (material.emissiveFresnelParameters) {
  29845. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  29846. }
  29847. if (material.specularTexture) {
  29848. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  29849. }
  29850. if (material.bumpTexture) {
  29851. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  29852. }
  29853. return serializationObject;
  29854. };
  29855. serializeTexture = function (texture) {
  29856. var serializationObject = {};
  29857. if (!texture.name) {
  29858. return null;
  29859. }
  29860. if (texture instanceof BABYLON.CubeTexture) {
  29861. serializationObject.name = texture.name;
  29862. serializationObject.hasAlpha = texture.hasAlpha;
  29863. serializationObject.isCube = true;
  29864. serializationObject.level = texture.level;
  29865. serializationObject.coordinatesMode = texture.coordinatesMode;
  29866. return serializationObject;
  29867. }
  29868. var index;
  29869. if (texture instanceof BABYLON.MirrorTexture) {
  29870. var mirrorTexture = texture;
  29871. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  29872. serializationObject.renderList = [];
  29873. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  29874. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  29875. }
  29876. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  29877. }
  29878. else if (texture instanceof BABYLON.RenderTargetTexture) {
  29879. var renderTargetTexture = texture;
  29880. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  29881. serializationObject.renderList = [];
  29882. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  29883. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  29884. }
  29885. }
  29886. var regularTexture = texture;
  29887. serializationObject.name = texture.name;
  29888. serializationObject.hasAlpha = texture.hasAlpha;
  29889. serializationObject.level = texture.level;
  29890. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  29891. serializationObject.coordinatesMode = texture.coordinatesMode;
  29892. serializationObject.uOffset = regularTexture.uOffset;
  29893. serializationObject.vOffset = regularTexture.vOffset;
  29894. serializationObject.uScale = regularTexture.uScale;
  29895. serializationObject.vScale = regularTexture.vScale;
  29896. serializationObject.uAng = regularTexture.uAng;
  29897. serializationObject.vAng = regularTexture.vAng;
  29898. serializationObject.wAng = regularTexture.wAng;
  29899. serializationObject.wrapU = texture.wrapU;
  29900. serializationObject.wrapV = texture.wrapV;
  29901. // Animations
  29902. appendAnimations(texture, serializationObject);
  29903. return serializationObject;
  29904. };
  29905. var serializeSkeleton = function (skeleton) {
  29906. var serializationObject = {};
  29907. serializationObject.name = skeleton.name;
  29908. serializationObject.id = skeleton.id;
  29909. serializationObject.bones = [];
  29910. for (var index = 0; index < skeleton.bones.length; index++) {
  29911. var bone = skeleton.bones[index];
  29912. var serializedBone = {
  29913. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  29914. name: bone.name,
  29915. matrix: bone.getLocalMatrix().toArray()
  29916. };
  29917. serializationObject.bones.push(serializedBone);
  29918. if (bone.animations && bone.animations.length > 0) {
  29919. serializedBone.animation = serializeAnimation(bone.animations[0]);
  29920. }
  29921. }
  29922. return serializationObject;
  29923. };
  29924. var serializeParticleSystem = function (particleSystem) {
  29925. var serializationObject = {};
  29926. serializationObject.emitterId = particleSystem.emitter.id;
  29927. serializationObject.capacity = particleSystem.getCapacity();
  29928. if (particleSystem.particleTexture) {
  29929. serializationObject.textureName = particleSystem.particleTexture.name;
  29930. }
  29931. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  29932. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  29933. serializationObject.minSize = particleSystem.minSize;
  29934. serializationObject.maxSize = particleSystem.maxSize;
  29935. serializationObject.minLifeTime = particleSystem.minLifeTime;
  29936. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  29937. serializationObject.emitRate = particleSystem.emitRate;
  29938. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  29939. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  29940. serializationObject.gravity = particleSystem.gravity.asArray();
  29941. serializationObject.direction1 = particleSystem.direction1.asArray();
  29942. serializationObject.direction2 = particleSystem.direction2.asArray();
  29943. serializationObject.color1 = particleSystem.color1.asArray();
  29944. serializationObject.color2 = particleSystem.color2.asArray();
  29945. serializationObject.colorDead = particleSystem.colorDead.asArray();
  29946. serializationObject.updateSpeed = particleSystem.updateSpeed;
  29947. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  29948. serializationObject.textureMask = particleSystem.textureMask.asArray();
  29949. serializationObject.blendMode = particleSystem.blendMode;
  29950. return serializationObject;
  29951. };
  29952. var serializeLensFlareSystem = function (lensFlareSystem) {
  29953. var serializationObject = {};
  29954. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  29955. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  29956. serializationObject.flares = [];
  29957. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  29958. var flare = lensFlareSystem.lensFlares[index];
  29959. serializationObject.flares.push({
  29960. size: flare.size,
  29961. position: flare.position,
  29962. color: flare.color.asArray(),
  29963. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  29964. });
  29965. }
  29966. return serializationObject;
  29967. };
  29968. var serializeShadowGenerator = function (light) {
  29969. var serializationObject = {};
  29970. var shadowGenerator = light.getShadowGenerator();
  29971. serializationObject.lightId = light.id;
  29972. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  29973. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  29974. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  29975. serializationObject.renderList = [];
  29976. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  29977. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  29978. serializationObject.renderList.push(mesh.id);
  29979. }
  29980. return serializationObject;
  29981. };
  29982. var serializedGeometries = [];
  29983. var serializeVertexData;
  29984. var serializeTorusKnot;
  29985. var serializePlane;
  29986. var serializeGround;
  29987. var serializeTorus;
  29988. var serializeCylinder;
  29989. var serializeSphere;
  29990. var serializeBox;
  29991. var serializeGeometry = function (geometry, serializationGeometries) {
  29992. if (serializedGeometries[geometry.id]) {
  29993. return;
  29994. }
  29995. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29996. serializationGeometries.boxes.push(serializeBox(geometry));
  29997. }
  29998. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29999. serializationGeometries.spheres.push(serializeSphere(geometry));
  30000. }
  30001. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  30002. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  30003. }
  30004. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  30005. serializationGeometries.toruses.push(serializeTorus(geometry));
  30006. }
  30007. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  30008. serializationGeometries.grounds.push(serializeGround(geometry));
  30009. }
  30010. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  30011. serializationGeometries.planes.push(serializePlane(geometry));
  30012. }
  30013. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  30014. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  30015. }
  30016. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  30017. throw new Error("Unknown primitive type");
  30018. }
  30019. else {
  30020. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  30021. }
  30022. serializedGeometries[geometry.id] = true;
  30023. };
  30024. var serializeGeometryBase = function (geometry) {
  30025. var serializationObject = {};
  30026. serializationObject.id = geometry.id;
  30027. if (BABYLON.Tags.HasTags(geometry)) {
  30028. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  30029. }
  30030. return serializationObject;
  30031. };
  30032. serializeVertexData = function (vertexData) {
  30033. var serializationObject = serializeGeometryBase(vertexData);
  30034. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30035. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30036. }
  30037. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30038. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30039. }
  30040. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30041. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30042. }
  30043. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30044. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  30045. }
  30046. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30047. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  30048. }
  30049. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30050. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  30051. }
  30052. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30053. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  30054. }
  30055. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30056. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  30057. }
  30058. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30059. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30060. }
  30061. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30062. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30063. serializationObject.matricesIndices._isExpanded = true;
  30064. }
  30065. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30066. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30067. }
  30068. serializationObject.indices = vertexData.getIndices();
  30069. return serializationObject;
  30070. };
  30071. var serializePrimitive = function (primitive) {
  30072. var serializationObject = serializeGeometryBase(primitive);
  30073. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  30074. return serializationObject;
  30075. };
  30076. serializeBox = function (box) {
  30077. var serializationObject = serializePrimitive(box);
  30078. serializationObject.size = box.size;
  30079. return serializationObject;
  30080. };
  30081. serializeSphere = function (sphere) {
  30082. var serializationObject = serializePrimitive(sphere);
  30083. serializationObject.segments = sphere.segments;
  30084. serializationObject.diameter = sphere.diameter;
  30085. return serializationObject;
  30086. };
  30087. serializeCylinder = function (cylinder) {
  30088. var serializationObject = serializePrimitive(cylinder);
  30089. serializationObject.height = cylinder.height;
  30090. serializationObject.diameterTop = cylinder.diameterTop;
  30091. serializationObject.diameterBottom = cylinder.diameterBottom;
  30092. serializationObject.tessellation = cylinder.tessellation;
  30093. return serializationObject;
  30094. };
  30095. serializeTorus = function (torus) {
  30096. var serializationObject = serializePrimitive(torus);
  30097. serializationObject.diameter = torus.diameter;
  30098. serializationObject.thickness = torus.thickness;
  30099. serializationObject.tessellation = torus.tessellation;
  30100. return serializationObject;
  30101. };
  30102. serializeGround = function (ground) {
  30103. var serializationObject = serializePrimitive(ground);
  30104. serializationObject.width = ground.width;
  30105. serializationObject.height = ground.height;
  30106. serializationObject.subdivisions = ground.subdivisions;
  30107. return serializationObject;
  30108. };
  30109. serializePlane = function (plane) {
  30110. var serializationObject = serializePrimitive(plane);
  30111. serializationObject.size = plane.size;
  30112. return serializationObject;
  30113. };
  30114. serializeTorusKnot = function (torusKnot) {
  30115. var serializationObject = serializePrimitive(torusKnot);
  30116. serializationObject.radius = torusKnot.radius;
  30117. serializationObject.tube = torusKnot.tube;
  30118. serializationObject.radialSegments = torusKnot.radialSegments;
  30119. serializationObject.tubularSegments = torusKnot.tubularSegments;
  30120. serializationObject.p = torusKnot.p;
  30121. serializationObject.q = torusKnot.q;
  30122. return serializationObject;
  30123. };
  30124. var serializeMesh = function (mesh, serializationScene) {
  30125. var serializationObject = {};
  30126. serializationObject.name = mesh.name;
  30127. serializationObject.id = mesh.id;
  30128. if (BABYLON.Tags.HasTags(mesh)) {
  30129. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  30130. }
  30131. serializationObject.position = mesh.position.asArray();
  30132. if (mesh.rotationQuaternion) {
  30133. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  30134. }
  30135. else if (mesh.rotation) {
  30136. serializationObject.rotation = mesh.rotation.asArray();
  30137. }
  30138. serializationObject.scaling = mesh.scaling.asArray();
  30139. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  30140. serializationObject.isEnabled = mesh.isEnabled();
  30141. serializationObject.isVisible = mesh.isVisible;
  30142. serializationObject.infiniteDistance = mesh.infiniteDistance;
  30143. serializationObject.pickable = mesh.isPickable;
  30144. serializationObject.receiveShadows = mesh.receiveShadows;
  30145. serializationObject.billboardMode = mesh.billboardMode;
  30146. serializationObject.visibility = mesh.visibility;
  30147. serializationObject.checkCollisions = mesh.checkCollisions;
  30148. // Parent
  30149. if (mesh.parent) {
  30150. serializationObject.parentId = mesh.parent.id;
  30151. }
  30152. // Geometry
  30153. var geometry = mesh._geometry;
  30154. if (geometry) {
  30155. var geometryId = geometry.id;
  30156. serializationObject.geometryId = geometryId;
  30157. if (!mesh.getScene().getGeometryByID(geometryId)) {
  30158. // 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
  30159. serializeGeometry(geometry, serializationScene.geometries);
  30160. }
  30161. // SubMeshes
  30162. serializationObject.subMeshes = [];
  30163. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30164. var subMesh = mesh.subMeshes[subIndex];
  30165. serializationObject.subMeshes.push({
  30166. materialIndex: subMesh.materialIndex,
  30167. verticesStart: subMesh.verticesStart,
  30168. verticesCount: subMesh.verticesCount,
  30169. indexStart: subMesh.indexStart,
  30170. indexCount: subMesh.indexCount
  30171. });
  30172. }
  30173. }
  30174. // Material
  30175. if (mesh.material) {
  30176. serializationObject.materialId = mesh.material.id;
  30177. }
  30178. else {
  30179. mesh.material = null;
  30180. }
  30181. // Skeleton
  30182. if (mesh.skeleton) {
  30183. serializationObject.skeletonId = mesh.skeleton.id;
  30184. }
  30185. // Physics
  30186. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  30187. serializationObject.physicsMass = mesh.getPhysicsMass();
  30188. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  30189. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  30190. switch (mesh.getPhysicsImpostor()) {
  30191. case BABYLON.PhysicsEngine.BoxImpostor:
  30192. serializationObject.physicsImpostor = 1;
  30193. break;
  30194. case BABYLON.PhysicsEngine.SphereImpostor:
  30195. serializationObject.physicsImpostor = 2;
  30196. break;
  30197. }
  30198. }
  30199. // Instances
  30200. serializationObject.instances = [];
  30201. for (var index = 0; index < mesh.instances.length; index++) {
  30202. var instance = mesh.instances[index];
  30203. var serializationInstance = {
  30204. name: instance.name,
  30205. position: instance.position.asArray(),
  30206. rotation: instance.rotation.asArray(),
  30207. rotationQuaternion: instance.rotationQuaternion.asArray(),
  30208. scaling: instance.scaling.asArray()
  30209. };
  30210. serializationObject.instances.push(serializationInstance);
  30211. // Animations
  30212. appendAnimations(instance, serializationInstance);
  30213. }
  30214. // Animations
  30215. appendAnimations(mesh, serializationObject);
  30216. // Layer mask
  30217. serializationObject.layerMask = mesh.layerMask;
  30218. return serializationObject;
  30219. };
  30220. var finalizeSingleMesh = function (mesh, serializationObject) {
  30221. //only works if the mesh is already loaded
  30222. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30223. //serialize material
  30224. if (mesh.material) {
  30225. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30226. serializationObject.materials = serializationObject.materials || [];
  30227. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30228. serializationObject.materials.push(serializeMaterial(mesh.material));
  30229. }
  30230. }
  30231. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30232. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30233. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30234. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  30235. }
  30236. }
  30237. }
  30238. //serialize geometry
  30239. var geometry = mesh._geometry;
  30240. if (geometry) {
  30241. if (!serializationObject.geometries) {
  30242. serializationObject.geometries = {};
  30243. serializationObject.geometries.boxes = [];
  30244. serializationObject.geometries.spheres = [];
  30245. serializationObject.geometries.cylinders = [];
  30246. serializationObject.geometries.toruses = [];
  30247. serializationObject.geometries.grounds = [];
  30248. serializationObject.geometries.planes = [];
  30249. serializationObject.geometries.torusKnots = [];
  30250. serializationObject.geometries.vertexData = [];
  30251. }
  30252. serializeGeometry(geometry, serializationObject.geometries);
  30253. }
  30254. // Skeletons
  30255. if (mesh.skeleton) {
  30256. serializationObject.skeletons = serializationObject.skeletons || [];
  30257. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  30258. }
  30259. //serialize the actual mesh
  30260. serializationObject.meshes = serializationObject.meshes || [];
  30261. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30262. }
  30263. };
  30264. var SceneSerializer = (function () {
  30265. function SceneSerializer() {
  30266. }
  30267. SceneSerializer.Serialize = function (scene) {
  30268. var serializationObject = {};
  30269. // Scene
  30270. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30271. serializationObject.autoClear = scene.autoClear;
  30272. serializationObject.clearColor = scene.clearColor.asArray();
  30273. serializationObject.ambientColor = scene.ambientColor.asArray();
  30274. serializationObject.gravity = scene.gravity.asArray();
  30275. // Fog
  30276. if (scene.fogMode && scene.fogMode !== 0) {
  30277. serializationObject.fogMode = scene.fogMode;
  30278. serializationObject.fogColor = scene.fogColor.asArray();
  30279. serializationObject.fogStart = scene.fogStart;
  30280. serializationObject.fogEnd = scene.fogEnd;
  30281. serializationObject.fogDensity = scene.fogDensity;
  30282. }
  30283. // Lights
  30284. serializationObject.lights = [];
  30285. var index;
  30286. var light;
  30287. for (index = 0; index < scene.lights.length; index++) {
  30288. light = scene.lights[index];
  30289. serializationObject.lights.push(serializeLight(light));
  30290. }
  30291. // Cameras
  30292. serializationObject.cameras = [];
  30293. for (index = 0; index < scene.cameras.length; index++) {
  30294. var camera = scene.cameras[index];
  30295. serializationObject.cameras.push(serializeCamera(camera));
  30296. }
  30297. if (scene.activeCamera) {
  30298. serializationObject.activeCameraID = scene.activeCamera.id;
  30299. }
  30300. // Materials
  30301. serializationObject.materials = [];
  30302. serializationObject.multiMaterials = [];
  30303. var material;
  30304. for (index = 0; index < scene.materials.length; index++) {
  30305. material = scene.materials[index];
  30306. serializationObject.materials.push(serializeMaterial(material));
  30307. }
  30308. // MultiMaterials
  30309. serializationObject.multiMaterials = [];
  30310. for (index = 0; index < scene.multiMaterials.length; index++) {
  30311. var multiMaterial = scene.multiMaterials[index];
  30312. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  30313. }
  30314. for (index = 0; index < scene.materials.length; index++) {
  30315. material = scene.materials[index];
  30316. if (material instanceof BABYLON.StandardMaterial) {
  30317. serializationObject.materials.push(serializeMaterial(material));
  30318. }
  30319. else if (material instanceof BABYLON.MultiMaterial) {
  30320. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  30321. }
  30322. }
  30323. // Skeletons
  30324. serializationObject.skeletons = [];
  30325. for (index = 0; index < scene.skeletons.length; index++) {
  30326. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  30327. }
  30328. // Geometries
  30329. serializationObject.geometries = {};
  30330. serializationObject.geometries.boxes = [];
  30331. serializationObject.geometries.spheres = [];
  30332. serializationObject.geometries.cylinders = [];
  30333. serializationObject.geometries.toruses = [];
  30334. serializationObject.geometries.grounds = [];
  30335. serializationObject.geometries.planes = [];
  30336. serializationObject.geometries.torusKnots = [];
  30337. serializationObject.geometries.vertexData = [];
  30338. serializedGeometries = [];
  30339. var geometries = scene.getGeometries();
  30340. for (index = 0; index < geometries.length; index++) {
  30341. var geometry = geometries[index];
  30342. if (geometry.isReady()) {
  30343. serializeGeometry(geometry, serializationObject.geometries);
  30344. }
  30345. }
  30346. // Meshes
  30347. serializationObject.meshes = [];
  30348. for (index = 0; index < scene.meshes.length; index++) {
  30349. var abstractMesh = scene.meshes[index];
  30350. if (abstractMesh instanceof BABYLON.Mesh) {
  30351. var mesh = abstractMesh;
  30352. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30353. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30354. }
  30355. }
  30356. }
  30357. // Particles Systems
  30358. serializationObject.particleSystems = [];
  30359. for (index = 0; index < scene.particleSystems.length; index++) {
  30360. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  30361. }
  30362. // Lens flares
  30363. serializationObject.lensFlareSystems = [];
  30364. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30365. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  30366. }
  30367. // Shadows
  30368. serializationObject.shadowGenerators = [];
  30369. for (index = 0; index < scene.lights.length; index++) {
  30370. light = scene.lights[index];
  30371. if (light.getShadowGenerator()) {
  30372. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  30373. }
  30374. }
  30375. return serializationObject;
  30376. };
  30377. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30378. if (withParents === void 0) { withParents = false; }
  30379. if (withChildren === void 0) { withChildren = false; }
  30380. var serializationObject = {};
  30381. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30382. if (withParents || withChildren) {
  30383. //deliberate for loop! not for each, appended should be processed as well.
  30384. for (var i = 0; i < toSerialize.length; ++i) {
  30385. if (withChildren) {
  30386. toSerialize[i].getDescendants().forEach(function (node) {
  30387. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30388. toSerialize.push(node);
  30389. }
  30390. });
  30391. }
  30392. //make sure the array doesn't contain the object already
  30393. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30394. toSerialize.push(toSerialize[i].parent);
  30395. }
  30396. }
  30397. }
  30398. toSerialize.forEach(function (mesh) {
  30399. finalizeSingleMesh(mesh, serializationObject);
  30400. });
  30401. return serializationObject;
  30402. };
  30403. return SceneSerializer;
  30404. })();
  30405. BABYLON.SceneSerializer = SceneSerializer;
  30406. })(BABYLON || (BABYLON = {}));
  30407. var BABYLON;
  30408. (function (BABYLON) {
  30409. // Unique ID when we import meshes from Babylon to CSG
  30410. var currentCSGMeshId = 0;
  30411. // # class Vertex
  30412. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30413. // one to provide additional features like texture coordinates and vertex
  30414. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30415. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30416. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30417. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30418. // is not used anywhere else.
  30419. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30420. var Vertex = (function () {
  30421. function Vertex(pos, normal, uv) {
  30422. this.pos = pos;
  30423. this.normal = normal;
  30424. this.uv = uv;
  30425. }
  30426. Vertex.prototype.clone = function () {
  30427. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30428. };
  30429. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30430. // orientation of a polygon is flipped.
  30431. Vertex.prototype.flip = function () {
  30432. this.normal = this.normal.scale(-1);
  30433. };
  30434. // Create a new vertex between this vertex and `other` by linearly
  30435. // interpolating all properties using a parameter of `t`. Subclasses should
  30436. // override this to interpolate additional properties.
  30437. Vertex.prototype.interpolate = function (other, t) {
  30438. 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));
  30439. };
  30440. return Vertex;
  30441. })();
  30442. // # class Plane
  30443. // Represents a plane in 3D space.
  30444. var Plane = (function () {
  30445. function Plane(normal, w) {
  30446. this.normal = normal;
  30447. this.w = w;
  30448. }
  30449. Plane.FromPoints = function (a, b, c) {
  30450. var v0 = c.subtract(a);
  30451. var v1 = b.subtract(a);
  30452. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30453. return null;
  30454. }
  30455. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30456. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30457. };
  30458. Plane.prototype.clone = function () {
  30459. return new Plane(this.normal.clone(), this.w);
  30460. };
  30461. Plane.prototype.flip = function () {
  30462. this.normal.scaleInPlace(-1);
  30463. this.w = -this.w;
  30464. };
  30465. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30466. // fragments in the appropriate lists. Coplanar polygons go into either
  30467. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30468. // respect to this plane. Polygons in front or in back of this plane go into
  30469. // either `front` or `back`.
  30470. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30471. var COPLANAR = 0;
  30472. var FRONT = 1;
  30473. var BACK = 2;
  30474. var SPANNING = 3;
  30475. // Classify each point as well as the entire polygon into one of the above
  30476. // four classes.
  30477. var polygonType = 0;
  30478. var types = [];
  30479. var i;
  30480. var t;
  30481. for (i = 0; i < polygon.vertices.length; i++) {
  30482. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30483. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30484. polygonType |= type;
  30485. types.push(type);
  30486. }
  30487. // Put the polygon in the correct list, splitting it when necessary.
  30488. switch (polygonType) {
  30489. case COPLANAR:
  30490. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30491. break;
  30492. case FRONT:
  30493. front.push(polygon);
  30494. break;
  30495. case BACK:
  30496. back.push(polygon);
  30497. break;
  30498. case SPANNING:
  30499. var f = [], b = [];
  30500. for (i = 0; i < polygon.vertices.length; i++) {
  30501. var j = (i + 1) % polygon.vertices.length;
  30502. var ti = types[i], tj = types[j];
  30503. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30504. if (ti !== BACK)
  30505. f.push(vi);
  30506. if (ti !== FRONT)
  30507. b.push(ti !== BACK ? vi.clone() : vi);
  30508. if ((ti | tj) === SPANNING) {
  30509. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30510. var v = vi.interpolate(vj, t);
  30511. f.push(v);
  30512. b.push(v.clone());
  30513. }
  30514. }
  30515. var poly;
  30516. if (f.length >= 3) {
  30517. poly = new Polygon(f, polygon.shared);
  30518. if (poly.plane)
  30519. front.push(poly);
  30520. }
  30521. if (b.length >= 3) {
  30522. poly = new Polygon(b, polygon.shared);
  30523. if (poly.plane)
  30524. back.push(poly);
  30525. }
  30526. break;
  30527. }
  30528. };
  30529. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30530. // point is on the plane.
  30531. Plane.EPSILON = 1e-5;
  30532. return Plane;
  30533. })();
  30534. // # class Polygon
  30535. // Represents a convex polygon. The vertices used to initialize a polygon must
  30536. // be coplanar and form a convex loop.
  30537. //
  30538. // Each convex polygon has a `shared` property, which is shared between all
  30539. // polygons that are clones of each other or were split from the same polygon.
  30540. // This can be used to define per-polygon properties (such as surface color).
  30541. var Polygon = (function () {
  30542. function Polygon(vertices, shared) {
  30543. this.vertices = vertices;
  30544. this.shared = shared;
  30545. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30546. }
  30547. Polygon.prototype.clone = function () {
  30548. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30549. return new Polygon(vertices, this.shared);
  30550. };
  30551. Polygon.prototype.flip = function () {
  30552. this.vertices.reverse().map(function (v) { v.flip(); });
  30553. this.plane.flip();
  30554. };
  30555. return Polygon;
  30556. })();
  30557. // # class Node
  30558. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30559. // by picking a polygon to split along. That polygon (and all other coplanar
  30560. // polygons) are added directly to that node and the other polygons are added to
  30561. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30562. // no distinction between internal and leaf nodes.
  30563. var Node = (function () {
  30564. function Node(polygons) {
  30565. this.plane = null;
  30566. this.front = null;
  30567. this.back = null;
  30568. this.polygons = [];
  30569. if (polygons) {
  30570. this.build(polygons);
  30571. }
  30572. }
  30573. Node.prototype.clone = function () {
  30574. var node = new Node();
  30575. node.plane = this.plane && this.plane.clone();
  30576. node.front = this.front && this.front.clone();
  30577. node.back = this.back && this.back.clone();
  30578. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30579. return node;
  30580. };
  30581. // Convert solid space to empty space and empty space to solid space.
  30582. Node.prototype.invert = function () {
  30583. for (var i = 0; i < this.polygons.length; i++) {
  30584. this.polygons[i].flip();
  30585. }
  30586. if (this.plane) {
  30587. this.plane.flip();
  30588. }
  30589. if (this.front) {
  30590. this.front.invert();
  30591. }
  30592. if (this.back) {
  30593. this.back.invert();
  30594. }
  30595. var temp = this.front;
  30596. this.front = this.back;
  30597. this.back = temp;
  30598. };
  30599. // Recursively remove all polygons in `polygons` that are inside this BSP
  30600. // tree.
  30601. Node.prototype.clipPolygons = function (polygons) {
  30602. if (!this.plane)
  30603. return polygons.slice();
  30604. var front = [], back = [];
  30605. for (var i = 0; i < polygons.length; i++) {
  30606. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30607. }
  30608. if (this.front) {
  30609. front = this.front.clipPolygons(front);
  30610. }
  30611. if (this.back) {
  30612. back = this.back.clipPolygons(back);
  30613. }
  30614. else {
  30615. back = [];
  30616. }
  30617. return front.concat(back);
  30618. };
  30619. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30620. // `bsp`.
  30621. Node.prototype.clipTo = function (bsp) {
  30622. this.polygons = bsp.clipPolygons(this.polygons);
  30623. if (this.front)
  30624. this.front.clipTo(bsp);
  30625. if (this.back)
  30626. this.back.clipTo(bsp);
  30627. };
  30628. // Return a list of all polygons in this BSP tree.
  30629. Node.prototype.allPolygons = function () {
  30630. var polygons = this.polygons.slice();
  30631. if (this.front)
  30632. polygons = polygons.concat(this.front.allPolygons());
  30633. if (this.back)
  30634. polygons = polygons.concat(this.back.allPolygons());
  30635. return polygons;
  30636. };
  30637. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30638. // new polygons are filtered down to the bottom of the tree and become new
  30639. // nodes there. Each set of polygons is partitioned using the first polygon
  30640. // (no heuristic is used to pick a good split).
  30641. Node.prototype.build = function (polygons) {
  30642. if (!polygons.length)
  30643. return;
  30644. if (!this.plane)
  30645. this.plane = polygons[0].plane.clone();
  30646. var front = [], back = [];
  30647. for (var i = 0; i < polygons.length; i++) {
  30648. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30649. }
  30650. if (front.length) {
  30651. if (!this.front)
  30652. this.front = new Node();
  30653. this.front.build(front);
  30654. }
  30655. if (back.length) {
  30656. if (!this.back)
  30657. this.back = new Node();
  30658. this.back.build(back);
  30659. }
  30660. };
  30661. return Node;
  30662. })();
  30663. var CSG = (function () {
  30664. function CSG() {
  30665. this.polygons = new Array();
  30666. }
  30667. // Convert BABYLON.Mesh to BABYLON.CSG
  30668. CSG.FromMesh = function (mesh) {
  30669. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30670. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30671. if (mesh instanceof BABYLON.Mesh) {
  30672. mesh.computeWorldMatrix(true);
  30673. matrix = mesh.getWorldMatrix();
  30674. meshPosition = mesh.position.clone();
  30675. meshRotation = mesh.rotation.clone();
  30676. if (mesh.rotationQuaternion) {
  30677. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30678. }
  30679. meshScaling = mesh.scaling.clone();
  30680. }
  30681. else {
  30682. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30683. }
  30684. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30685. var subMeshes = mesh.subMeshes;
  30686. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30687. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30688. vertices = [];
  30689. for (var j = 0; j < 3; j++) {
  30690. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30691. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30692. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30693. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30694. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30695. vertex = new Vertex(position, normal, uv);
  30696. vertices.push(vertex);
  30697. }
  30698. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30699. // To handle the case of degenerated triangle
  30700. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30701. if (polygon.plane)
  30702. polygons.push(polygon);
  30703. }
  30704. }
  30705. var csg = CSG.FromPolygons(polygons);
  30706. csg.matrix = matrix;
  30707. csg.position = meshPosition;
  30708. csg.rotation = meshRotation;
  30709. csg.scaling = meshScaling;
  30710. csg.rotationQuaternion = meshRotationQuaternion;
  30711. currentCSGMeshId++;
  30712. return csg;
  30713. };
  30714. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30715. CSG.FromPolygons = function (polygons) {
  30716. var csg = new CSG();
  30717. csg.polygons = polygons;
  30718. return csg;
  30719. };
  30720. CSG.prototype.clone = function () {
  30721. var csg = new CSG();
  30722. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30723. csg.copyTransformAttributes(this);
  30724. return csg;
  30725. };
  30726. CSG.prototype.toPolygons = function () {
  30727. return this.polygons;
  30728. };
  30729. CSG.prototype.union = function (csg) {
  30730. var a = new Node(this.clone().polygons);
  30731. var b = new Node(csg.clone().polygons);
  30732. a.clipTo(b);
  30733. b.clipTo(a);
  30734. b.invert();
  30735. b.clipTo(a);
  30736. b.invert();
  30737. a.build(b.allPolygons());
  30738. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30739. };
  30740. CSG.prototype.unionInPlace = function (csg) {
  30741. var a = new Node(this.polygons);
  30742. var b = new Node(csg.polygons);
  30743. a.clipTo(b);
  30744. b.clipTo(a);
  30745. b.invert();
  30746. b.clipTo(a);
  30747. b.invert();
  30748. a.build(b.allPolygons());
  30749. this.polygons = a.allPolygons();
  30750. };
  30751. CSG.prototype.subtract = function (csg) {
  30752. var a = new Node(this.clone().polygons);
  30753. var b = new Node(csg.clone().polygons);
  30754. a.invert();
  30755. a.clipTo(b);
  30756. b.clipTo(a);
  30757. b.invert();
  30758. b.clipTo(a);
  30759. b.invert();
  30760. a.build(b.allPolygons());
  30761. a.invert();
  30762. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30763. };
  30764. CSG.prototype.subtractInPlace = function (csg) {
  30765. var a = new Node(this.polygons);
  30766. var b = new Node(csg.polygons);
  30767. a.invert();
  30768. a.clipTo(b);
  30769. b.clipTo(a);
  30770. b.invert();
  30771. b.clipTo(a);
  30772. b.invert();
  30773. a.build(b.allPolygons());
  30774. a.invert();
  30775. this.polygons = a.allPolygons();
  30776. };
  30777. CSG.prototype.intersect = function (csg) {
  30778. var a = new Node(this.clone().polygons);
  30779. var b = new Node(csg.clone().polygons);
  30780. a.invert();
  30781. b.clipTo(a);
  30782. b.invert();
  30783. a.clipTo(b);
  30784. b.clipTo(a);
  30785. a.build(b.allPolygons());
  30786. a.invert();
  30787. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30788. };
  30789. CSG.prototype.intersectInPlace = function (csg) {
  30790. var a = new Node(this.polygons);
  30791. var b = new Node(csg.polygons);
  30792. a.invert();
  30793. b.clipTo(a);
  30794. b.invert();
  30795. a.clipTo(b);
  30796. b.clipTo(a);
  30797. a.build(b.allPolygons());
  30798. a.invert();
  30799. this.polygons = a.allPolygons();
  30800. };
  30801. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30802. // not modified.
  30803. CSG.prototype.inverse = function () {
  30804. var csg = this.clone();
  30805. csg.inverseInPlace();
  30806. return csg;
  30807. };
  30808. CSG.prototype.inverseInPlace = function () {
  30809. this.polygons.map(function (p) { p.flip(); });
  30810. };
  30811. // This is used to keep meshes transformations so they can be restored
  30812. // when we build back a Babylon Mesh
  30813. // NB : All CSG operations are performed in world coordinates
  30814. CSG.prototype.copyTransformAttributes = function (csg) {
  30815. this.matrix = csg.matrix;
  30816. this.position = csg.position;
  30817. this.rotation = csg.rotation;
  30818. this.scaling = csg.scaling;
  30819. this.rotationQuaternion = csg.rotationQuaternion;
  30820. return this;
  30821. };
  30822. // Build Raw mesh from CSG
  30823. // Coordinates here are in world space
  30824. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30825. var matrix = this.matrix.clone();
  30826. matrix.invert();
  30827. 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;
  30828. if (keepSubMeshes) {
  30829. // Sort Polygons, since subMeshes are indices range
  30830. polygons.sort(function (a, b) {
  30831. if (a.shared.meshId === b.shared.meshId) {
  30832. return a.shared.subMeshId - b.shared.subMeshId;
  30833. }
  30834. else {
  30835. return a.shared.meshId - b.shared.meshId;
  30836. }
  30837. });
  30838. }
  30839. for (var i = 0, il = polygons.length; i < il; i++) {
  30840. polygon = polygons[i];
  30841. // Building SubMeshes
  30842. if (!subMesh_dict[polygon.shared.meshId]) {
  30843. subMesh_dict[polygon.shared.meshId] = {};
  30844. }
  30845. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30846. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30847. indexStart: +Infinity,
  30848. indexEnd: -Infinity,
  30849. materialIndex: polygon.shared.materialIndex
  30850. };
  30851. }
  30852. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30853. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30854. polygonIndices[0] = 0;
  30855. polygonIndices[1] = j - 1;
  30856. polygonIndices[2] = j;
  30857. for (var k = 0; k < 3; k++) {
  30858. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30859. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30860. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30861. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30862. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30863. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30864. // Check if 2 points can be merged
  30865. if (!(typeof vertex_idx !== 'undefined' &&
  30866. normals[vertex_idx * 3] === localNormal.x &&
  30867. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30868. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30869. uvs[vertex_idx * 2] === uv.x &&
  30870. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30871. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30872. uvs.push(uv.x, uv.y);
  30873. normals.push(normal.x, normal.y, normal.z);
  30874. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30875. }
  30876. indices.push(vertex_idx);
  30877. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30878. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30879. currentIndex++;
  30880. }
  30881. }
  30882. }
  30883. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30884. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30885. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30886. mesh.setIndices(indices);
  30887. if (keepSubMeshes) {
  30888. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30889. var materialIndexOffset = 0, materialMaxIndex;
  30890. mesh.subMeshes = new Array();
  30891. for (var m in subMesh_dict) {
  30892. materialMaxIndex = -1;
  30893. for (var sm in subMesh_dict[m]) {
  30894. subMesh_obj = subMesh_dict[m][sm];
  30895. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30896. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30897. }
  30898. materialIndexOffset += ++materialMaxIndex;
  30899. }
  30900. }
  30901. return mesh;
  30902. };
  30903. // Build Mesh from CSG taking material and transforms into account
  30904. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30905. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30906. mesh.material = material;
  30907. mesh.position.copyFrom(this.position);
  30908. mesh.rotation.copyFrom(this.rotation);
  30909. if (this.rotationQuaternion) {
  30910. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30911. }
  30912. mesh.scaling.copyFrom(this.scaling);
  30913. mesh.computeWorldMatrix(true);
  30914. return mesh;
  30915. };
  30916. return CSG;
  30917. })();
  30918. BABYLON.CSG = CSG;
  30919. })(BABYLON || (BABYLON = {}));
  30920. var BABYLON;
  30921. (function (BABYLON) {
  30922. var VRDistortionCorrectionPostProcess = (function (_super) {
  30923. __extends(VRDistortionCorrectionPostProcess, _super);
  30924. //ANY
  30925. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30926. var _this = this;
  30927. _super.call(this, name, "vrDistortionCorrection", [
  30928. 'LensCenter',
  30929. 'Scale',
  30930. 'ScaleIn',
  30931. 'HmdWarpParam'
  30932. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30933. this._isRightEye = isRightEye;
  30934. this._distortionFactors = vrMetrics.distortionK;
  30935. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30936. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30937. this.onSizeChanged = function () {
  30938. _this.aspectRatio = _this.width * .5 / _this.height;
  30939. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30940. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30941. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30942. };
  30943. this.onApply = function (effect) {
  30944. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30945. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30946. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30947. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30948. };
  30949. }
  30950. return VRDistortionCorrectionPostProcess;
  30951. })(BABYLON.PostProcess);
  30952. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30953. })(BABYLON || (BABYLON = {}));
  30954. // Mainly based on these 2 articles :
  30955. // 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
  30956. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30957. var BABYLON;
  30958. (function (BABYLON) {
  30959. (function (JoystickAxis) {
  30960. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30961. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30962. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30963. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30964. var JoystickAxis = BABYLON.JoystickAxis;
  30965. var VirtualJoystick = (function () {
  30966. function VirtualJoystick(leftJoystick) {
  30967. var _this = this;
  30968. if (leftJoystick) {
  30969. this._leftJoystick = true;
  30970. }
  30971. else {
  30972. this._leftJoystick = false;
  30973. }
  30974. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30975. VirtualJoystick._globalJoystickIndex++;
  30976. // By default left & right arrow keys are moving the X
  30977. // and up & down keys are moving the Y
  30978. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30979. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30980. this.reverseLeftRight = false;
  30981. this.reverseUpDown = false;
  30982. // collections of pointers
  30983. this._touches = new BABYLON.SmartCollection();
  30984. this.deltaPosition = BABYLON.Vector3.Zero();
  30985. this._joystickSensibility = 25;
  30986. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30987. this._rotationSpeed = 25;
  30988. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30989. this._rotateOnAxisRelativeToMesh = false;
  30990. this._onResize = function (evt) {
  30991. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30992. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30993. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30994. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30995. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30996. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30997. };
  30998. // injecting a canvas element on top of the canvas 3D game
  30999. if (!VirtualJoystick.vjCanvas) {
  31000. window.addEventListener("resize", this._onResize, false);
  31001. VirtualJoystick.vjCanvas = document.createElement("canvas");
  31002. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31003. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31004. VirtualJoystick.vjCanvas.width = window.innerWidth;
  31005. VirtualJoystick.vjCanvas.height = window.innerHeight;
  31006. VirtualJoystick.vjCanvas.style.width = "100%";
  31007. VirtualJoystick.vjCanvas.style.height = "100%";
  31008. VirtualJoystick.vjCanvas.style.position = "absolute";
  31009. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  31010. VirtualJoystick.vjCanvas.style.top = "0px";
  31011. VirtualJoystick.vjCanvas.style.left = "0px";
  31012. VirtualJoystick.vjCanvas.style.zIndex = "5";
  31013. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  31014. // Support for jQuery PEP polyfill
  31015. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  31016. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  31017. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  31018. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31019. document.body.appendChild(VirtualJoystick.vjCanvas);
  31020. }
  31021. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  31022. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  31023. this.pressed = false;
  31024. // default joystick color
  31025. this._joystickColor = "cyan";
  31026. this._joystickPointerID = -1;
  31027. // current joystick position
  31028. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  31029. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  31030. // origin joystick position
  31031. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  31032. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  31033. this._onPointerDownHandlerRef = function (evt) {
  31034. _this._onPointerDown(evt);
  31035. };
  31036. this._onPointerMoveHandlerRef = function (evt) {
  31037. _this._onPointerMove(evt);
  31038. };
  31039. this._onPointerOutHandlerRef = function (evt) {
  31040. _this._onPointerUp(evt);
  31041. };
  31042. this._onPointerUpHandlerRef = function (evt) {
  31043. _this._onPointerUp(evt);
  31044. };
  31045. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  31046. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  31047. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  31048. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  31049. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  31050. evt.preventDefault(); // Disables system menu
  31051. }, false);
  31052. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31053. }
  31054. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  31055. this._joystickSensibility = newJoystickSensibility;
  31056. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31057. };
  31058. VirtualJoystick.prototype._onPointerDown = function (e) {
  31059. var positionOnScreenCondition;
  31060. e.preventDefault();
  31061. if (this._leftJoystick === true) {
  31062. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  31063. }
  31064. else {
  31065. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  31066. }
  31067. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  31068. // First contact will be dedicated to the virtual joystick
  31069. this._joystickPointerID = e.pointerId;
  31070. this._joystickPointerStartPos.x = e.clientX;
  31071. this._joystickPointerStartPos.y = e.clientY;
  31072. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  31073. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  31074. this._deltaJoystickVector.x = 0;
  31075. this._deltaJoystickVector.y = 0;
  31076. this.pressed = true;
  31077. this._touches.add(e.pointerId.toString(), e);
  31078. }
  31079. else {
  31080. // You can only trigger the action buttons with a joystick declared
  31081. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  31082. this._action();
  31083. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  31084. }
  31085. }
  31086. };
  31087. VirtualJoystick.prototype._onPointerMove = function (e) {
  31088. // If the current pointer is the one associated to the joystick (first touch contact)
  31089. if (this._joystickPointerID == e.pointerId) {
  31090. this._joystickPointerPos.x = e.clientX;
  31091. this._joystickPointerPos.y = e.clientY;
  31092. this._deltaJoystickVector = this._joystickPointerPos.clone();
  31093. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  31094. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  31095. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  31096. switch (this._axisTargetedByLeftAndRight) {
  31097. case JoystickAxis.X:
  31098. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  31099. break;
  31100. case JoystickAxis.Y:
  31101. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  31102. break;
  31103. case JoystickAxis.Z:
  31104. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  31105. break;
  31106. }
  31107. var directionUpDown = this.reverseUpDown ? 1 : -1;
  31108. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  31109. switch (this._axisTargetedByUpAndDown) {
  31110. case JoystickAxis.X:
  31111. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  31112. break;
  31113. case JoystickAxis.Y:
  31114. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  31115. break;
  31116. case JoystickAxis.Z:
  31117. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  31118. break;
  31119. }
  31120. }
  31121. else {
  31122. if (this._touches.item(e.pointerId.toString())) {
  31123. this._touches.item(e.pointerId.toString()).x = e.clientX;
  31124. this._touches.item(e.pointerId.toString()).y = e.clientY;
  31125. }
  31126. }
  31127. };
  31128. VirtualJoystick.prototype._onPointerUp = function (e) {
  31129. if (this._joystickPointerID == e.pointerId) {
  31130. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  31131. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  31132. this._joystickPointerID = -1;
  31133. this.pressed = false;
  31134. }
  31135. else {
  31136. var touch = this._touches.item(e.pointerId.toString());
  31137. if (touch) {
  31138. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31139. }
  31140. }
  31141. this._deltaJoystickVector.x = 0;
  31142. this._deltaJoystickVector.y = 0;
  31143. this._touches.remove(e.pointerId.toString());
  31144. };
  31145. /**
  31146. * Change the color of the virtual joystick
  31147. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  31148. */
  31149. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  31150. this._joystickColor = newColor;
  31151. };
  31152. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  31153. this._action = action;
  31154. };
  31155. // Define which axis you'd like to control for left & right
  31156. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  31157. switch (axis) {
  31158. case JoystickAxis.X:
  31159. case JoystickAxis.Y:
  31160. case JoystickAxis.Z:
  31161. this._axisTargetedByLeftAndRight = axis;
  31162. break;
  31163. default:
  31164. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31165. break;
  31166. }
  31167. };
  31168. // Define which axis you'd like to control for up & down
  31169. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  31170. switch (axis) {
  31171. case JoystickAxis.X:
  31172. case JoystickAxis.Y:
  31173. case JoystickAxis.Z:
  31174. this._axisTargetedByUpAndDown = axis;
  31175. break;
  31176. default:
  31177. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31178. break;
  31179. }
  31180. };
  31181. VirtualJoystick.prototype._clearCanvas = function () {
  31182. if (this._leftJoystick) {
  31183. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  31184. }
  31185. else {
  31186. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  31187. }
  31188. };
  31189. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  31190. var _this = this;
  31191. if (this.pressed) {
  31192. this._touches.forEach(function (touch) {
  31193. if (touch.pointerId === _this._joystickPointerID) {
  31194. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  31195. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  31196. VirtualJoystick.vjCanvasContext.beginPath();
  31197. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31198. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31199. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31200. VirtualJoystick.vjCanvasContext.stroke();
  31201. VirtualJoystick.vjCanvasContext.closePath();
  31202. VirtualJoystick.vjCanvasContext.beginPath();
  31203. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31204. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31205. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31206. VirtualJoystick.vjCanvasContext.stroke();
  31207. VirtualJoystick.vjCanvasContext.closePath();
  31208. VirtualJoystick.vjCanvasContext.beginPath();
  31209. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31210. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31211. VirtualJoystick.vjCanvasContext.stroke();
  31212. VirtualJoystick.vjCanvasContext.closePath();
  31213. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31214. }
  31215. else {
  31216. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31217. VirtualJoystick.vjCanvasContext.beginPath();
  31218. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31219. VirtualJoystick.vjCanvasContext.beginPath();
  31220. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31221. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31222. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31223. VirtualJoystick.vjCanvasContext.stroke();
  31224. VirtualJoystick.vjCanvasContext.closePath();
  31225. touch.prevX = touch.x;
  31226. touch.prevY = touch.y;
  31227. }
  31228. ;
  31229. });
  31230. }
  31231. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31232. };
  31233. VirtualJoystick.prototype.releaseCanvas = function () {
  31234. if (VirtualJoystick.vjCanvas) {
  31235. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31236. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31237. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31238. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31239. window.removeEventListener("resize", this._onResize);
  31240. document.body.removeChild(VirtualJoystick.vjCanvas);
  31241. VirtualJoystick.vjCanvas = null;
  31242. }
  31243. };
  31244. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31245. VirtualJoystick._globalJoystickIndex = 0;
  31246. return VirtualJoystick;
  31247. })();
  31248. BABYLON.VirtualJoystick = VirtualJoystick;
  31249. })(BABYLON || (BABYLON = {}));
  31250. var BABYLON;
  31251. (function (BABYLON) {
  31252. // We're mainly based on the logic defined into the FreeCamera code
  31253. var VirtualJoysticksCamera = (function (_super) {
  31254. __extends(VirtualJoysticksCamera, _super);
  31255. function VirtualJoysticksCamera(name, position, scene) {
  31256. _super.call(this, name, position, scene);
  31257. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31258. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31259. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31260. this._leftjoystick.setJoystickSensibility(0.15);
  31261. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31262. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31263. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31264. this._rightjoystick.reverseUpDown = true;
  31265. this._rightjoystick.setJoystickSensibility(0.05);
  31266. this._rightjoystick.setJoystickColor("yellow");
  31267. }
  31268. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31269. return this._leftjoystick;
  31270. };
  31271. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31272. return this._rightjoystick;
  31273. };
  31274. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31275. var speed = this._computeLocalCameraSpeed() * 50;
  31276. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31277. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31278. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31279. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31280. if (!this._leftjoystick.pressed) {
  31281. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31282. }
  31283. if (!this._rightjoystick.pressed) {
  31284. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31285. }
  31286. _super.prototype._checkInputs.call(this);
  31287. };
  31288. VirtualJoysticksCamera.prototype.dispose = function () {
  31289. this._leftjoystick.releaseCanvas();
  31290. _super.prototype.dispose.call(this);
  31291. };
  31292. return VirtualJoysticksCamera;
  31293. })(BABYLON.FreeCamera);
  31294. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31295. })(BABYLON || (BABYLON = {}));
  31296. var BABYLON;
  31297. (function (BABYLON) {
  31298. var AnaglyphPostProcess = (function (_super) {
  31299. __extends(AnaglyphPostProcess, _super);
  31300. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31301. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31302. }
  31303. return AnaglyphPostProcess;
  31304. })(BABYLON.PostProcess);
  31305. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31306. })(BABYLON || (BABYLON = {}));
  31307. var BABYLON;
  31308. (function (BABYLON) {
  31309. var OutlineRenderer = (function () {
  31310. function OutlineRenderer(scene) {
  31311. this._scene = scene;
  31312. }
  31313. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31314. var _this = this;
  31315. if (useOverlay === void 0) { useOverlay = false; }
  31316. var scene = this._scene;
  31317. var engine = this._scene.getEngine();
  31318. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31319. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31320. return;
  31321. }
  31322. var mesh = subMesh.getRenderingMesh();
  31323. var material = subMesh.getMaterial();
  31324. engine.enableEffect(this._effect);
  31325. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31326. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31327. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31328. // Bones
  31329. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31330. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31331. }
  31332. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31333. // Alpha test
  31334. if (material && material.needAlphaTesting()) {
  31335. var alphaTexture = material.getAlphaTestTexture();
  31336. this._effect.setTexture("diffuseSampler", alphaTexture);
  31337. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31338. }
  31339. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31340. };
  31341. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31342. var defines = [];
  31343. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31344. var mesh = subMesh.getMesh();
  31345. var material = subMesh.getMaterial();
  31346. // Alpha test
  31347. if (material && material.needAlphaTesting()) {
  31348. defines.push("#define ALPHATEST");
  31349. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31350. attribs.push(BABYLON.VertexBuffer.UVKind);
  31351. defines.push("#define UV1");
  31352. }
  31353. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31354. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31355. defines.push("#define UV2");
  31356. }
  31357. }
  31358. // Bones
  31359. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31360. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31361. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31362. if (mesh.numBoneInfluencers > 4) {
  31363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31365. }
  31366. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31367. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31368. }
  31369. else {
  31370. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31371. }
  31372. // Instances
  31373. if (useInstances) {
  31374. defines.push("#define INSTANCES");
  31375. attribs.push("world0");
  31376. attribs.push("world1");
  31377. attribs.push("world2");
  31378. attribs.push("world3");
  31379. }
  31380. // Get correct effect
  31381. var join = defines.join("\n");
  31382. if (this._cachedDefines !== join) {
  31383. this._cachedDefines = join;
  31384. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31385. }
  31386. return this._effect.isReady();
  31387. };
  31388. return OutlineRenderer;
  31389. })();
  31390. BABYLON.OutlineRenderer = OutlineRenderer;
  31391. })(BABYLON || (BABYLON = {}));
  31392. var BABYLON;
  31393. (function (BABYLON) {
  31394. var MeshAssetTask = (function () {
  31395. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31396. this.name = name;
  31397. this.meshesNames = meshesNames;
  31398. this.rootUrl = rootUrl;
  31399. this.sceneFilename = sceneFilename;
  31400. this.isCompleted = false;
  31401. }
  31402. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31403. var _this = this;
  31404. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31405. _this.loadedMeshes = meshes;
  31406. _this.loadedParticleSystems = particleSystems;
  31407. _this.loadedSkeletons = skeletons;
  31408. _this.isCompleted = true;
  31409. if (_this.onSuccess) {
  31410. _this.onSuccess(_this);
  31411. }
  31412. onSuccess();
  31413. }, null, function () {
  31414. if (_this.onError) {
  31415. _this.onError(_this);
  31416. }
  31417. onError();
  31418. });
  31419. };
  31420. return MeshAssetTask;
  31421. })();
  31422. BABYLON.MeshAssetTask = MeshAssetTask;
  31423. var TextFileAssetTask = (function () {
  31424. function TextFileAssetTask(name, url) {
  31425. this.name = name;
  31426. this.url = url;
  31427. this.isCompleted = false;
  31428. }
  31429. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31430. var _this = this;
  31431. BABYLON.Tools.LoadFile(this.url, function (data) {
  31432. _this.text = data;
  31433. _this.isCompleted = true;
  31434. if (_this.onSuccess) {
  31435. _this.onSuccess(_this);
  31436. }
  31437. onSuccess();
  31438. }, null, scene.database, false, function () {
  31439. if (_this.onError) {
  31440. _this.onError(_this);
  31441. }
  31442. onError();
  31443. });
  31444. };
  31445. return TextFileAssetTask;
  31446. })();
  31447. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31448. var BinaryFileAssetTask = (function () {
  31449. function BinaryFileAssetTask(name, url) {
  31450. this.name = name;
  31451. this.url = url;
  31452. this.isCompleted = false;
  31453. }
  31454. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31455. var _this = this;
  31456. BABYLON.Tools.LoadFile(this.url, function (data) {
  31457. _this.data = data;
  31458. _this.isCompleted = true;
  31459. if (_this.onSuccess) {
  31460. _this.onSuccess(_this);
  31461. }
  31462. onSuccess();
  31463. }, null, scene.database, true, function () {
  31464. if (_this.onError) {
  31465. _this.onError(_this);
  31466. }
  31467. onError();
  31468. });
  31469. };
  31470. return BinaryFileAssetTask;
  31471. })();
  31472. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31473. var ImageAssetTask = (function () {
  31474. function ImageAssetTask(name, url) {
  31475. this.name = name;
  31476. this.url = url;
  31477. this.isCompleted = false;
  31478. }
  31479. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31480. var _this = this;
  31481. var img = new Image();
  31482. img.onload = function () {
  31483. _this.image = img;
  31484. _this.isCompleted = true;
  31485. if (_this.onSuccess) {
  31486. _this.onSuccess(_this);
  31487. }
  31488. onSuccess();
  31489. };
  31490. img.onerror = function () {
  31491. if (_this.onError) {
  31492. _this.onError(_this);
  31493. }
  31494. onError();
  31495. };
  31496. img.src = this.url;
  31497. };
  31498. return ImageAssetTask;
  31499. })();
  31500. BABYLON.ImageAssetTask = ImageAssetTask;
  31501. var TextureAssetTask = (function () {
  31502. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31504. this.name = name;
  31505. this.url = url;
  31506. this.noMipmap = noMipmap;
  31507. this.invertY = invertY;
  31508. this.samplingMode = samplingMode;
  31509. this.isCompleted = false;
  31510. }
  31511. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31512. var _this = this;
  31513. var onload = function () {
  31514. _this.isCompleted = true;
  31515. if (_this.onSuccess) {
  31516. _this.onSuccess(_this);
  31517. }
  31518. onSuccess();
  31519. };
  31520. var onerror = function () {
  31521. if (_this.onError) {
  31522. _this.onError(_this);
  31523. }
  31524. onError();
  31525. };
  31526. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31527. };
  31528. return TextureAssetTask;
  31529. })();
  31530. BABYLON.TextureAssetTask = TextureAssetTask;
  31531. var AssetsManager = (function () {
  31532. function AssetsManager(scene) {
  31533. this._tasks = new Array();
  31534. this._waitingTasksCount = 0;
  31535. this.useDefaultLoadingScreen = true;
  31536. this._scene = scene;
  31537. }
  31538. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31539. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31540. this._tasks.push(task);
  31541. return task;
  31542. };
  31543. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31544. var task = new TextFileAssetTask(taskName, url);
  31545. this._tasks.push(task);
  31546. return task;
  31547. };
  31548. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31549. var task = new BinaryFileAssetTask(taskName, url);
  31550. this._tasks.push(task);
  31551. return task;
  31552. };
  31553. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31554. var task = new ImageAssetTask(taskName, url);
  31555. this._tasks.push(task);
  31556. return task;
  31557. };
  31558. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31559. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31560. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31561. this._tasks.push(task);
  31562. return task;
  31563. };
  31564. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31565. this._waitingTasksCount--;
  31566. if (this._waitingTasksCount === 0) {
  31567. if (this.onFinish) {
  31568. this.onFinish(this._tasks);
  31569. }
  31570. this._scene.getEngine().hideLoadingUI();
  31571. }
  31572. };
  31573. AssetsManager.prototype._runTask = function (task) {
  31574. var _this = this;
  31575. task.run(this._scene, function () {
  31576. if (_this.onTaskSuccess) {
  31577. _this.onTaskSuccess(task);
  31578. }
  31579. _this._decreaseWaitingTasksCount();
  31580. }, function () {
  31581. if (_this.onTaskError) {
  31582. _this.onTaskError(task);
  31583. }
  31584. _this._decreaseWaitingTasksCount();
  31585. });
  31586. };
  31587. AssetsManager.prototype.reset = function () {
  31588. this._tasks = new Array();
  31589. return this;
  31590. };
  31591. AssetsManager.prototype.load = function () {
  31592. this._waitingTasksCount = this._tasks.length;
  31593. if (this._waitingTasksCount === 0) {
  31594. if (this.onFinish) {
  31595. this.onFinish(this._tasks);
  31596. }
  31597. return this;
  31598. }
  31599. if (this.useDefaultLoadingScreen) {
  31600. this._scene.getEngine().displayLoadingUI();
  31601. }
  31602. for (var index = 0; index < this._tasks.length; index++) {
  31603. var task = this._tasks[index];
  31604. this._runTask(task);
  31605. }
  31606. return this;
  31607. };
  31608. return AssetsManager;
  31609. })();
  31610. BABYLON.AssetsManager = AssetsManager;
  31611. })(BABYLON || (BABYLON = {}));
  31612. var BABYLON;
  31613. (function (BABYLON) {
  31614. var VRDeviceOrientationFreeCamera = (function (_super) {
  31615. __extends(VRDeviceOrientationFreeCamera, _super);
  31616. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31617. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31618. _super.call(this, name, position, scene);
  31619. this._alpha = 0;
  31620. this._beta = 0;
  31621. this._gamma = 0;
  31622. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31623. metrics.compensateDistortion = compensateDistortion;
  31624. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31625. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31626. }
  31627. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31628. this._alpha = +evt.alpha | 0;
  31629. this._beta = +evt.beta | 0;
  31630. this._gamma = +evt.gamma | 0;
  31631. if (this._gamma < 0) {
  31632. this._gamma = 90 + this._gamma;
  31633. }
  31634. else {
  31635. // Incline it in the correct angle.
  31636. this._gamma = 270 - this._gamma;
  31637. }
  31638. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31639. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31640. this.rotation.z = this._beta / 180.0 * Math.PI;
  31641. };
  31642. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31643. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31644. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31645. };
  31646. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31647. _super.prototype.detachControl.call(this, element);
  31648. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31649. };
  31650. return VRDeviceOrientationFreeCamera;
  31651. })(BABYLON.FreeCamera);
  31652. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31653. })(BABYLON || (BABYLON = {}));
  31654. var BABYLON;
  31655. (function (BABYLON) {
  31656. var WebVRFreeCamera = (function (_super) {
  31657. __extends(WebVRFreeCamera, _super);
  31658. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31659. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31660. _super.call(this, name, position, scene);
  31661. this._hmdDevice = null;
  31662. this._sensorDevice = null;
  31663. this._cacheState = null;
  31664. this._cacheQuaternion = new BABYLON.Quaternion();
  31665. this._cacheRotation = BABYLON.Vector3.Zero();
  31666. this._vrEnabled = false;
  31667. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31668. metrics.compensateDistortion = compensateDistortion;
  31669. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31670. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31671. }
  31672. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31673. var size = devices.length;
  31674. var i = 0;
  31675. // Reset devices.
  31676. this._sensorDevice = null;
  31677. this._hmdDevice = null;
  31678. // Search for a HmdDevice.
  31679. while (i < size && this._hmdDevice === null) {
  31680. if (devices[i] instanceof HMDVRDevice) {
  31681. this._hmdDevice = devices[i];
  31682. }
  31683. i++;
  31684. }
  31685. i = 0;
  31686. while (i < size && this._sensorDevice === null) {
  31687. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31688. this._sensorDevice = devices[i];
  31689. }
  31690. i++;
  31691. }
  31692. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31693. };
  31694. WebVRFreeCamera.prototype._checkInputs = function () {
  31695. if (this._vrEnabled) {
  31696. this._cacheState = this._sensorDevice.getState();
  31697. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31698. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31699. this.rotation.x = -this._cacheRotation.z;
  31700. this.rotation.y = -this._cacheRotation.y;
  31701. this.rotation.z = this._cacheRotation.x;
  31702. }
  31703. _super.prototype._checkInputs.call(this);
  31704. };
  31705. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31706. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31707. if (navigator.getVRDevices) {
  31708. navigator.getVRDevices().then(this._getWebVRDevices);
  31709. }
  31710. else if (navigator.mozGetVRDevices) {
  31711. navigator.mozGetVRDevices(this._getWebVRDevices);
  31712. }
  31713. };
  31714. WebVRFreeCamera.prototype.detachControl = function (element) {
  31715. _super.prototype.detachControl.call(this, element);
  31716. this._vrEnabled = false;
  31717. };
  31718. return WebVRFreeCamera;
  31719. })(BABYLON.FreeCamera);
  31720. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31721. })(BABYLON || (BABYLON = {}));
  31722. var BABYLON;
  31723. (function (BABYLON) {
  31724. // Standard optimizations
  31725. var SceneOptimization = (function () {
  31726. function SceneOptimization(priority) {
  31727. if (priority === void 0) { priority = 0; }
  31728. this.priority = priority;
  31729. this.apply = function (scene) {
  31730. return true; // Return true if everything that can be done was applied
  31731. };
  31732. }
  31733. return SceneOptimization;
  31734. })();
  31735. BABYLON.SceneOptimization = SceneOptimization;
  31736. var TextureOptimization = (function (_super) {
  31737. __extends(TextureOptimization, _super);
  31738. function TextureOptimization(priority, maximumSize) {
  31739. var _this = this;
  31740. if (priority === void 0) { priority = 0; }
  31741. if (maximumSize === void 0) { maximumSize = 1024; }
  31742. _super.call(this, priority);
  31743. this.priority = priority;
  31744. this.maximumSize = maximumSize;
  31745. this.apply = function (scene) {
  31746. var allDone = true;
  31747. for (var index = 0; index < scene.textures.length; index++) {
  31748. var texture = scene.textures[index];
  31749. if (!texture.canRescale) {
  31750. continue;
  31751. }
  31752. var currentSize = texture.getSize();
  31753. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31754. if (maxDimension > _this.maximumSize) {
  31755. texture.scale(0.5);
  31756. allDone = false;
  31757. }
  31758. }
  31759. return allDone;
  31760. };
  31761. }
  31762. return TextureOptimization;
  31763. })(SceneOptimization);
  31764. BABYLON.TextureOptimization = TextureOptimization;
  31765. var HardwareScalingOptimization = (function (_super) {
  31766. __extends(HardwareScalingOptimization, _super);
  31767. function HardwareScalingOptimization(priority, maximumScale) {
  31768. var _this = this;
  31769. if (priority === void 0) { priority = 0; }
  31770. if (maximumScale === void 0) { maximumScale = 2; }
  31771. _super.call(this, priority);
  31772. this.priority = priority;
  31773. this.maximumScale = maximumScale;
  31774. this._currentScale = 1;
  31775. this.apply = function (scene) {
  31776. _this._currentScale++;
  31777. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31778. return _this._currentScale >= _this.maximumScale;
  31779. };
  31780. }
  31781. return HardwareScalingOptimization;
  31782. })(SceneOptimization);
  31783. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31784. var ShadowsOptimization = (function (_super) {
  31785. __extends(ShadowsOptimization, _super);
  31786. function ShadowsOptimization() {
  31787. _super.apply(this, arguments);
  31788. this.apply = function (scene) {
  31789. scene.shadowsEnabled = false;
  31790. return true;
  31791. };
  31792. }
  31793. return ShadowsOptimization;
  31794. })(SceneOptimization);
  31795. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31796. var PostProcessesOptimization = (function (_super) {
  31797. __extends(PostProcessesOptimization, _super);
  31798. function PostProcessesOptimization() {
  31799. _super.apply(this, arguments);
  31800. this.apply = function (scene) {
  31801. scene.postProcessesEnabled = false;
  31802. return true;
  31803. };
  31804. }
  31805. return PostProcessesOptimization;
  31806. })(SceneOptimization);
  31807. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31808. var LensFlaresOptimization = (function (_super) {
  31809. __extends(LensFlaresOptimization, _super);
  31810. function LensFlaresOptimization() {
  31811. _super.apply(this, arguments);
  31812. this.apply = function (scene) {
  31813. scene.lensFlaresEnabled = false;
  31814. return true;
  31815. };
  31816. }
  31817. return LensFlaresOptimization;
  31818. })(SceneOptimization);
  31819. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31820. var ParticlesOptimization = (function (_super) {
  31821. __extends(ParticlesOptimization, _super);
  31822. function ParticlesOptimization() {
  31823. _super.apply(this, arguments);
  31824. this.apply = function (scene) {
  31825. scene.particlesEnabled = false;
  31826. return true;
  31827. };
  31828. }
  31829. return ParticlesOptimization;
  31830. })(SceneOptimization);
  31831. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31832. var RenderTargetsOptimization = (function (_super) {
  31833. __extends(RenderTargetsOptimization, _super);
  31834. function RenderTargetsOptimization() {
  31835. _super.apply(this, arguments);
  31836. this.apply = function (scene) {
  31837. scene.renderTargetsEnabled = false;
  31838. return true;
  31839. };
  31840. }
  31841. return RenderTargetsOptimization;
  31842. })(SceneOptimization);
  31843. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31844. var MergeMeshesOptimization = (function (_super) {
  31845. __extends(MergeMeshesOptimization, _super);
  31846. function MergeMeshesOptimization() {
  31847. var _this = this;
  31848. _super.apply(this, arguments);
  31849. this._canBeMerged = function (abstractMesh) {
  31850. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31851. return false;
  31852. }
  31853. var mesh = abstractMesh;
  31854. if (!mesh.isVisible || !mesh.isEnabled()) {
  31855. return false;
  31856. }
  31857. if (mesh.instances.length > 0) {
  31858. return false;
  31859. }
  31860. if (mesh.skeleton || mesh.hasLODLevels) {
  31861. return false;
  31862. }
  31863. if (mesh.parent) {
  31864. return false;
  31865. }
  31866. return true;
  31867. };
  31868. this.apply = function (scene, updateSelectionTree) {
  31869. var globalPool = scene.meshes.slice(0);
  31870. var globalLength = globalPool.length;
  31871. for (var index = 0; index < globalLength; index++) {
  31872. var currentPool = new Array();
  31873. var current = globalPool[index];
  31874. // Checks
  31875. if (!_this._canBeMerged(current)) {
  31876. continue;
  31877. }
  31878. currentPool.push(current);
  31879. // Find compatible meshes
  31880. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31881. var otherMesh = globalPool[subIndex];
  31882. if (!_this._canBeMerged(otherMesh)) {
  31883. continue;
  31884. }
  31885. if (otherMesh.material !== current.material) {
  31886. continue;
  31887. }
  31888. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31889. continue;
  31890. }
  31891. currentPool.push(otherMesh);
  31892. globalLength--;
  31893. globalPool.splice(subIndex, 1);
  31894. subIndex--;
  31895. }
  31896. if (currentPool.length < 2) {
  31897. continue;
  31898. }
  31899. // Merge meshes
  31900. BABYLON.Mesh.MergeMeshes(currentPool);
  31901. }
  31902. if (updateSelectionTree != undefined) {
  31903. if (updateSelectionTree) {
  31904. scene.createOrUpdateSelectionOctree();
  31905. }
  31906. }
  31907. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31908. scene.createOrUpdateSelectionOctree();
  31909. }
  31910. return true;
  31911. };
  31912. }
  31913. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31914. get: function () {
  31915. return MergeMeshesOptimization._UpdateSelectionTree;
  31916. },
  31917. set: function (value) {
  31918. MergeMeshesOptimization._UpdateSelectionTree = value;
  31919. },
  31920. enumerable: true,
  31921. configurable: true
  31922. });
  31923. MergeMeshesOptimization._UpdateSelectionTree = false;
  31924. return MergeMeshesOptimization;
  31925. })(SceneOptimization);
  31926. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31927. // Options
  31928. var SceneOptimizerOptions = (function () {
  31929. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31930. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31931. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31932. this.targetFrameRate = targetFrameRate;
  31933. this.trackerDuration = trackerDuration;
  31934. this.optimizations = new Array();
  31935. }
  31936. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31937. var result = new SceneOptimizerOptions(targetFrameRate);
  31938. var priority = 0;
  31939. result.optimizations.push(new MergeMeshesOptimization(priority));
  31940. result.optimizations.push(new ShadowsOptimization(priority));
  31941. result.optimizations.push(new LensFlaresOptimization(priority));
  31942. // Next priority
  31943. priority++;
  31944. result.optimizations.push(new PostProcessesOptimization(priority));
  31945. result.optimizations.push(new ParticlesOptimization(priority));
  31946. // Next priority
  31947. priority++;
  31948. result.optimizations.push(new TextureOptimization(priority, 1024));
  31949. return result;
  31950. };
  31951. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31952. var result = new SceneOptimizerOptions(targetFrameRate);
  31953. var priority = 0;
  31954. result.optimizations.push(new MergeMeshesOptimization(priority));
  31955. result.optimizations.push(new ShadowsOptimization(priority));
  31956. result.optimizations.push(new LensFlaresOptimization(priority));
  31957. // Next priority
  31958. priority++;
  31959. result.optimizations.push(new PostProcessesOptimization(priority));
  31960. result.optimizations.push(new ParticlesOptimization(priority));
  31961. // Next priority
  31962. priority++;
  31963. result.optimizations.push(new TextureOptimization(priority, 512));
  31964. // Next priority
  31965. priority++;
  31966. result.optimizations.push(new RenderTargetsOptimization(priority));
  31967. // Next priority
  31968. priority++;
  31969. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31970. return result;
  31971. };
  31972. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31973. var result = new SceneOptimizerOptions(targetFrameRate);
  31974. var priority = 0;
  31975. result.optimizations.push(new MergeMeshesOptimization(priority));
  31976. result.optimizations.push(new ShadowsOptimization(priority));
  31977. result.optimizations.push(new LensFlaresOptimization(priority));
  31978. // Next priority
  31979. priority++;
  31980. result.optimizations.push(new PostProcessesOptimization(priority));
  31981. result.optimizations.push(new ParticlesOptimization(priority));
  31982. // Next priority
  31983. priority++;
  31984. result.optimizations.push(new TextureOptimization(priority, 256));
  31985. // Next priority
  31986. priority++;
  31987. result.optimizations.push(new RenderTargetsOptimization(priority));
  31988. // Next priority
  31989. priority++;
  31990. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31991. return result;
  31992. };
  31993. return SceneOptimizerOptions;
  31994. })();
  31995. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31996. // Scene optimizer tool
  31997. var SceneOptimizer = (function () {
  31998. function SceneOptimizer() {
  31999. }
  32000. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  32001. // TODO: add an epsilon
  32002. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  32003. if (onSuccess) {
  32004. onSuccess();
  32005. }
  32006. return;
  32007. }
  32008. // Apply current level of optimizations
  32009. var allDone = true;
  32010. var noOptimizationApplied = true;
  32011. for (var index = 0; index < options.optimizations.length; index++) {
  32012. var optimization = options.optimizations[index];
  32013. if (optimization.priority === currentPriorityLevel) {
  32014. noOptimizationApplied = false;
  32015. allDone = allDone && optimization.apply(scene);
  32016. }
  32017. }
  32018. // If no optimization was applied, this is a failure :(
  32019. if (noOptimizationApplied) {
  32020. if (onFailure) {
  32021. onFailure();
  32022. }
  32023. return;
  32024. }
  32025. // If all optimizations were done, move to next level
  32026. if (allDone) {
  32027. currentPriorityLevel++;
  32028. }
  32029. // Let's the system running for a specific amount of time before checking FPS
  32030. scene.executeWhenReady(function () {
  32031. setTimeout(function () {
  32032. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  32033. }, options.trackerDuration);
  32034. });
  32035. };
  32036. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  32037. if (!options) {
  32038. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  32039. }
  32040. // Let's the system running for a specific amount of time before checking FPS
  32041. scene.executeWhenReady(function () {
  32042. setTimeout(function () {
  32043. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  32044. }, options.trackerDuration);
  32045. });
  32046. };
  32047. return SceneOptimizer;
  32048. })();
  32049. BABYLON.SceneOptimizer = SceneOptimizer;
  32050. })(BABYLON || (BABYLON = {}));
  32051. var BABYLON;
  32052. (function (BABYLON) {
  32053. var Internals;
  32054. (function (Internals) {
  32055. var MeshLODLevel = (function () {
  32056. function MeshLODLevel(distance, mesh) {
  32057. this.distance = distance;
  32058. this.mesh = mesh;
  32059. }
  32060. return MeshLODLevel;
  32061. })();
  32062. Internals.MeshLODLevel = MeshLODLevel;
  32063. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32064. })(BABYLON || (BABYLON = {}));
  32065. var BABYLON;
  32066. (function (BABYLON) {
  32067. var RawTexture = (function (_super) {
  32068. __extends(RawTexture, _super);
  32069. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  32070. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32071. if (invertY === void 0) { invertY = false; }
  32072. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32073. _super.call(this, null, scene, !generateMipMaps, invertY);
  32074. this.format = format;
  32075. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  32076. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32077. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32078. }
  32079. RawTexture.prototype.update = function (data) {
  32080. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  32081. };
  32082. // Statics
  32083. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32084. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32085. if (invertY === void 0) { invertY = false; }
  32086. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32087. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  32088. };
  32089. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32090. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32091. if (invertY === void 0) { invertY = false; }
  32092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32093. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32094. };
  32095. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32096. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32097. if (invertY === void 0) { invertY = false; }
  32098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32099. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32100. };
  32101. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32102. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32103. if (invertY === void 0) { invertY = false; }
  32104. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32105. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32106. };
  32107. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32108. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32109. if (invertY === void 0) { invertY = false; }
  32110. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32111. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32112. };
  32113. return RawTexture;
  32114. })(BABYLON.Texture);
  32115. BABYLON.RawTexture = RawTexture;
  32116. })(BABYLON || (BABYLON = {}));
  32117. var BABYLON;
  32118. (function (BABYLON) {
  32119. var IndexedVector2 = (function (_super) {
  32120. __extends(IndexedVector2, _super);
  32121. function IndexedVector2(original, index) {
  32122. _super.call(this, original.x, original.y);
  32123. this.index = index;
  32124. }
  32125. return IndexedVector2;
  32126. })(BABYLON.Vector2);
  32127. var PolygonPoints = (function () {
  32128. function PolygonPoints() {
  32129. this.elements = new Array();
  32130. }
  32131. PolygonPoints.prototype.add = function (originalPoints) {
  32132. var _this = this;
  32133. var result = new Array();
  32134. originalPoints.forEach(function (point) {
  32135. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  32136. var newPoint = new IndexedVector2(point, _this.elements.length);
  32137. result.push(newPoint);
  32138. _this.elements.push(newPoint);
  32139. }
  32140. });
  32141. return result;
  32142. };
  32143. PolygonPoints.prototype.computeBounds = function () {
  32144. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32145. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32146. this.elements.forEach(function (point) {
  32147. // x
  32148. if (point.x < lmin.x) {
  32149. lmin.x = point.x;
  32150. }
  32151. else if (point.x > lmax.x) {
  32152. lmax.x = point.x;
  32153. }
  32154. // y
  32155. if (point.y < lmin.y) {
  32156. lmin.y = point.y;
  32157. }
  32158. else if (point.y > lmax.y) {
  32159. lmax.y = point.y;
  32160. }
  32161. });
  32162. return {
  32163. min: lmin,
  32164. max: lmax,
  32165. width: lmax.x - lmin.x,
  32166. height: lmax.y - lmin.y
  32167. };
  32168. };
  32169. return PolygonPoints;
  32170. })();
  32171. var Polygon = (function () {
  32172. function Polygon() {
  32173. }
  32174. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  32175. return [
  32176. new BABYLON.Vector2(xmin, ymin),
  32177. new BABYLON.Vector2(xmax, ymin),
  32178. new BABYLON.Vector2(xmax, ymax),
  32179. new BABYLON.Vector2(xmin, ymax)
  32180. ];
  32181. };
  32182. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  32183. if (cx === void 0) { cx = 0; }
  32184. if (cy === void 0) { cy = 0; }
  32185. if (numberOfSides === void 0) { numberOfSides = 32; }
  32186. var result = new Array();
  32187. var angle = 0;
  32188. var increment = (Math.PI * 2) / numberOfSides;
  32189. for (var i = 0; i < numberOfSides; i++) {
  32190. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  32191. angle -= increment;
  32192. }
  32193. return result;
  32194. };
  32195. Polygon.Parse = function (input) {
  32196. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  32197. var i, result = [];
  32198. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32199. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32200. }
  32201. return result;
  32202. };
  32203. Polygon.StartingAt = function (x, y) {
  32204. return BABYLON.Path2.StartingAt(x, y);
  32205. };
  32206. return Polygon;
  32207. })();
  32208. BABYLON.Polygon = Polygon;
  32209. var PolygonMeshBuilder = (function () {
  32210. function PolygonMeshBuilder(name, contours, scene) {
  32211. this._points = new PolygonPoints();
  32212. this._outlinepoints = new PolygonPoints();
  32213. this._holes = [];
  32214. if (!("poly2tri" in window)) {
  32215. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32216. }
  32217. this._name = name;
  32218. this._scene = scene;
  32219. var points;
  32220. if (contours instanceof BABYLON.Path2) {
  32221. points = contours.getPoints();
  32222. }
  32223. else {
  32224. points = contours;
  32225. }
  32226. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32227. this._outlinepoints.add(points);
  32228. }
  32229. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32230. this._swctx.addHole(this._points.add(hole));
  32231. var holepoints = new PolygonPoints();
  32232. holepoints.add(hole);
  32233. this._holes.push(holepoints);
  32234. return this;
  32235. };
  32236. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32237. var _this = this;
  32238. if (updatable === void 0) { updatable = false; }
  32239. var result = new BABYLON.Mesh(this._name, this._scene);
  32240. var normals = [];
  32241. var positions = [];
  32242. var uvs = [];
  32243. var bounds = this._points.computeBounds();
  32244. this._points.elements.forEach(function (p) {
  32245. normals.push(0, 1.0, 0);
  32246. positions.push(p.x, 0, p.y);
  32247. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32248. });
  32249. var indices = [];
  32250. this._swctx.triangulate();
  32251. this._swctx.getTriangles().forEach(function (triangle) {
  32252. triangle.getPoints().forEach(function (point) {
  32253. indices.push(point.index);
  32254. });
  32255. });
  32256. if (depth > 0) {
  32257. var positionscount = (positions.length / 3); //get the current pointcount
  32258. this._points.elements.forEach(function (p) {
  32259. normals.push(0, -1.0, 0);
  32260. positions.push(p.x, -depth, p.y);
  32261. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32262. });
  32263. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32264. var p2;
  32265. var poscounter = 0;
  32266. this._swctx.getTriangles().forEach(function (triangle) {
  32267. triangle.getPoints().forEach(function (point) {
  32268. switch (poscounter) {
  32269. case 0:
  32270. p1 = point;
  32271. break;
  32272. case 1:
  32273. p2 = point;
  32274. break;
  32275. case 2:
  32276. indices.push(point.index + positionscount);
  32277. indices.push(p2.index + positionscount);
  32278. indices.push(p1.index + positionscount);
  32279. poscounter = -1;
  32280. break;
  32281. }
  32282. poscounter++;
  32283. //indices.push((<IndexedVector2>point).index + positionscount);
  32284. });
  32285. });
  32286. //Add the sides
  32287. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32288. this._holes.forEach(function (hole) {
  32289. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32290. });
  32291. }
  32292. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32293. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32294. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32295. result.setIndices(indices);
  32296. return result;
  32297. };
  32298. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32299. var StartIndex = positions.length / 3;
  32300. var ulength = 0;
  32301. for (var i = 0; i < points.elements.length; i++) {
  32302. var p = points.elements[i];
  32303. var p1;
  32304. if ((i + 1) > points.elements.length - 1) {
  32305. p1 = points.elements[0];
  32306. }
  32307. else {
  32308. p1 = points.elements[i + 1];
  32309. }
  32310. positions.push(p.x, 0, p.y);
  32311. positions.push(p.x, -depth, p.y);
  32312. positions.push(p1.x, 0, p1.y);
  32313. positions.push(p1.x, -depth, p1.y);
  32314. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32315. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32316. var v3 = v2.subtract(v1);
  32317. var v4 = new BABYLON.Vector3(0, 1, 0);
  32318. var vn = BABYLON.Vector3.Cross(v3, v4);
  32319. vn = vn.normalize();
  32320. uvs.push(ulength / bounds.width, 0);
  32321. uvs.push(ulength / bounds.width, 1);
  32322. ulength += v3.length();
  32323. uvs.push((ulength / bounds.width), 0);
  32324. uvs.push((ulength / bounds.width), 1);
  32325. if (!flip) {
  32326. normals.push(-vn.x, -vn.y, -vn.z);
  32327. normals.push(-vn.x, -vn.y, -vn.z);
  32328. normals.push(-vn.x, -vn.y, -vn.z);
  32329. normals.push(-vn.x, -vn.y, -vn.z);
  32330. indices.push(StartIndex);
  32331. indices.push(StartIndex + 1);
  32332. indices.push(StartIndex + 2);
  32333. indices.push(StartIndex + 1);
  32334. indices.push(StartIndex + 3);
  32335. indices.push(StartIndex + 2);
  32336. }
  32337. else {
  32338. normals.push(vn.x, vn.y, vn.z);
  32339. normals.push(vn.x, vn.y, vn.z);
  32340. normals.push(vn.x, vn.y, vn.z);
  32341. normals.push(vn.x, vn.y, vn.z);
  32342. indices.push(StartIndex);
  32343. indices.push(StartIndex + 2);
  32344. indices.push(StartIndex + 1);
  32345. indices.push(StartIndex + 1);
  32346. indices.push(StartIndex + 2);
  32347. indices.push(StartIndex + 3);
  32348. }
  32349. StartIndex += 4;
  32350. }
  32351. ;
  32352. };
  32353. return PolygonMeshBuilder;
  32354. })();
  32355. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32356. })(BABYLON || (BABYLON = {}));
  32357. var BABYLON;
  32358. (function (BABYLON) {
  32359. var Octree = (function () {
  32360. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32361. if (maxDepth === void 0) { maxDepth = 2; }
  32362. this.maxDepth = maxDepth;
  32363. this.dynamicContent = new Array();
  32364. this._maxBlockCapacity = maxBlockCapacity || 64;
  32365. this._selectionContent = new BABYLON.SmartArray(1024);
  32366. this._creationFunc = creationFunc;
  32367. }
  32368. // Methods
  32369. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32370. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32371. };
  32372. Octree.prototype.addMesh = function (entry) {
  32373. for (var index = 0; index < this.blocks.length; index++) {
  32374. var block = this.blocks[index];
  32375. block.addEntry(entry);
  32376. }
  32377. };
  32378. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32379. this._selectionContent.reset();
  32380. for (var index = 0; index < this.blocks.length; index++) {
  32381. var block = this.blocks[index];
  32382. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32383. }
  32384. if (allowDuplicate) {
  32385. this._selectionContent.concat(this.dynamicContent);
  32386. }
  32387. else {
  32388. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32389. }
  32390. return this._selectionContent;
  32391. };
  32392. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32393. this._selectionContent.reset();
  32394. for (var index = 0; index < this.blocks.length; index++) {
  32395. var block = this.blocks[index];
  32396. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32397. }
  32398. if (allowDuplicate) {
  32399. this._selectionContent.concat(this.dynamicContent);
  32400. }
  32401. else {
  32402. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32403. }
  32404. return this._selectionContent;
  32405. };
  32406. Octree.prototype.intersectsRay = function (ray) {
  32407. this._selectionContent.reset();
  32408. for (var index = 0; index < this.blocks.length; index++) {
  32409. var block = this.blocks[index];
  32410. block.intersectsRay(ray, this._selectionContent);
  32411. }
  32412. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32413. return this._selectionContent;
  32414. };
  32415. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32416. target.blocks = new Array();
  32417. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32418. // Segmenting space
  32419. for (var x = 0; x < 2; x++) {
  32420. for (var y = 0; y < 2; y++) {
  32421. for (var z = 0; z < 2; z++) {
  32422. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32423. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32424. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32425. block.addEntries(entries);
  32426. target.blocks.push(block);
  32427. }
  32428. }
  32429. }
  32430. };
  32431. Octree.CreationFuncForMeshes = function (entry, block) {
  32432. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32433. block.entries.push(entry);
  32434. }
  32435. };
  32436. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32437. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32438. block.entries.push(entry);
  32439. }
  32440. };
  32441. return Octree;
  32442. })();
  32443. BABYLON.Octree = Octree;
  32444. })(BABYLON || (BABYLON = {}));
  32445. var BABYLON;
  32446. (function (BABYLON) {
  32447. var OctreeBlock = (function () {
  32448. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32449. this.entries = new Array();
  32450. this._boundingVectors = new Array();
  32451. this._capacity = capacity;
  32452. this._depth = depth;
  32453. this._maxDepth = maxDepth;
  32454. this._creationFunc = creationFunc;
  32455. this._minPoint = minPoint;
  32456. this._maxPoint = maxPoint;
  32457. this._boundingVectors.push(minPoint.clone());
  32458. this._boundingVectors.push(maxPoint.clone());
  32459. this._boundingVectors.push(minPoint.clone());
  32460. this._boundingVectors[2].x = maxPoint.x;
  32461. this._boundingVectors.push(minPoint.clone());
  32462. this._boundingVectors[3].y = maxPoint.y;
  32463. this._boundingVectors.push(minPoint.clone());
  32464. this._boundingVectors[4].z = maxPoint.z;
  32465. this._boundingVectors.push(maxPoint.clone());
  32466. this._boundingVectors[5].z = minPoint.z;
  32467. this._boundingVectors.push(maxPoint.clone());
  32468. this._boundingVectors[6].x = minPoint.x;
  32469. this._boundingVectors.push(maxPoint.clone());
  32470. this._boundingVectors[7].y = minPoint.y;
  32471. }
  32472. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32473. // Property
  32474. get: function () {
  32475. return this._capacity;
  32476. },
  32477. enumerable: true,
  32478. configurable: true
  32479. });
  32480. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32481. get: function () {
  32482. return this._minPoint;
  32483. },
  32484. enumerable: true,
  32485. configurable: true
  32486. });
  32487. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32488. get: function () {
  32489. return this._maxPoint;
  32490. },
  32491. enumerable: true,
  32492. configurable: true
  32493. });
  32494. // Methods
  32495. OctreeBlock.prototype.addEntry = function (entry) {
  32496. if (this.blocks) {
  32497. for (var index = 0; index < this.blocks.length; index++) {
  32498. var block = this.blocks[index];
  32499. block.addEntry(entry);
  32500. }
  32501. return;
  32502. }
  32503. this._creationFunc(entry, this);
  32504. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32505. this.createInnerBlocks();
  32506. }
  32507. };
  32508. OctreeBlock.prototype.addEntries = function (entries) {
  32509. for (var index = 0; index < entries.length; index++) {
  32510. var mesh = entries[index];
  32511. this.addEntry(mesh);
  32512. }
  32513. };
  32514. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32515. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32516. if (this.blocks) {
  32517. for (var index = 0; index < this.blocks.length; index++) {
  32518. var block = this.blocks[index];
  32519. block.select(frustumPlanes, selection, allowDuplicate);
  32520. }
  32521. return;
  32522. }
  32523. if (allowDuplicate) {
  32524. selection.concat(this.entries);
  32525. }
  32526. else {
  32527. selection.concatWithNoDuplicate(this.entries);
  32528. }
  32529. }
  32530. };
  32531. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32532. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32533. if (this.blocks) {
  32534. for (var index = 0; index < this.blocks.length; index++) {
  32535. var block = this.blocks[index];
  32536. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32537. }
  32538. return;
  32539. }
  32540. if (allowDuplicate) {
  32541. selection.concat(this.entries);
  32542. }
  32543. else {
  32544. selection.concatWithNoDuplicate(this.entries);
  32545. }
  32546. }
  32547. };
  32548. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32549. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32550. if (this.blocks) {
  32551. for (var index = 0; index < this.blocks.length; index++) {
  32552. var block = this.blocks[index];
  32553. block.intersectsRay(ray, selection);
  32554. }
  32555. return;
  32556. }
  32557. selection.concatWithNoDuplicate(this.entries);
  32558. }
  32559. };
  32560. OctreeBlock.prototype.createInnerBlocks = function () {
  32561. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32562. };
  32563. return OctreeBlock;
  32564. })();
  32565. BABYLON.OctreeBlock = OctreeBlock;
  32566. })(BABYLON || (BABYLON = {}));
  32567. var BABYLON;
  32568. (function (BABYLON) {
  32569. var BlurPostProcess = (function (_super) {
  32570. __extends(BlurPostProcess, _super);
  32571. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32572. var _this = this;
  32573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32574. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32575. this.direction = direction;
  32576. this.blurWidth = blurWidth;
  32577. this.onApply = function (effect) {
  32578. effect.setFloat2("screenSize", _this.width, _this.height);
  32579. effect.setVector2("direction", _this.direction);
  32580. effect.setFloat("blurWidth", _this.blurWidth);
  32581. };
  32582. }
  32583. return BlurPostProcess;
  32584. })(BABYLON.PostProcess);
  32585. BABYLON.BlurPostProcess = BlurPostProcess;
  32586. })(BABYLON || (BABYLON = {}));
  32587. var BABYLON;
  32588. (function (BABYLON) {
  32589. var RefractionPostProcess = (function (_super) {
  32590. __extends(RefractionPostProcess, _super);
  32591. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32592. var _this = this;
  32593. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32594. this.color = color;
  32595. this.depth = depth;
  32596. this.colorLevel = colorLevel;
  32597. this.onActivate = function (cam) {
  32598. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32599. };
  32600. this.onApply = function (effect) {
  32601. effect.setColor3("baseColor", _this.color);
  32602. effect.setFloat("depth", _this.depth);
  32603. effect.setFloat("colorLevel", _this.colorLevel);
  32604. effect.setTexture("refractionSampler", _this._refRexture);
  32605. };
  32606. }
  32607. // Methods
  32608. RefractionPostProcess.prototype.dispose = function (camera) {
  32609. if (this._refRexture) {
  32610. this._refRexture.dispose();
  32611. }
  32612. _super.prototype.dispose.call(this, camera);
  32613. };
  32614. return RefractionPostProcess;
  32615. })(BABYLON.PostProcess);
  32616. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32617. })(BABYLON || (BABYLON = {}));
  32618. var BABYLON;
  32619. (function (BABYLON) {
  32620. var BlackAndWhitePostProcess = (function (_super) {
  32621. __extends(BlackAndWhitePostProcess, _super);
  32622. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32623. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32624. }
  32625. return BlackAndWhitePostProcess;
  32626. })(BABYLON.PostProcess);
  32627. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32628. })(BABYLON || (BABYLON = {}));
  32629. var BABYLON;
  32630. (function (BABYLON) {
  32631. var ConvolutionPostProcess = (function (_super) {
  32632. __extends(ConvolutionPostProcess, _super);
  32633. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32634. var _this = this;
  32635. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32636. this.kernel = kernel;
  32637. this.onApply = function (effect) {
  32638. effect.setFloat2("screenSize", _this.width, _this.height);
  32639. effect.setArray("kernel", _this.kernel);
  32640. };
  32641. }
  32642. // Statics
  32643. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32644. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32645. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32646. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32647. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32648. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32649. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32650. return ConvolutionPostProcess;
  32651. })(BABYLON.PostProcess);
  32652. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32653. })(BABYLON || (BABYLON = {}));
  32654. var BABYLON;
  32655. (function (BABYLON) {
  32656. var FilterPostProcess = (function (_super) {
  32657. __extends(FilterPostProcess, _super);
  32658. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32659. var _this = this;
  32660. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32661. this.kernelMatrix = kernelMatrix;
  32662. this.onApply = function (effect) {
  32663. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32664. };
  32665. }
  32666. return FilterPostProcess;
  32667. })(BABYLON.PostProcess);
  32668. BABYLON.FilterPostProcess = FilterPostProcess;
  32669. })(BABYLON || (BABYLON = {}));
  32670. var BABYLON;
  32671. (function (BABYLON) {
  32672. var FxaaPostProcess = (function (_super) {
  32673. __extends(FxaaPostProcess, _super);
  32674. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32675. var _this = this;
  32676. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32677. this.onSizeChanged = function () {
  32678. _this.texelWidth = 1.0 / _this.width;
  32679. _this.texelHeight = 1.0 / _this.height;
  32680. };
  32681. this.onApply = function (effect) {
  32682. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32683. };
  32684. }
  32685. return FxaaPostProcess;
  32686. })(BABYLON.PostProcess);
  32687. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32688. })(BABYLON || (BABYLON = {}));
  32689. var BABYLON;
  32690. (function (BABYLON) {
  32691. var StereoscopicInterlacePostProcess = (function (_super) {
  32692. __extends(StereoscopicInterlacePostProcess, _super);
  32693. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32694. var _this = this;
  32695. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32696. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32697. this.onSizeChanged = function () {
  32698. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32699. };
  32700. this.onApply = function (effect) {
  32701. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32702. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32703. };
  32704. }
  32705. return StereoscopicInterlacePostProcess;
  32706. })(BABYLON.PostProcess);
  32707. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32708. })(BABYLON || (BABYLON = {}));
  32709. var BABYLON;
  32710. (function (BABYLON) {
  32711. var LensFlare = (function () {
  32712. function LensFlare(size, position, color, imgUrl, system) {
  32713. this.size = size;
  32714. this.position = position;
  32715. this.dispose = function () {
  32716. if (this.texture) {
  32717. this.texture.dispose();
  32718. }
  32719. // Remove from scene
  32720. var index = this._system.lensFlares.indexOf(this);
  32721. this._system.lensFlares.splice(index, 1);
  32722. };
  32723. this.color = color || new BABYLON.Color3(1, 1, 1);
  32724. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32725. this._system = system;
  32726. system.lensFlares.push(this);
  32727. }
  32728. return LensFlare;
  32729. })();
  32730. BABYLON.LensFlare = LensFlare;
  32731. })(BABYLON || (BABYLON = {}));
  32732. var BABYLON;
  32733. (function (BABYLON) {
  32734. var LensFlareSystem = (function () {
  32735. function LensFlareSystem(name, emitter, scene) {
  32736. this.name = name;
  32737. this.lensFlares = new Array();
  32738. this.borderLimit = 300;
  32739. this.layerMask = 0x0FFFFFFF;
  32740. this._vertexDeclaration = [2];
  32741. this._vertexStrideSize = 2 * 4;
  32742. this._isEnabled = true;
  32743. this._scene = scene;
  32744. this._emitter = emitter;
  32745. scene.lensFlareSystems.push(this);
  32746. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32747. // VBO
  32748. var vertices = [];
  32749. vertices.push(1, 1);
  32750. vertices.push(-1, 1);
  32751. vertices.push(-1, -1);
  32752. vertices.push(1, -1);
  32753. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32754. // Indices
  32755. var indices = [];
  32756. indices.push(0);
  32757. indices.push(1);
  32758. indices.push(2);
  32759. indices.push(0);
  32760. indices.push(2);
  32761. indices.push(3);
  32762. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32763. // Effects
  32764. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32765. }
  32766. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32767. get: function () {
  32768. return this._isEnabled;
  32769. },
  32770. set: function (value) {
  32771. this._isEnabled = value;
  32772. },
  32773. enumerable: true,
  32774. configurable: true
  32775. });
  32776. LensFlareSystem.prototype.getScene = function () {
  32777. return this._scene;
  32778. };
  32779. LensFlareSystem.prototype.getEmitter = function () {
  32780. return this._emitter;
  32781. };
  32782. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32783. this._emitter = newEmitter;
  32784. };
  32785. LensFlareSystem.prototype.getEmitterPosition = function () {
  32786. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32787. };
  32788. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32789. var position = this.getEmitterPosition();
  32790. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32791. this._positionX = position.x;
  32792. this._positionY = position.y;
  32793. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32794. if (position.z > 0) {
  32795. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32796. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32797. return true;
  32798. }
  32799. }
  32800. return false;
  32801. };
  32802. LensFlareSystem.prototype._isVisible = function () {
  32803. if (!this._isEnabled) {
  32804. return false;
  32805. }
  32806. var emitterPosition = this.getEmitterPosition();
  32807. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32808. var distance = direction.length();
  32809. direction.normalize();
  32810. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32811. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32812. return !pickInfo.hit || pickInfo.distance > distance;
  32813. };
  32814. LensFlareSystem.prototype.render = function () {
  32815. if (!this._effect.isReady())
  32816. return false;
  32817. var engine = this._scene.getEngine();
  32818. var viewport = this._scene.activeCamera.viewport;
  32819. var globalViewport = viewport.toGlobal(engine);
  32820. // Position
  32821. if (!this.computeEffectivePosition(globalViewport)) {
  32822. return false;
  32823. }
  32824. // Visibility
  32825. if (!this._isVisible()) {
  32826. return false;
  32827. }
  32828. // Intensity
  32829. var awayX;
  32830. var awayY;
  32831. if (this._positionX < this.borderLimit + globalViewport.x) {
  32832. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32833. }
  32834. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32835. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32836. }
  32837. else {
  32838. awayX = 0;
  32839. }
  32840. if (this._positionY < this.borderLimit + globalViewport.y) {
  32841. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32842. }
  32843. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32844. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32845. }
  32846. else {
  32847. awayY = 0;
  32848. }
  32849. var away = (awayX > awayY) ? awayX : awayY;
  32850. if (away > this.borderLimit) {
  32851. away = this.borderLimit;
  32852. }
  32853. var intensity = 1.0 - (away / this.borderLimit);
  32854. if (intensity < 0) {
  32855. return false;
  32856. }
  32857. if (intensity > 1.0) {
  32858. intensity = 1.0;
  32859. }
  32860. // Position
  32861. var centerX = globalViewport.x + globalViewport.width / 2;
  32862. var centerY = globalViewport.y + globalViewport.height / 2;
  32863. var distX = centerX - this._positionX;
  32864. var distY = centerY - this._positionY;
  32865. // Effects
  32866. engine.enableEffect(this._effect);
  32867. engine.setState(false);
  32868. engine.setDepthBuffer(false);
  32869. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32870. // VBOs
  32871. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32872. // Flares
  32873. for (var index = 0; index < this.lensFlares.length; index++) {
  32874. var flare = this.lensFlares[index];
  32875. var x = centerX - (distX * flare.position);
  32876. var y = centerY - (distY * flare.position);
  32877. var cw = flare.size;
  32878. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32879. var cx = 2 * (x / globalViewport.width) - 1.0;
  32880. var cy = 1.0 - 2 * (y / globalViewport.height);
  32881. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32882. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32883. // Texture
  32884. this._effect.setTexture("textureSampler", flare.texture);
  32885. // Color
  32886. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32887. // Draw order
  32888. engine.draw(true, 0, 6);
  32889. }
  32890. engine.setDepthBuffer(true);
  32891. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32892. return true;
  32893. };
  32894. LensFlareSystem.prototype.dispose = function () {
  32895. if (this._vertexBuffer) {
  32896. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32897. this._vertexBuffer = null;
  32898. }
  32899. if (this._indexBuffer) {
  32900. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32901. this._indexBuffer = null;
  32902. }
  32903. while (this.lensFlares.length) {
  32904. this.lensFlares[0].dispose();
  32905. }
  32906. // Remove from scene
  32907. var index = this._scene.lensFlareSystems.indexOf(this);
  32908. this._scene.lensFlareSystems.splice(index, 1);
  32909. };
  32910. return LensFlareSystem;
  32911. })();
  32912. BABYLON.LensFlareSystem = LensFlareSystem;
  32913. })(BABYLON || (BABYLON = {}));
  32914. var BABYLON;
  32915. (function (BABYLON) {
  32916. // We're mainly based on the logic defined into the FreeCamera code
  32917. var DeviceOrientationCamera = (function (_super) {
  32918. __extends(DeviceOrientationCamera, _super);
  32919. function DeviceOrientationCamera(name, position, scene) {
  32920. var _this = this;
  32921. _super.call(this, name, position, scene);
  32922. this._offsetX = null;
  32923. this._offsetY = null;
  32924. this._orientationGamma = 0;
  32925. this._orientationBeta = 0;
  32926. this._initialOrientationGamma = 0;
  32927. this._initialOrientationBeta = 0;
  32928. this.angularSensibility = 10000.0;
  32929. this.moveSensibility = 50.0;
  32930. window.addEventListener("resize", function () {
  32931. _this._initialOrientationGamma = null;
  32932. }, false);
  32933. }
  32934. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32935. var _this = this;
  32936. if (this._attachedCanvas) {
  32937. return;
  32938. }
  32939. this._attachedCanvas = canvas;
  32940. if (!this._orientationChanged) {
  32941. this._orientationChanged = function (evt) {
  32942. if (!_this._initialOrientationGamma) {
  32943. _this._initialOrientationGamma = evt.gamma;
  32944. _this._initialOrientationBeta = evt.beta;
  32945. }
  32946. _this._orientationGamma = evt.gamma;
  32947. _this._orientationBeta = evt.beta;
  32948. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32949. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32950. };
  32951. }
  32952. window.addEventListener("deviceorientation", this._orientationChanged);
  32953. };
  32954. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32955. if (this._attachedCanvas != canvas) {
  32956. return;
  32957. }
  32958. window.removeEventListener("deviceorientation", this._orientationChanged);
  32959. this._attachedCanvas = null;
  32960. this._orientationGamma = 0;
  32961. this._orientationBeta = 0;
  32962. this._initialOrientationGamma = 0;
  32963. this._initialOrientationBeta = 0;
  32964. };
  32965. DeviceOrientationCamera.prototype._checkInputs = function () {
  32966. if (!this._offsetX) {
  32967. return;
  32968. }
  32969. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32970. var speed = this._computeLocalCameraSpeed();
  32971. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32972. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32973. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32974. _super.prototype._checkInputs.call(this);
  32975. };
  32976. return DeviceOrientationCamera;
  32977. })(BABYLON.FreeCamera);
  32978. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32979. })(BABYLON || (BABYLON = {}));
  32980. var BABYLON;
  32981. (function (BABYLON) {
  32982. var Gamepads = (function () {
  32983. function Gamepads(ongamedpadconnected) {
  32984. var _this = this;
  32985. this.babylonGamepads = [];
  32986. this.oneGamepadConnected = false;
  32987. this.isMonitoring = false;
  32988. this.gamepadEventSupported = 'GamepadEvent' in window;
  32989. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32990. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32991. 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=";
  32992. this._callbackGamepadConnected = ongamedpadconnected;
  32993. if (this.gamepadSupportAvailable) {
  32994. // Checking if the gamepad connected event is supported (like in Firefox)
  32995. if (this.gamepadEventSupported) {
  32996. window.addEventListener('gamepadconnected', function (evt) {
  32997. _this._onGamepadConnected(evt);
  32998. }, false);
  32999. window.addEventListener('gamepaddisconnected', function (evt) {
  33000. _this._onGamepadDisconnected(evt);
  33001. }, false);
  33002. }
  33003. else {
  33004. this._startMonitoringGamepads();
  33005. }
  33006. if (!this.oneGamepadConnected) {
  33007. this._insertGamepadDOMInstructions();
  33008. }
  33009. }
  33010. else {
  33011. this._insertGamepadDOMNotSupported();
  33012. }
  33013. }
  33014. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  33015. Gamepads.gamepadDOMInfo = document.createElement("div");
  33016. var buttonAImage = document.createElement("img");
  33017. buttonAImage.src = this.buttonADataURL;
  33018. var spanMessage = document.createElement("span");
  33019. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  33020. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  33021. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33022. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33023. Gamepads.gamepadDOMInfo.style.width = "100%";
  33024. Gamepads.gamepadDOMInfo.style.height = "48px";
  33025. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33026. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33027. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33028. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33029. buttonAImage.style.position = "relative";
  33030. buttonAImage.style.bottom = "8px";
  33031. spanMessage.style.position = "relative";
  33032. spanMessage.style.fontSize = "32px";
  33033. spanMessage.style.bottom = "32px";
  33034. spanMessage.style.color = "green";
  33035. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33036. };
  33037. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  33038. Gamepads.gamepadDOMInfo = document.createElement("div");
  33039. var spanMessage = document.createElement("span");
  33040. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  33041. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33042. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33043. Gamepads.gamepadDOMInfo.style.width = "100%";
  33044. Gamepads.gamepadDOMInfo.style.height = "40px";
  33045. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33046. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33047. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33048. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33049. spanMessage.style.position = "relative";
  33050. spanMessage.style.fontSize = "32px";
  33051. spanMessage.style.color = "red";
  33052. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33053. };
  33054. Gamepads.prototype.dispose = function () {
  33055. if (Gamepads.gamepadDOMInfo) {
  33056. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33057. }
  33058. };
  33059. Gamepads.prototype._onGamepadConnected = function (evt) {
  33060. var newGamepad = this._addNewGamepad(evt.gamepad);
  33061. if (this._callbackGamepadConnected)
  33062. this._callbackGamepadConnected(newGamepad);
  33063. this._startMonitoringGamepads();
  33064. };
  33065. Gamepads.prototype._addNewGamepad = function (gamepad) {
  33066. if (!this.oneGamepadConnected) {
  33067. this.oneGamepadConnected = true;
  33068. if (Gamepads.gamepadDOMInfo) {
  33069. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33070. Gamepads.gamepadDOMInfo = null;
  33071. }
  33072. }
  33073. var newGamepad;
  33074. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  33075. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  33076. }
  33077. else {
  33078. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  33079. }
  33080. this.babylonGamepads.push(newGamepad);
  33081. return newGamepad;
  33082. };
  33083. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  33084. // Remove the gamepad from the list of gamepads to monitor.
  33085. for (var i in this.babylonGamepads) {
  33086. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  33087. this.babylonGamepads.splice(i, 1);
  33088. break;
  33089. }
  33090. }
  33091. // If no gamepads are left, stop the polling loop.
  33092. if (this.babylonGamepads.length == 0) {
  33093. this._stopMonitoringGamepads();
  33094. }
  33095. };
  33096. Gamepads.prototype._startMonitoringGamepads = function () {
  33097. if (!this.isMonitoring) {
  33098. this.isMonitoring = true;
  33099. this._checkGamepadsStatus();
  33100. }
  33101. };
  33102. Gamepads.prototype._stopMonitoringGamepads = function () {
  33103. this.isMonitoring = false;
  33104. };
  33105. Gamepads.prototype._checkGamepadsStatus = function () {
  33106. var _this = this;
  33107. // updating gamepad objects
  33108. this._updateGamepadObjects();
  33109. for (var i in this.babylonGamepads) {
  33110. this.babylonGamepads[i].update();
  33111. }
  33112. if (this.isMonitoring) {
  33113. if (window.requestAnimationFrame) {
  33114. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33115. }
  33116. else if (window.mozRequestAnimationFrame) {
  33117. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33118. }
  33119. else if (window.webkitRequestAnimationFrame) {
  33120. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33121. }
  33122. }
  33123. };
  33124. // This function is called only on Chrome, which does not yet support
  33125. // connection/disconnection events, but requires you to monitor
  33126. // an array for changes.
  33127. Gamepads.prototype._updateGamepadObjects = function () {
  33128. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  33129. for (var i = 0; i < gamepads.length; i++) {
  33130. if (gamepads[i]) {
  33131. if (!(gamepads[i].index in this.babylonGamepads)) {
  33132. var newGamepad = this._addNewGamepad(gamepads[i]);
  33133. if (this._callbackGamepadConnected) {
  33134. this._callbackGamepadConnected(newGamepad);
  33135. }
  33136. }
  33137. else {
  33138. this.babylonGamepads[i].browserGamepad = gamepads[i];
  33139. }
  33140. }
  33141. }
  33142. };
  33143. return Gamepads;
  33144. })();
  33145. BABYLON.Gamepads = Gamepads;
  33146. var StickValues = (function () {
  33147. function StickValues(x, y) {
  33148. this.x = x;
  33149. this.y = y;
  33150. }
  33151. return StickValues;
  33152. })();
  33153. BABYLON.StickValues = StickValues;
  33154. var Gamepad = (function () {
  33155. function Gamepad(id, index, browserGamepad) {
  33156. this.id = id;
  33157. this.index = index;
  33158. this.browserGamepad = browserGamepad;
  33159. if (this.browserGamepad.axes.length >= 2) {
  33160. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33161. }
  33162. if (this.browserGamepad.axes.length >= 4) {
  33163. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33164. }
  33165. }
  33166. Gamepad.prototype.onleftstickchanged = function (callback) {
  33167. this._onleftstickchanged = callback;
  33168. };
  33169. Gamepad.prototype.onrightstickchanged = function (callback) {
  33170. this._onrightstickchanged = callback;
  33171. };
  33172. Object.defineProperty(Gamepad.prototype, "leftStick", {
  33173. get: function () {
  33174. return this._leftStick;
  33175. },
  33176. set: function (newValues) {
  33177. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  33178. this._onleftstickchanged(newValues);
  33179. }
  33180. this._leftStick = newValues;
  33181. },
  33182. enumerable: true,
  33183. configurable: true
  33184. });
  33185. Object.defineProperty(Gamepad.prototype, "rightStick", {
  33186. get: function () {
  33187. return this._rightStick;
  33188. },
  33189. set: function (newValues) {
  33190. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  33191. this._onrightstickchanged(newValues);
  33192. }
  33193. this._rightStick = newValues;
  33194. },
  33195. enumerable: true,
  33196. configurable: true
  33197. });
  33198. Gamepad.prototype.update = function () {
  33199. if (this._leftStick) {
  33200. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33201. }
  33202. if (this._rightStick) {
  33203. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33204. }
  33205. };
  33206. return Gamepad;
  33207. })();
  33208. BABYLON.Gamepad = Gamepad;
  33209. var GenericPad = (function (_super) {
  33210. __extends(GenericPad, _super);
  33211. function GenericPad(id, index, gamepad) {
  33212. _super.call(this, id, index, gamepad);
  33213. this.id = id;
  33214. this.index = index;
  33215. this.gamepad = gamepad;
  33216. this._buttons = new Array(gamepad.buttons.length);
  33217. }
  33218. GenericPad.prototype.onbuttondown = function (callback) {
  33219. this._onbuttondown = callback;
  33220. };
  33221. GenericPad.prototype.onbuttonup = function (callback) {
  33222. this._onbuttonup = callback;
  33223. };
  33224. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33225. if (newValue !== currentValue) {
  33226. if (this._onbuttondown && newValue === 1) {
  33227. this._onbuttondown(buttonIndex);
  33228. }
  33229. if (this._onbuttonup && newValue === 0) {
  33230. this._onbuttonup(buttonIndex);
  33231. }
  33232. }
  33233. return newValue;
  33234. };
  33235. GenericPad.prototype.update = function () {
  33236. _super.prototype.update.call(this);
  33237. for (var index = 0; index < this._buttons.length; index++) {
  33238. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33239. }
  33240. };
  33241. return GenericPad;
  33242. })(Gamepad);
  33243. BABYLON.GenericPad = GenericPad;
  33244. (function (Xbox360Button) {
  33245. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33246. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33247. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33248. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33249. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33250. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33251. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33252. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33253. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33254. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33255. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33256. var Xbox360Button = BABYLON.Xbox360Button;
  33257. (function (Xbox360Dpad) {
  33258. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33259. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33260. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33261. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33262. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33263. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33264. var Xbox360Pad = (function (_super) {
  33265. __extends(Xbox360Pad, _super);
  33266. function Xbox360Pad() {
  33267. _super.apply(this, arguments);
  33268. this._leftTrigger = 0;
  33269. this._rightTrigger = 0;
  33270. this._buttonA = 0;
  33271. this._buttonB = 0;
  33272. this._buttonX = 0;
  33273. this._buttonY = 0;
  33274. this._buttonBack = 0;
  33275. this._buttonStart = 0;
  33276. this._buttonLB = 0;
  33277. this._buttonRB = 0;
  33278. this._buttonLeftStick = 0;
  33279. this._buttonRightStick = 0;
  33280. this._dPadUp = 0;
  33281. this._dPadDown = 0;
  33282. this._dPadLeft = 0;
  33283. this._dPadRight = 0;
  33284. }
  33285. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33286. this._onlefttriggerchanged = callback;
  33287. };
  33288. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33289. this._onrighttriggerchanged = callback;
  33290. };
  33291. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33292. get: function () {
  33293. return this._leftTrigger;
  33294. },
  33295. set: function (newValue) {
  33296. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33297. this._onlefttriggerchanged(newValue);
  33298. }
  33299. this._leftTrigger = newValue;
  33300. },
  33301. enumerable: true,
  33302. configurable: true
  33303. });
  33304. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33305. get: function () {
  33306. return this._rightTrigger;
  33307. },
  33308. set: function (newValue) {
  33309. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33310. this._onrighttriggerchanged(newValue);
  33311. }
  33312. this._rightTrigger = newValue;
  33313. },
  33314. enumerable: true,
  33315. configurable: true
  33316. });
  33317. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33318. this._onbuttondown = callback;
  33319. };
  33320. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33321. this._onbuttonup = callback;
  33322. };
  33323. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33324. this._ondpaddown = callback;
  33325. };
  33326. Xbox360Pad.prototype.ondpadup = function (callback) {
  33327. this._ondpadup = callback;
  33328. };
  33329. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33330. if (newValue !== currentValue) {
  33331. if (this._onbuttondown && newValue === 1) {
  33332. this._onbuttondown(buttonType);
  33333. }
  33334. if (this._onbuttonup && newValue === 0) {
  33335. this._onbuttonup(buttonType);
  33336. }
  33337. }
  33338. return newValue;
  33339. };
  33340. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33341. if (newValue !== currentValue) {
  33342. if (this._ondpaddown && newValue === 1) {
  33343. this._ondpaddown(buttonType);
  33344. }
  33345. if (this._ondpadup && newValue === 0) {
  33346. this._ondpadup(buttonType);
  33347. }
  33348. }
  33349. return newValue;
  33350. };
  33351. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33352. get: function () {
  33353. return this._buttonA;
  33354. },
  33355. set: function (value) {
  33356. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33357. },
  33358. enumerable: true,
  33359. configurable: true
  33360. });
  33361. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33362. get: function () {
  33363. return this._buttonB;
  33364. },
  33365. set: function (value) {
  33366. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33367. },
  33368. enumerable: true,
  33369. configurable: true
  33370. });
  33371. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33372. get: function () {
  33373. return this._buttonX;
  33374. },
  33375. set: function (value) {
  33376. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33377. },
  33378. enumerable: true,
  33379. configurable: true
  33380. });
  33381. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33382. get: function () {
  33383. return this._buttonY;
  33384. },
  33385. set: function (value) {
  33386. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33387. },
  33388. enumerable: true,
  33389. configurable: true
  33390. });
  33391. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33392. get: function () {
  33393. return this._buttonStart;
  33394. },
  33395. set: function (value) {
  33396. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33397. },
  33398. enumerable: true,
  33399. configurable: true
  33400. });
  33401. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33402. get: function () {
  33403. return this._buttonBack;
  33404. },
  33405. set: function (value) {
  33406. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33407. },
  33408. enumerable: true,
  33409. configurable: true
  33410. });
  33411. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33412. get: function () {
  33413. return this._buttonLB;
  33414. },
  33415. set: function (value) {
  33416. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33417. },
  33418. enumerable: true,
  33419. configurable: true
  33420. });
  33421. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33422. get: function () {
  33423. return this._buttonRB;
  33424. },
  33425. set: function (value) {
  33426. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33427. },
  33428. enumerable: true,
  33429. configurable: true
  33430. });
  33431. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33432. get: function () {
  33433. return this._buttonLeftStick;
  33434. },
  33435. set: function (value) {
  33436. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33437. },
  33438. enumerable: true,
  33439. configurable: true
  33440. });
  33441. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33442. get: function () {
  33443. return this._buttonRightStick;
  33444. },
  33445. set: function (value) {
  33446. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33447. },
  33448. enumerable: true,
  33449. configurable: true
  33450. });
  33451. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33452. get: function () {
  33453. return this._dPadUp;
  33454. },
  33455. set: function (value) {
  33456. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33457. },
  33458. enumerable: true,
  33459. configurable: true
  33460. });
  33461. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33462. get: function () {
  33463. return this._dPadDown;
  33464. },
  33465. set: function (value) {
  33466. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33467. },
  33468. enumerable: true,
  33469. configurable: true
  33470. });
  33471. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33472. get: function () {
  33473. return this._dPadLeft;
  33474. },
  33475. set: function (value) {
  33476. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33477. },
  33478. enumerable: true,
  33479. configurable: true
  33480. });
  33481. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33482. get: function () {
  33483. return this._dPadRight;
  33484. },
  33485. set: function (value) {
  33486. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33487. },
  33488. enumerable: true,
  33489. configurable: true
  33490. });
  33491. Xbox360Pad.prototype.update = function () {
  33492. _super.prototype.update.call(this);
  33493. this.buttonA = this.browserGamepad.buttons[0].value;
  33494. this.buttonB = this.browserGamepad.buttons[1].value;
  33495. this.buttonX = this.browserGamepad.buttons[2].value;
  33496. this.buttonY = this.browserGamepad.buttons[3].value;
  33497. this.buttonLB = this.browserGamepad.buttons[4].value;
  33498. this.buttonRB = this.browserGamepad.buttons[5].value;
  33499. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33500. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33501. this.buttonBack = this.browserGamepad.buttons[8].value;
  33502. this.buttonStart = this.browserGamepad.buttons[9].value;
  33503. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33504. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33505. this.dPadUp = this.browserGamepad.buttons[12].value;
  33506. this.dPadDown = this.browserGamepad.buttons[13].value;
  33507. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33508. this.dPadRight = this.browserGamepad.buttons[15].value;
  33509. };
  33510. return Xbox360Pad;
  33511. })(Gamepad);
  33512. BABYLON.Xbox360Pad = Xbox360Pad;
  33513. })(BABYLON || (BABYLON = {}));
  33514. var BABYLON;
  33515. (function (BABYLON) {
  33516. // We're mainly based on the logic defined into the FreeCamera code
  33517. var GamepadCamera = (function (_super) {
  33518. __extends(GamepadCamera, _super);
  33519. function GamepadCamera(name, position, scene) {
  33520. var _this = this;
  33521. _super.call(this, name, position, scene);
  33522. this.angularSensibility = 200;
  33523. this.moveSensibility = 75;
  33524. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33525. }
  33526. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33527. // Only the first gamepad can control the camera
  33528. if (gamepad.index === 0) {
  33529. this._gamepad = gamepad;
  33530. }
  33531. };
  33532. GamepadCamera.prototype._checkInputs = function () {
  33533. if (this._gamepad) {
  33534. var LSValues = this._gamepad.leftStick;
  33535. var normalizedLX = LSValues.x / this.moveSensibility;
  33536. var normalizedLY = LSValues.y / this.moveSensibility;
  33537. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33538. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33539. var RSValues = this._gamepad.rightStick;
  33540. var normalizedRX = RSValues.x / this.angularSensibility;
  33541. var normalizedRY = RSValues.y / this.angularSensibility;
  33542. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33543. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33544. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33545. var speed = this._computeLocalCameraSpeed() * 50.0;
  33546. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33547. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33548. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33549. }
  33550. _super.prototype._checkInputs.call(this);
  33551. };
  33552. GamepadCamera.prototype.dispose = function () {
  33553. this._gamepads.dispose();
  33554. _super.prototype.dispose.call(this);
  33555. };
  33556. return GamepadCamera;
  33557. })(BABYLON.FreeCamera);
  33558. BABYLON.GamepadCamera = GamepadCamera;
  33559. })(BABYLON || (BABYLON = {}));
  33560. var BABYLON;
  33561. (function (BABYLON) {
  33562. var Analyser = (function () {
  33563. function Analyser(scene) {
  33564. this.SMOOTHING = 0.75;
  33565. this.FFT_SIZE = 512;
  33566. this.BARGRAPHAMPLITUDE = 256;
  33567. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33568. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33569. this._scene = scene;
  33570. this._audioEngine = BABYLON.Engine.audioEngine;
  33571. if (this._audioEngine.canUseWebAudio) {
  33572. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33573. this._webAudioAnalyser.minDecibels = -140;
  33574. this._webAudioAnalyser.maxDecibels = 0;
  33575. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33576. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33577. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33578. }
  33579. }
  33580. Analyser.prototype.getFrequencyBinCount = function () {
  33581. if (this._audioEngine.canUseWebAudio) {
  33582. return this._webAudioAnalyser.frequencyBinCount;
  33583. }
  33584. else {
  33585. return 0;
  33586. }
  33587. };
  33588. Analyser.prototype.getByteFrequencyData = function () {
  33589. if (this._audioEngine.canUseWebAudio) {
  33590. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33591. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33592. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33593. }
  33594. return this._byteFreqs;
  33595. };
  33596. Analyser.prototype.getByteTimeDomainData = function () {
  33597. if (this._audioEngine.canUseWebAudio) {
  33598. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33599. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33600. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33601. }
  33602. return this._byteTime;
  33603. };
  33604. Analyser.prototype.getFloatFrequencyData = function () {
  33605. if (this._audioEngine.canUseWebAudio) {
  33606. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33607. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33608. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33609. }
  33610. return this._floatFreqs;
  33611. };
  33612. Analyser.prototype.drawDebugCanvas = function () {
  33613. var _this = this;
  33614. if (this._audioEngine.canUseWebAudio) {
  33615. if (!this._debugCanvas) {
  33616. this._debugCanvas = document.createElement("canvas");
  33617. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33618. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33619. this._debugCanvas.style.position = "absolute";
  33620. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33621. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33622. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33623. document.body.appendChild(this._debugCanvas);
  33624. this._registerFunc = function () {
  33625. _this.drawDebugCanvas();
  33626. };
  33627. this._scene.registerBeforeRender(this._registerFunc);
  33628. }
  33629. if (this._registerFunc) {
  33630. var workingArray = this.getByteFrequencyData();
  33631. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33632. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33633. // Draw the frequency domain chart.
  33634. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33635. var value = workingArray[i];
  33636. var percent = value / this.BARGRAPHAMPLITUDE;
  33637. var height = this.DEBUGCANVASSIZE.height * percent;
  33638. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33639. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33640. var hue = i / this.getFrequencyBinCount() * 360;
  33641. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33642. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33643. }
  33644. }
  33645. }
  33646. };
  33647. Analyser.prototype.stopDebugCanvas = function () {
  33648. if (this._debugCanvas) {
  33649. this._scene.unregisterBeforeRender(this._registerFunc);
  33650. this._registerFunc = null;
  33651. document.body.removeChild(this._debugCanvas);
  33652. this._debugCanvas = null;
  33653. this._debugCanvasContext = null;
  33654. }
  33655. };
  33656. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33657. if (this._audioEngine.canUseWebAudio) {
  33658. inputAudioNode.connect(this._webAudioAnalyser);
  33659. this._webAudioAnalyser.connect(outputAudioNode);
  33660. }
  33661. };
  33662. Analyser.prototype.dispose = function () {
  33663. if (this._audioEngine.canUseWebAudio) {
  33664. this._webAudioAnalyser.disconnect();
  33665. }
  33666. };
  33667. return Analyser;
  33668. })();
  33669. BABYLON.Analyser = Analyser;
  33670. })(BABYLON || (BABYLON = {}));
  33671. var BABYLON;
  33672. (function (BABYLON) {
  33673. var AudioEngine = (function () {
  33674. function AudioEngine() {
  33675. this._audioContext = null;
  33676. this._audioContextInitialized = false;
  33677. this.canUseWebAudio = false;
  33678. this.WarnedWebAudioUnsupported = false;
  33679. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33680. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33681. this.canUseWebAudio = true;
  33682. }
  33683. }
  33684. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33685. get: function () {
  33686. if (!this._audioContextInitialized) {
  33687. this._initializeAudioContext();
  33688. }
  33689. return this._audioContext;
  33690. },
  33691. enumerable: true,
  33692. configurable: true
  33693. });
  33694. AudioEngine.prototype._initializeAudioContext = function () {
  33695. try {
  33696. if (this.canUseWebAudio) {
  33697. this._audioContext = new AudioContext();
  33698. // create a global volume gain node
  33699. this.masterGain = this._audioContext.createGain();
  33700. this.masterGain.gain.value = 1;
  33701. this.masterGain.connect(this._audioContext.destination);
  33702. this._audioContextInitialized = true;
  33703. }
  33704. }
  33705. catch (e) {
  33706. this.canUseWebAudio = false;
  33707. BABYLON.Tools.Error("Web Audio: " + e.message);
  33708. }
  33709. };
  33710. AudioEngine.prototype.dispose = function () {
  33711. if (this.canUseWebAudio && this._audioContextInitialized) {
  33712. if (this._connectedAnalyser) {
  33713. this._connectedAnalyser.stopDebugCanvas();
  33714. this._connectedAnalyser.dispose();
  33715. this.masterGain.disconnect();
  33716. this.masterGain.connect(this._audioContext.destination);
  33717. this._connectedAnalyser = null;
  33718. }
  33719. this.masterGain.gain.value = 1;
  33720. }
  33721. this.WarnedWebAudioUnsupported = false;
  33722. };
  33723. AudioEngine.prototype.getGlobalVolume = function () {
  33724. if (this.canUseWebAudio && this._audioContextInitialized) {
  33725. return this.masterGain.gain.value;
  33726. }
  33727. else {
  33728. return -1;
  33729. }
  33730. };
  33731. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33732. if (this.canUseWebAudio && this._audioContextInitialized) {
  33733. this.masterGain.gain.value = newVolume;
  33734. }
  33735. };
  33736. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33737. if (this._connectedAnalyser) {
  33738. this._connectedAnalyser.stopDebugCanvas();
  33739. }
  33740. if (this.canUseWebAudio && this._audioContextInitialized) {
  33741. this._connectedAnalyser = analyser;
  33742. this.masterGain.disconnect();
  33743. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33744. }
  33745. };
  33746. return AudioEngine;
  33747. })();
  33748. BABYLON.AudioEngine = AudioEngine;
  33749. })(BABYLON || (BABYLON = {}));
  33750. var BABYLON;
  33751. (function (BABYLON) {
  33752. var Sound = (function () {
  33753. /**
  33754. * Create a sound and attach it to a scene
  33755. * @param name Name of your sound
  33756. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33757. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33758. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33759. */
  33760. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33761. var _this = this;
  33762. this.autoplay = false;
  33763. this.loop = false;
  33764. this.useCustomAttenuation = false;
  33765. this.spatialSound = false;
  33766. this.refDistance = 1;
  33767. this.rolloffFactor = 1;
  33768. this.maxDistance = 100;
  33769. this.distanceModel = "linear";
  33770. this._panningModel = "equalpower";
  33771. this._playbackRate = 1;
  33772. this._streaming = false;
  33773. this._startTime = 0;
  33774. this._startOffset = 0;
  33775. this._position = BABYLON.Vector3.Zero();
  33776. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33777. this._volume = 1;
  33778. this._isLoaded = false;
  33779. this._isReadyToPlay = false;
  33780. this.isPlaying = false;
  33781. this.isPaused = false;
  33782. this._isDirectional = false;
  33783. // Used if you'd like to create a directional sound.
  33784. // If not set, the sound will be omnidirectional
  33785. this._coneInnerAngle = 360;
  33786. this._coneOuterAngle = 360;
  33787. this._coneOuterGain = 0;
  33788. this._isOutputConnected = false;
  33789. this.name = name;
  33790. this._scene = scene;
  33791. this._readyToPlayCallback = readyToPlayCallback;
  33792. // Default custom attenuation function is a linear attenuation
  33793. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33794. if (currentDistance < maxDistance) {
  33795. return currentVolume * (1 - currentDistance / maxDistance);
  33796. }
  33797. else {
  33798. return 0;
  33799. }
  33800. };
  33801. if (options) {
  33802. this.autoplay = options.autoplay || false;
  33803. this.loop = options.loop || false;
  33804. // if volume === 0, we need another way to check this option
  33805. if (options.volume !== undefined) {
  33806. this._volume = options.volume;
  33807. }
  33808. this.spatialSound = options.spatialSound || false;
  33809. this.maxDistance = options.maxDistance || 100;
  33810. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33811. this.rolloffFactor = options.rolloffFactor || 1;
  33812. this.refDistance = options.refDistance || 1;
  33813. this.distanceModel = options.distanceModel || "linear";
  33814. this._playbackRate = options.playbackRate || 1;
  33815. this._streaming = options.streaming || false;
  33816. }
  33817. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33818. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33819. this._soundGain.gain.value = this._volume;
  33820. this._inputAudioNode = this._soundGain;
  33821. this._ouputAudioNode = this._soundGain;
  33822. if (this.spatialSound) {
  33823. this._createSpatialParameters();
  33824. }
  33825. this._scene.mainSoundTrack.AddSound(this);
  33826. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33827. if (urlOrArrayBuffer) {
  33828. // If it's an URL
  33829. if (typeof (urlOrArrayBuffer) === "string") {
  33830. // Loading sound using XHR2
  33831. if (!this._streaming) {
  33832. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33833. }
  33834. else {
  33835. this._htmlAudioElement = new Audio();
  33836. this._htmlAudioElement.src = urlOrArrayBuffer;
  33837. this._htmlAudioElement.controls = false;
  33838. this._htmlAudioElement.loop = this.loop;
  33839. this._htmlAudioElement.crossOrigin = "anonymous";
  33840. this._isReadyToPlay = true;
  33841. document.body.appendChild(this._htmlAudioElement);
  33842. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33843. if (this._readyToPlayCallback) {
  33844. window.setTimeout(function () {
  33845. _this._readyToPlayCallback();
  33846. }, 1000);
  33847. }
  33848. if (this.autoplay) {
  33849. this.play();
  33850. }
  33851. }
  33852. }
  33853. else {
  33854. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33855. this._soundLoaded(urlOrArrayBuffer);
  33856. }
  33857. else {
  33858. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33859. }
  33860. }
  33861. }
  33862. }
  33863. else {
  33864. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33865. this._scene.mainSoundTrack.AddSound(this);
  33866. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33867. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33868. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33869. }
  33870. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33871. if (this._readyToPlayCallback) {
  33872. window.setTimeout(function () {
  33873. _this._readyToPlayCallback();
  33874. }, 1000);
  33875. }
  33876. }
  33877. }
  33878. Sound.prototype.dispose = function () {
  33879. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33880. if (this.isPlaying) {
  33881. this.stop();
  33882. }
  33883. this._isReadyToPlay = false;
  33884. if (this.soundTrackId === -1) {
  33885. this._scene.mainSoundTrack.RemoveSound(this);
  33886. }
  33887. else {
  33888. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33889. }
  33890. if (this._soundGain) {
  33891. this._soundGain.disconnect();
  33892. this._soundGain = null;
  33893. }
  33894. if (this._soundPanner) {
  33895. this._soundPanner.disconnect();
  33896. this._soundPanner = null;
  33897. }
  33898. if (this._soundSource) {
  33899. this._soundSource.disconnect();
  33900. this._soundSource = null;
  33901. }
  33902. this._audioBuffer = null;
  33903. if (this._htmlAudioElement) {
  33904. this._htmlAudioElement.pause();
  33905. this._htmlAudioElement.src = "";
  33906. document.body.removeChild(this._htmlAudioElement);
  33907. }
  33908. if (this._connectedMesh) {
  33909. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33910. this._connectedMesh = null;
  33911. }
  33912. }
  33913. };
  33914. Sound.prototype._soundLoaded = function (audioData) {
  33915. var _this = this;
  33916. this._isLoaded = true;
  33917. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33918. _this._audioBuffer = buffer;
  33919. _this._isReadyToPlay = true;
  33920. if (_this.autoplay) {
  33921. _this.play();
  33922. }
  33923. if (_this._readyToPlayCallback) {
  33924. _this._readyToPlayCallback();
  33925. }
  33926. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33927. };
  33928. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33929. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33930. this._audioBuffer = audioBuffer;
  33931. this._isReadyToPlay = true;
  33932. }
  33933. };
  33934. Sound.prototype.updateOptions = function (options) {
  33935. if (options) {
  33936. this.loop = options.loop || this.loop;
  33937. this.maxDistance = options.maxDistance || this.maxDistance;
  33938. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33939. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33940. this.refDistance = options.refDistance || this.refDistance;
  33941. this.distanceModel = options.distanceModel || this.distanceModel;
  33942. this._playbackRate = options.playbackRate || this._playbackRate;
  33943. this._updateSpatialParameters();
  33944. if (this.isPlaying) {
  33945. if (this._streaming) {
  33946. this._htmlAudioElement.playbackRate = this._playbackRate;
  33947. }
  33948. else {
  33949. this._soundSource.playbackRate.value = this._playbackRate;
  33950. }
  33951. }
  33952. }
  33953. };
  33954. Sound.prototype._createSpatialParameters = function () {
  33955. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33956. if (this._scene.headphone) {
  33957. this._panningModel = "HRTF";
  33958. }
  33959. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33960. this._updateSpatialParameters();
  33961. this._soundPanner.connect(this._ouputAudioNode);
  33962. this._inputAudioNode = this._soundPanner;
  33963. }
  33964. };
  33965. Sound.prototype._updateSpatialParameters = function () {
  33966. if (this.spatialSound) {
  33967. if (this.useCustomAttenuation) {
  33968. // Tricks to disable in a way embedded Web Audio attenuation
  33969. this._soundPanner.distanceModel = "linear";
  33970. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33971. this._soundPanner.refDistance = 1;
  33972. this._soundPanner.rolloffFactor = 1;
  33973. this._soundPanner.panningModel = this._panningModel;
  33974. }
  33975. else {
  33976. this._soundPanner.distanceModel = this.distanceModel;
  33977. this._soundPanner.maxDistance = this.maxDistance;
  33978. this._soundPanner.refDistance = this.refDistance;
  33979. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33980. this._soundPanner.panningModel = this._panningModel;
  33981. }
  33982. }
  33983. };
  33984. Sound.prototype.switchPanningModelToHRTF = function () {
  33985. this._panningModel = "HRTF";
  33986. this._switchPanningModel();
  33987. };
  33988. Sound.prototype.switchPanningModelToEqualPower = function () {
  33989. this._panningModel = "equalpower";
  33990. this._switchPanningModel();
  33991. };
  33992. Sound.prototype._switchPanningModel = function () {
  33993. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33994. this._soundPanner.panningModel = this._panningModel;
  33995. }
  33996. };
  33997. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33998. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33999. if (this._isOutputConnected) {
  34000. this._ouputAudioNode.disconnect();
  34001. }
  34002. this._ouputAudioNode.connect(soundTrackAudioNode);
  34003. this._isOutputConnected = true;
  34004. }
  34005. };
  34006. /**
  34007. * Transform this sound into a directional source
  34008. * @param coneInnerAngle Size of the inner cone in degree
  34009. * @param coneOuterAngle Size of the outer cone in degree
  34010. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34011. */
  34012. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34013. if (coneOuterAngle < coneInnerAngle) {
  34014. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34015. return;
  34016. }
  34017. this._coneInnerAngle = coneInnerAngle;
  34018. this._coneOuterAngle = coneOuterAngle;
  34019. this._coneOuterGain = coneOuterGain;
  34020. this._isDirectional = true;
  34021. if (this.isPlaying && this.loop) {
  34022. this.stop();
  34023. this.play();
  34024. }
  34025. };
  34026. Sound.prototype.setPosition = function (newPosition) {
  34027. this._position = newPosition;
  34028. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34029. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34030. }
  34031. };
  34032. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34033. this._localDirection = newLocalDirection;
  34034. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34035. this._updateDirection();
  34036. }
  34037. };
  34038. Sound.prototype._updateDirection = function () {
  34039. var mat = this._connectedMesh.getWorldMatrix();
  34040. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34041. direction.normalize();
  34042. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34043. };
  34044. Sound.prototype.updateDistanceFromListener = function () {
  34045. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34046. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34047. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34048. }
  34049. };
  34050. Sound.prototype.setAttenuationFunction = function (callback) {
  34051. this._customAttenuationFunction = callback;
  34052. };
  34053. /**
  34054. * Play the sound
  34055. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34056. */
  34057. Sound.prototype.play = function (time) {
  34058. var _this = this;
  34059. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34060. try {
  34061. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34062. if (!this._soundSource || !this._streamingSource) {
  34063. if (this.spatialSound) {
  34064. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34065. if (this._isDirectional) {
  34066. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34067. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34068. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34069. if (this._connectedMesh) {
  34070. this._updateDirection();
  34071. }
  34072. else {
  34073. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34074. }
  34075. }
  34076. }
  34077. }
  34078. if (this._streaming) {
  34079. if (!this._streamingSource) {
  34080. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34081. this._htmlAudioElement.onended = function () { _this._onended(); };
  34082. this._htmlAudioElement.playbackRate = this._playbackRate;
  34083. }
  34084. this._streamingSource.disconnect();
  34085. this._streamingSource.connect(this._inputAudioNode);
  34086. this._htmlAudioElement.play();
  34087. }
  34088. else {
  34089. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34090. this._soundSource.buffer = this._audioBuffer;
  34091. this._soundSource.connect(this._inputAudioNode);
  34092. this._soundSource.loop = this.loop;
  34093. this._soundSource.playbackRate.value = this._playbackRate;
  34094. this._soundSource.onended = function () { _this._onended(); };
  34095. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34096. }
  34097. this._startTime = startTime;
  34098. this.isPlaying = true;
  34099. this.isPaused = false;
  34100. }
  34101. catch (ex) {
  34102. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34103. }
  34104. }
  34105. };
  34106. Sound.prototype._onended = function () {
  34107. this.isPlaying = false;
  34108. if (this.onended) {
  34109. this.onended();
  34110. }
  34111. };
  34112. /**
  34113. * Stop the sound
  34114. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34115. */
  34116. Sound.prototype.stop = function (time) {
  34117. if (this.isPlaying) {
  34118. if (this._streaming) {
  34119. this._htmlAudioElement.pause();
  34120. // Test needed for Firefox or it will generate an Invalid State Error
  34121. if (this._htmlAudioElement.currentTime > 0) {
  34122. this._htmlAudioElement.currentTime = 0;
  34123. }
  34124. }
  34125. else {
  34126. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34127. this._soundSource.stop(stopTime);
  34128. }
  34129. this.isPlaying = false;
  34130. }
  34131. };
  34132. Sound.prototype.pause = function () {
  34133. if (this.isPlaying) {
  34134. if (this._streaming) {
  34135. this._htmlAudioElement.pause();
  34136. }
  34137. else {
  34138. this.stop(0);
  34139. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34140. }
  34141. this.isPaused = true;
  34142. }
  34143. };
  34144. Sound.prototype.setVolume = function (newVolume, time) {
  34145. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34146. if (time) {
  34147. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34148. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  34149. }
  34150. else {
  34151. this._soundGain.gain.value = newVolume;
  34152. }
  34153. }
  34154. this._volume = newVolume;
  34155. };
  34156. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34157. this._playbackRate = newPlaybackRate;
  34158. if (this.isPlaying) {
  34159. if (this._streaming) {
  34160. this._htmlAudioElement.playbackRate = this._playbackRate;
  34161. }
  34162. else {
  34163. this._soundSource.playbackRate.value = this._playbackRate;
  34164. }
  34165. }
  34166. };
  34167. Sound.prototype.getVolume = function () {
  34168. return this._volume;
  34169. };
  34170. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34171. var _this = this;
  34172. this._connectedMesh = meshToConnectTo;
  34173. if (!this.spatialSound) {
  34174. this.spatialSound = true;
  34175. this._createSpatialParameters();
  34176. if (this.isPlaying && this.loop) {
  34177. this.stop();
  34178. this.play();
  34179. }
  34180. }
  34181. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34182. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34183. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34184. };
  34185. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34186. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34187. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34188. this._updateDirection();
  34189. }
  34190. };
  34191. return Sound;
  34192. })();
  34193. BABYLON.Sound = Sound;
  34194. })(BABYLON || (BABYLON = {}));
  34195. var BABYLON;
  34196. (function (BABYLON) {
  34197. var SoundTrack = (function () {
  34198. function SoundTrack(scene, options) {
  34199. this.id = -1;
  34200. this._isMainTrack = false;
  34201. this._isInitialized = false;
  34202. this._scene = scene;
  34203. this.soundCollection = new Array();
  34204. this._options = options;
  34205. if (!this._isMainTrack) {
  34206. this._scene.soundTracks.push(this);
  34207. this.id = this._scene.soundTracks.length - 1;
  34208. }
  34209. }
  34210. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34211. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34212. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34213. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34214. if (this._options) {
  34215. if (this._options.volume) {
  34216. this._outputAudioNode.gain.value = this._options.volume;
  34217. }
  34218. if (this._options.mainTrack) {
  34219. this._isMainTrack = this._options.mainTrack;
  34220. }
  34221. }
  34222. this._isInitialized = true;
  34223. }
  34224. };
  34225. SoundTrack.prototype.dispose = function () {
  34226. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34227. if (this._connectedAnalyser) {
  34228. this._connectedAnalyser.stopDebugCanvas();
  34229. }
  34230. while (this.soundCollection.length) {
  34231. this.soundCollection[0].dispose();
  34232. }
  34233. if (this._outputAudioNode) {
  34234. this._outputAudioNode.disconnect();
  34235. }
  34236. this._outputAudioNode = null;
  34237. }
  34238. };
  34239. SoundTrack.prototype.AddSound = function (sound) {
  34240. if (!this._isInitialized) {
  34241. this._initializeSoundTrackAudioGraph();
  34242. }
  34243. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34244. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34245. }
  34246. if (sound.soundTrackId) {
  34247. if (sound.soundTrackId === -1) {
  34248. this._scene.mainSoundTrack.RemoveSound(sound);
  34249. }
  34250. else {
  34251. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34252. }
  34253. }
  34254. this.soundCollection.push(sound);
  34255. sound.soundTrackId = this.id;
  34256. };
  34257. SoundTrack.prototype.RemoveSound = function (sound) {
  34258. var index = this.soundCollection.indexOf(sound);
  34259. if (index !== -1) {
  34260. this.soundCollection.splice(index, 1);
  34261. }
  34262. };
  34263. SoundTrack.prototype.setVolume = function (newVolume) {
  34264. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34265. this._outputAudioNode.gain.value = newVolume;
  34266. }
  34267. };
  34268. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34269. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34270. for (var i = 0; i < this.soundCollection.length; i++) {
  34271. this.soundCollection[i].switchPanningModelToHRTF();
  34272. }
  34273. }
  34274. };
  34275. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34276. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34277. for (var i = 0; i < this.soundCollection.length; i++) {
  34278. this.soundCollection[i].switchPanningModelToEqualPower();
  34279. }
  34280. }
  34281. };
  34282. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34283. if (this._connectedAnalyser) {
  34284. this._connectedAnalyser.stopDebugCanvas();
  34285. }
  34286. this._connectedAnalyser = analyser;
  34287. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34288. this._outputAudioNode.disconnect();
  34289. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34290. }
  34291. };
  34292. return SoundTrack;
  34293. })();
  34294. BABYLON.SoundTrack = SoundTrack;
  34295. })(BABYLON || (BABYLON = {}));
  34296. var BABYLON;
  34297. (function (BABYLON) {
  34298. var DepthRenderer = (function () {
  34299. function DepthRenderer(scene, type) {
  34300. var _this = this;
  34301. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34302. this._viewMatrix = BABYLON.Matrix.Zero();
  34303. this._projectionMatrix = BABYLON.Matrix.Zero();
  34304. this._transformMatrix = BABYLON.Matrix.Zero();
  34305. this._worldViewProjection = BABYLON.Matrix.Zero();
  34306. this._scene = scene;
  34307. var engine = scene.getEngine();
  34308. // Render target
  34309. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34310. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34311. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34312. this._depthMap.refreshRate = 1;
  34313. this._depthMap.renderParticles = false;
  34314. this._depthMap.renderList = null;
  34315. // set default depth value to 1.0 (far away)
  34316. this._depthMap.onClear = function (engine) {
  34317. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34318. };
  34319. // Custom render function
  34320. var renderSubMesh = function (subMesh) {
  34321. var mesh = subMesh.getRenderingMesh();
  34322. var scene = _this._scene;
  34323. var engine = scene.getEngine();
  34324. // Culling
  34325. engine.setState(subMesh.getMaterial().backFaceCulling);
  34326. // Managing instances
  34327. var batch = mesh._getInstancesRenderList(subMesh._id);
  34328. if (batch.mustReturn) {
  34329. return;
  34330. }
  34331. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34332. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34333. engine.enableEffect(_this._effect);
  34334. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34335. var material = subMesh.getMaterial();
  34336. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34337. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34338. // Alpha test
  34339. if (material && material.needAlphaTesting()) {
  34340. var alphaTexture = material.getAlphaTestTexture();
  34341. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34342. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34343. }
  34344. // Bones
  34345. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34346. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34347. }
  34348. // Draw
  34349. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34350. }
  34351. };
  34352. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34353. var index;
  34354. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34355. renderSubMesh(opaqueSubMeshes.data[index]);
  34356. }
  34357. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34358. renderSubMesh(alphaTestSubMeshes.data[index]);
  34359. }
  34360. };
  34361. }
  34362. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34363. var defines = [];
  34364. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34365. var mesh = subMesh.getMesh();
  34366. var scene = mesh.getScene();
  34367. var material = subMesh.getMaterial();
  34368. // Alpha test
  34369. if (material && material.needAlphaTesting()) {
  34370. defines.push("#define ALPHATEST");
  34371. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34372. attribs.push(BABYLON.VertexBuffer.UVKind);
  34373. defines.push("#define UV1");
  34374. }
  34375. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34376. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34377. defines.push("#define UV2");
  34378. }
  34379. }
  34380. // Bones
  34381. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34382. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34383. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34384. if (mesh.numBoneInfluencers > 4) {
  34385. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34386. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34387. }
  34388. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34389. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34390. }
  34391. else {
  34392. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34393. }
  34394. // Instances
  34395. if (useInstances) {
  34396. defines.push("#define INSTANCES");
  34397. attribs.push("world0");
  34398. attribs.push("world1");
  34399. attribs.push("world2");
  34400. attribs.push("world3");
  34401. }
  34402. // Get correct effect
  34403. var join = defines.join("\n");
  34404. if (this._cachedDefines !== join) {
  34405. this._cachedDefines = join;
  34406. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34407. }
  34408. return this._effect.isReady();
  34409. };
  34410. DepthRenderer.prototype.getDepthMap = function () {
  34411. return this._depthMap;
  34412. };
  34413. // Methods
  34414. DepthRenderer.prototype.dispose = function () {
  34415. this._depthMap.dispose();
  34416. };
  34417. return DepthRenderer;
  34418. })();
  34419. BABYLON.DepthRenderer = DepthRenderer;
  34420. })(BABYLON || (BABYLON = {}));
  34421. var BABYLON;
  34422. (function (BABYLON) {
  34423. var SSAORenderingPipeline = (function (_super) {
  34424. __extends(SSAORenderingPipeline, _super);
  34425. /**
  34426. * @constructor
  34427. * @param {string} name - The rendering pipeline name
  34428. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34429. * @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 }
  34430. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34431. */
  34432. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34433. var _this = this;
  34434. _super.call(this, scene.getEngine(), name);
  34435. // Members
  34436. /**
  34437. * The PassPostProcess id in the pipeline that contains the original scene color
  34438. * @type {string}
  34439. */
  34440. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34441. /**
  34442. * The SSAO PostProcess id in the pipeline
  34443. * @type {string}
  34444. */
  34445. this.SSAORenderEffect = "SSAORenderEffect";
  34446. /**
  34447. * The horizontal blur PostProcess id in the pipeline
  34448. * @type {string}
  34449. */
  34450. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34451. /**
  34452. * The vertical blur PostProcess id in the pipeline
  34453. * @type {string}
  34454. */
  34455. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34456. /**
  34457. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34458. * @type {string}
  34459. */
  34460. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34461. /**
  34462. * The output strength of the SSAO post-process. Default value is 1.0.
  34463. * @type {number}
  34464. */
  34465. this.totalStrength = 1.0;
  34466. /**
  34467. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  34468. * @type {number}
  34469. */
  34470. this.radius = 0.0001;
  34471. /**
  34472. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34473. * Must not be equal to fallOff and superior to fallOff.
  34474. * Default value is 0.975
  34475. * @type {number}
  34476. */
  34477. this.area = 0.0075;
  34478. /**
  34479. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34480. * Must not be equal to area and inferior to area.
  34481. * Default value is 0.0
  34482. * @type {number}
  34483. */
  34484. this.fallOff = 0.000001;
  34485. /**
  34486. * The base color of the SSAO post-process
  34487. * The final result is "base + ssao" between [0, 1]
  34488. * @type {number}
  34489. */
  34490. this.base = 0.5;
  34491. this._firstUpdate = true;
  34492. this._scene = scene;
  34493. // Set up assets
  34494. this._createRandomTexture();
  34495. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34496. var ssaoRatio = ratio.ssaoRatio || ratio;
  34497. var combineRatio = ratio.combineRatio || ratio;
  34498. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34499. this._createSSAOPostProcess(ssaoRatio);
  34500. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34501. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34502. this._createSSAOCombinePostProcess(combineRatio);
  34503. // Set up pipeline
  34504. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34505. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34506. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34507. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34508. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34509. // Finish
  34510. scene.postProcessRenderPipelineManager.addPipeline(this);
  34511. if (cameras)
  34512. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34513. }
  34514. // Public Methods
  34515. /**
  34516. * Returns the horizontal blur PostProcess
  34517. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34518. */
  34519. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34520. return this._blurHPostProcess;
  34521. };
  34522. /**
  34523. * Returns the vertical blur PostProcess
  34524. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34525. */
  34526. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34527. return this._blurVPostProcess;
  34528. };
  34529. /**
  34530. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34531. */
  34532. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34533. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34534. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34535. this._originalColorPostProcess = undefined;
  34536. this._ssaoPostProcess = undefined;
  34537. this._blurHPostProcess = undefined;
  34538. this._blurVPostProcess = undefined;
  34539. this._ssaoCombinePostProcess = undefined;
  34540. this._randomTexture.dispose();
  34541. if (disableDepthRender)
  34542. this._scene.disableDepthRenderer();
  34543. };
  34544. // Private Methods
  34545. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34546. var _this = this;
  34547. var numSamples = 16;
  34548. var sampleSphere = [
  34549. 0.5381, 0.1856, -0.4319,
  34550. 0.1379, 0.2486, 0.4430,
  34551. 0.3371, 0.5679, -0.0057,
  34552. -0.6999, -0.0451, -0.0019,
  34553. 0.0689, -0.1598, -0.8547,
  34554. 0.0560, 0.0069, -0.1843,
  34555. -0.0146, 0.1402, 0.0762,
  34556. 0.0100, -0.1924, -0.0344,
  34557. -0.3577, -0.5301, -0.4358,
  34558. -0.3169, 0.1063, 0.0158,
  34559. 0.0103, -0.5869, 0.0046,
  34560. -0.0897, -0.4940, 0.3287,
  34561. 0.7119, -0.0154, -0.0918,
  34562. -0.0533, 0.0596, -0.5411,
  34563. 0.0352, -0.0631, 0.5460,
  34564. -0.4776, 0.2847, -0.0271
  34565. ];
  34566. var samplesFactor = 1.0 / numSamples;
  34567. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  34568. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  34569. "area", "fallOff", "base"
  34570. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  34571. this._ssaoPostProcess.onApply = function (effect) {
  34572. if (_this._firstUpdate) {
  34573. effect.setArray3("sampleSphere", sampleSphere);
  34574. effect.setFloat("samplesFactor", samplesFactor);
  34575. effect.setFloat("randTextureTiles", 4.0);
  34576. _this._firstUpdate = false;
  34577. }
  34578. effect.setFloat("totalStrength", _this.totalStrength);
  34579. effect.setFloat("radius", _this.radius);
  34580. effect.setFloat("area", _this.area);
  34581. effect.setFloat("fallOff", _this.fallOff);
  34582. effect.setFloat("base", _this.base);
  34583. effect.setTexture("textureSampler", _this._depthTexture);
  34584. effect.setTexture("randomSampler", _this._randomTexture);
  34585. };
  34586. };
  34587. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34588. var _this = this;
  34589. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34590. this._ssaoCombinePostProcess.onApply = function (effect) {
  34591. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34592. };
  34593. };
  34594. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34595. var size = 512;
  34596. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34597. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34598. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34599. var context = this._randomTexture.getContext();
  34600. var rand = function (min, max) {
  34601. return Math.random() * (max - min) + min;
  34602. };
  34603. var randVector = BABYLON.Vector3.Zero();
  34604. for (var x = 0; x < size; x++) {
  34605. for (var y = 0; y < size; y++) {
  34606. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  34607. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  34608. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  34609. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34610. context.fillRect(x, y, 1, 1);
  34611. }
  34612. }
  34613. this._randomTexture.update(false);
  34614. };
  34615. return SSAORenderingPipeline;
  34616. })(BABYLON.PostProcessRenderPipeline);
  34617. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34618. })(BABYLON || (BABYLON = {}));
  34619. var BABYLON;
  34620. (function (BABYLON) {
  34621. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34622. var VolumetricLightScatteringPostProcess = (function (_super) {
  34623. __extends(VolumetricLightScatteringPostProcess, _super);
  34624. /**
  34625. * @constructor
  34626. * @param {string} name - The post-process name
  34627. * @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)
  34628. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34629. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34630. * @param {number} samples - The post-process quality, default 100
  34631. * @param {number} samplingMode - The post-process filtering mode
  34632. * @param {BABYLON.Engine} engine - The babylon engine
  34633. * @param {boolean} reusable - If the post-process is reusable
  34634. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34635. */
  34636. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34637. var _this = this;
  34638. if (samples === void 0) { samples = 100; }
  34639. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34640. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34641. this._screenCoordinates = BABYLON.Vector2.Zero();
  34642. /**
  34643. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34644. * @type {boolean}
  34645. */
  34646. this.useCustomMeshPosition = false;
  34647. /**
  34648. * If the post-process should inverse the light scattering direction
  34649. * @type {boolean}
  34650. */
  34651. this.invert = true;
  34652. /**
  34653. * Set to true to use the diffuseColor instead of the diffuseTexture
  34654. * @type {boolean}
  34655. */
  34656. this.useDiffuseColor = false;
  34657. /**
  34658. * Array containing the excluded meshes not rendered in the internal pass
  34659. */
  34660. this.excludedMeshes = new Array();
  34661. /**
  34662. * Controls the overall intensity of the post-process
  34663. * @type {number}
  34664. */
  34665. this.exposure = 0.3;
  34666. /**
  34667. * Dissipates each sample's contribution in range [0, 1]
  34668. * @type {number}
  34669. */
  34670. this.decay = 0.96815;
  34671. /**
  34672. * Controls the overall intensity of each sample
  34673. * @type {number}
  34674. */
  34675. this.weight = 0.58767;
  34676. /**
  34677. * Controls the density of each sample
  34678. * @type {number}
  34679. */
  34680. this.density = 0.926;
  34681. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34682. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34683. // Configure mesh
  34684. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34685. // Configure
  34686. this._createPass(scene, ratio.passRatio || ratio);
  34687. this.onActivate = function (camera) {
  34688. if (!_this.isSupported) {
  34689. _this.dispose(camera);
  34690. }
  34691. _this.onActivate = null;
  34692. };
  34693. this.onApply = function (effect) {
  34694. _this._updateMeshScreenCoordinates(scene);
  34695. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34696. effect.setFloat("exposure", _this.exposure);
  34697. effect.setFloat("decay", _this.decay);
  34698. effect.setFloat("weight", _this.weight);
  34699. effect.setFloat("density", _this.density);
  34700. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34701. };
  34702. }
  34703. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34704. var mesh = subMesh.getMesh();
  34705. var defines = [];
  34706. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34707. var material = subMesh.getMaterial();
  34708. var needUV = false;
  34709. // Render this.mesh as default
  34710. if (mesh === this.mesh) {
  34711. if (this.useDiffuseColor) {
  34712. defines.push("#define DIFFUSE_COLOR_RENDER");
  34713. }
  34714. else if (material) {
  34715. if (material.diffuseTexture !== undefined) {
  34716. defines.push("#define BASIC_RENDER");
  34717. }
  34718. else {
  34719. defines.push("#define DIFFUSE_COLOR_RENDER");
  34720. }
  34721. }
  34722. defines.push("#define NEED_UV");
  34723. needUV = true;
  34724. }
  34725. // Alpha test
  34726. if (material) {
  34727. if (material.needAlphaTesting()) {
  34728. defines.push("#define ALPHATEST");
  34729. }
  34730. if (material.opacityTexture !== undefined) {
  34731. defines.push("#define OPACITY");
  34732. if (material.opacityTexture.getAlphaFromRGB) {
  34733. defines.push("#define OPACITYRGB");
  34734. }
  34735. if (!needUV) {
  34736. defines.push("#define NEED_UV");
  34737. }
  34738. }
  34739. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34740. attribs.push(BABYLON.VertexBuffer.UVKind);
  34741. defines.push("#define UV1");
  34742. }
  34743. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34744. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34745. defines.push("#define UV2");
  34746. }
  34747. }
  34748. // Bones
  34749. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34750. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34751. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34752. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34753. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34754. }
  34755. else {
  34756. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34757. }
  34758. // Instances
  34759. if (useInstances) {
  34760. defines.push("#define INSTANCES");
  34761. attribs.push("world0");
  34762. attribs.push("world1");
  34763. attribs.push("world2");
  34764. attribs.push("world3");
  34765. }
  34766. // Get correct effect
  34767. var join = defines.join("\n");
  34768. if (this._cachedDefines !== join) {
  34769. this._cachedDefines = join;
  34770. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34771. }
  34772. return this._volumetricLightScatteringPass.isReady();
  34773. };
  34774. /**
  34775. * Sets the new light position for light scattering effect
  34776. * @param {BABYLON.Vector3} The new custom light position
  34777. */
  34778. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34779. this._customMeshPosition = position;
  34780. };
  34781. /**
  34782. * Returns the light position for light scattering effect
  34783. * @return {BABYLON.Vector3} The custom light position
  34784. */
  34785. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34786. return this._customMeshPosition;
  34787. };
  34788. /**
  34789. * Disposes the internal assets and detaches the post-process from the camera
  34790. */
  34791. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34792. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34793. if (rttIndex !== -1) {
  34794. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34795. }
  34796. this._volumetricLightScatteringRTT.dispose();
  34797. _super.prototype.dispose.call(this, camera);
  34798. };
  34799. /**
  34800. * Returns the render target texture used by the post-process
  34801. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34802. */
  34803. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34804. return this._volumetricLightScatteringRTT;
  34805. };
  34806. // Private methods
  34807. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34808. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34809. return true;
  34810. }
  34811. return false;
  34812. };
  34813. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34814. var _this = this;
  34815. var engine = scene.getEngine();
  34816. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34817. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34818. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34819. this._volumetricLightScatteringRTT.renderList = null;
  34820. this._volumetricLightScatteringRTT.renderParticles = false;
  34821. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34822. // Custom render function for submeshes
  34823. var renderSubMesh = function (subMesh) {
  34824. var mesh = subMesh.getRenderingMesh();
  34825. if (_this._meshExcluded(mesh)) {
  34826. return;
  34827. }
  34828. var scene = mesh.getScene();
  34829. var engine = scene.getEngine();
  34830. // Culling
  34831. engine.setState(subMesh.getMaterial().backFaceCulling);
  34832. // Managing instances
  34833. var batch = mesh._getInstancesRenderList(subMesh._id);
  34834. if (batch.mustReturn) {
  34835. return;
  34836. }
  34837. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34838. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34839. engine.enableEffect(_this._volumetricLightScatteringPass);
  34840. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34841. var material = subMesh.getMaterial();
  34842. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34843. // Alpha test
  34844. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34845. var alphaTexture = material.getAlphaTestTexture();
  34846. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34847. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34848. }
  34849. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34850. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34851. if (alphaTexture) {
  34852. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34853. }
  34854. }
  34855. if (material.opacityTexture !== undefined) {
  34856. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34857. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34858. }
  34859. }
  34860. // Bones
  34861. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34862. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34863. }
  34864. // Draw
  34865. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34866. }
  34867. };
  34868. // Render target texture callbacks
  34869. var savedSceneClearColor;
  34870. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34871. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34872. savedSceneClearColor = scene.clearColor;
  34873. scene.clearColor = sceneClearColor;
  34874. };
  34875. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34876. scene.clearColor = savedSceneClearColor;
  34877. };
  34878. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34879. var engine = scene.getEngine();
  34880. var index;
  34881. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34882. renderSubMesh(opaqueSubMeshes.data[index]);
  34883. }
  34884. engine.setAlphaTesting(true);
  34885. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34886. renderSubMesh(alphaTestSubMeshes.data[index]);
  34887. }
  34888. engine.setAlphaTesting(false);
  34889. if (transparentSubMeshes.length) {
  34890. // Sort sub meshes
  34891. for (index = 0; index < transparentSubMeshes.length; index++) {
  34892. var submesh = transparentSubMeshes.data[index];
  34893. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34894. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34895. }
  34896. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34897. sortedArray.sort(function (a, b) {
  34898. // Alpha index first
  34899. if (a._alphaIndex > b._alphaIndex) {
  34900. return 1;
  34901. }
  34902. if (a._alphaIndex < b._alphaIndex) {
  34903. return -1;
  34904. }
  34905. // Then distance to camera
  34906. if (a._distanceToCamera < b._distanceToCamera) {
  34907. return 1;
  34908. }
  34909. if (a._distanceToCamera > b._distanceToCamera) {
  34910. return -1;
  34911. }
  34912. return 0;
  34913. });
  34914. // Render sub meshes
  34915. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34916. for (index = 0; index < sortedArray.length; index++) {
  34917. renderSubMesh(sortedArray[index]);
  34918. }
  34919. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34920. }
  34921. };
  34922. };
  34923. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34924. var transform = scene.getTransformMatrix();
  34925. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  34926. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34927. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34928. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34929. if (this.invert)
  34930. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34931. };
  34932. // Static methods
  34933. /**
  34934. * Creates a default mesh for the Volumeric Light Scattering post-process
  34935. * @param {string} The mesh name
  34936. * @param {BABYLON.Scene} The scene where to create the mesh
  34937. * @return {BABYLON.Mesh} the default mesh
  34938. */
  34939. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34940. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34941. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34942. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34943. return mesh;
  34944. };
  34945. return VolumetricLightScatteringPostProcess;
  34946. })(BABYLON.PostProcess);
  34947. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34948. })(BABYLON || (BABYLON = {}));
  34949. // BABYLON.JS Chromatic Aberration GLSL Shader
  34950. // Author: Olivier Guyot
  34951. // Separates very slightly R, G and B colors on the edges of the screen
  34952. // Inspired by Francois Tarlier & Martins Upitis
  34953. var BABYLON;
  34954. (function (BABYLON) {
  34955. var LensRenderingPipeline = (function (_super) {
  34956. __extends(LensRenderingPipeline, _super);
  34957. /**
  34958. * @constructor
  34959. *
  34960. * Effect parameters are as follow:
  34961. * {
  34962. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34963. * edge_blur: number; // from 0 to x (1 for realism)
  34964. * distortion: number; // from 0 to x (1 for realism)
  34965. * grain_amount: number; // from 0 to 1
  34966. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34967. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34968. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34969. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34970. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34971. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34972. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34973. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34974. * }
  34975. * Note: if an effect parameter is unset, effect is disabled
  34976. *
  34977. * @param {string} name - The rendering pipeline name
  34978. * @param {object} parameters - An object containing all parameters (see above)
  34979. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34980. * @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)
  34981. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34982. */
  34983. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34984. var _this = this;
  34985. if (ratio === void 0) { ratio = 1.0; }
  34986. _super.call(this, scene.getEngine(), name);
  34987. // Lens effects can be of the following:
  34988. // - chromatic aberration (slight shift of RGB colors)
  34989. // - blur on the edge of the lens
  34990. // - lens distortion
  34991. // - depth-of-field blur & highlights enhancing
  34992. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34993. // - grain effect (noise or custom texture)
  34994. // Two additional texture samplers are needed:
  34995. // - depth map (for depth-of-field)
  34996. // - grain texture
  34997. /**
  34998. * The chromatic aberration PostProcess id in the pipeline
  34999. * @type {string}
  35000. */
  35001. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  35002. /**
  35003. * The highlights enhancing PostProcess id in the pipeline
  35004. * @type {string}
  35005. */
  35006. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  35007. /**
  35008. * The depth-of-field PostProcess id in the pipeline
  35009. * @type {string}
  35010. */
  35011. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  35012. this._scene = scene;
  35013. // Fetch texture samplers
  35014. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35015. if (parameters.grain_texture) {
  35016. this._grainTexture = parameters.grain_texture;
  35017. }
  35018. else {
  35019. this._createGrainTexture();
  35020. }
  35021. // save parameters
  35022. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  35023. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  35024. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  35025. this._distortion = parameters.distortion ? parameters.distortion : 0;
  35026. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  35027. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  35028. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  35029. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  35030. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  35031. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  35032. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  35033. // Create effects
  35034. this._createChromaticAberrationPostProcess(ratio);
  35035. this._createHighlightsPostProcess(ratio);
  35036. this._createDepthOfFieldPostProcess(ratio / 4);
  35037. // Set up pipeline
  35038. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  35039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  35040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  35041. if (this._highlightsGain === -1) {
  35042. this._disableEffect(this.HighlightsEnhancingEffect, null);
  35043. }
  35044. // Finish
  35045. scene.postProcessRenderPipelineManager.addPipeline(this);
  35046. if (cameras) {
  35047. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35048. }
  35049. }
  35050. // public methods (self explanatory)
  35051. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35052. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35053. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35054. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35055. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35056. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35057. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35058. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35059. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35060. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35061. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35062. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35063. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35064. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35065. };
  35066. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35067. this._highlightsPostProcess.updateEffect();
  35068. };
  35069. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35070. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35071. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35072. this._highlightsGain = amount;
  35073. };
  35074. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35075. if (this._highlightsGain === -1) {
  35076. this._highlightsGain = 1.0;
  35077. }
  35078. this._highlightsThreshold = amount;
  35079. };
  35080. LensRenderingPipeline.prototype.disableHighlights = function () {
  35081. this._highlightsGain = -1;
  35082. };
  35083. /**
  35084. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35085. */
  35086. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35087. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35088. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35089. this._chromaticAberrationPostProcess = undefined;
  35090. this._highlightsPostProcess = undefined;
  35091. this._depthOfFieldPostProcess = undefined;
  35092. this._grainTexture.dispose();
  35093. if (disableDepthRender)
  35094. this._scene.disableDepthRenderer();
  35095. };
  35096. // colors shifting and distortion
  35097. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35098. var _this = this;
  35099. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35100. [], // samplers
  35101. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35102. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35103. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35104. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35105. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35106. };
  35107. };
  35108. // highlights enhancing
  35109. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35110. var _this = this;
  35111. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35112. [], // samplers
  35113. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35114. this._highlightsPostProcess.onApply = function (effect) {
  35115. effect.setFloat('gain', _this._highlightsGain);
  35116. effect.setFloat('threshold', _this._highlightsThreshold);
  35117. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35118. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35119. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35120. };
  35121. };
  35122. // colors shifting and distortion
  35123. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35124. var _this = this;
  35125. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35126. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35127. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35128. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35129. this._depthOfFieldPostProcess.onApply = function (effect) {
  35130. effect.setTexture("depthSampler", _this._depthTexture);
  35131. effect.setTexture("grainSampler", _this._grainTexture);
  35132. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35133. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35134. effect.setFloat('grain_amount', _this._grainAmount);
  35135. effect.setBool('blur_noise', _this._blurNoise);
  35136. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35137. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35138. effect.setFloat('distortion', _this._distortion);
  35139. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35140. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35141. effect.setFloat('aperture', _this._dofAperture);
  35142. effect.setFloat('darken', _this._dofDarken);
  35143. effect.setFloat('edge_blur', _this._edgeBlur);
  35144. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35145. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35146. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35147. };
  35148. };
  35149. // creates a black and white random noise texture, 512x512
  35150. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35151. var size = 512;
  35152. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35153. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35154. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35155. var context = this._grainTexture.getContext();
  35156. var rand = function (min, max) {
  35157. return Math.random() * (max - min) + min;
  35158. };
  35159. var value;
  35160. for (var x = 0; x < size; x++) {
  35161. for (var y = 0; y < size; y++) {
  35162. value = Math.floor(rand(0.42, 0.58) * 255);
  35163. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35164. context.fillRect(x, y, 1, 1);
  35165. }
  35166. }
  35167. this._grainTexture.update(false);
  35168. };
  35169. return LensRenderingPipeline;
  35170. })(BABYLON.PostProcessRenderPipeline);
  35171. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35172. })(BABYLON || (BABYLON = {}));
  35173. //
  35174. // This post-process allows the modification of rendered colors by using
  35175. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35176. //
  35177. // The object needs to be provided an url to a texture containing the color
  35178. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35179. // Use an image editing software to tweak the LUT to match your needs.
  35180. //
  35181. // For an example of a color LUT, see here:
  35182. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35183. // For explanations on color grading, see here:
  35184. // http://udn.epicgames.com/Three/ColorGrading.html
  35185. //
  35186. var BABYLON;
  35187. (function (BABYLON) {
  35188. var ColorCorrectionPostProcess = (function (_super) {
  35189. __extends(ColorCorrectionPostProcess, _super);
  35190. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35191. var _this = this;
  35192. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35193. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35194. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35195. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35196. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35197. this.onApply = function (effect) {
  35198. effect.setTexture("colorTable", _this._colorTableTexture);
  35199. };
  35200. }
  35201. return ColorCorrectionPostProcess;
  35202. })(BABYLON.PostProcess);
  35203. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35204. })(BABYLON || (BABYLON = {}));
  35205. var BABYLON;
  35206. (function (BABYLON) {
  35207. var AnaglyphFreeCamera = (function (_super) {
  35208. __extends(AnaglyphFreeCamera, _super);
  35209. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35210. _super.call(this, name, position, scene);
  35211. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35212. }
  35213. return AnaglyphFreeCamera;
  35214. })(BABYLON.FreeCamera);
  35215. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35216. var AnaglyphArcRotateCamera = (function (_super) {
  35217. __extends(AnaglyphArcRotateCamera, _super);
  35218. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35219. _super.call(this, name, alpha, beta, radius, target, scene);
  35220. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35221. }
  35222. return AnaglyphArcRotateCamera;
  35223. })(BABYLON.ArcRotateCamera);
  35224. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35225. var AnaglyphGamepadCamera = (function (_super) {
  35226. __extends(AnaglyphGamepadCamera, _super);
  35227. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35228. _super.call(this, name, position, scene);
  35229. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35230. }
  35231. return AnaglyphGamepadCamera;
  35232. })(BABYLON.GamepadCamera);
  35233. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35234. var StereoscopicFreeCamera = (function (_super) {
  35235. __extends(StereoscopicFreeCamera, _super);
  35236. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35237. _super.call(this, name, position, scene);
  35238. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35239. }
  35240. return StereoscopicFreeCamera;
  35241. })(BABYLON.FreeCamera);
  35242. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35243. var StereoscopicArcRotateCamera = (function (_super) {
  35244. __extends(StereoscopicArcRotateCamera, _super);
  35245. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35246. _super.call(this, name, alpha, beta, radius, target, scene);
  35247. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35248. }
  35249. return StereoscopicArcRotateCamera;
  35250. })(BABYLON.ArcRotateCamera);
  35251. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35252. var StereoscopicGamepadCamera = (function (_super) {
  35253. __extends(StereoscopicGamepadCamera, _super);
  35254. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35255. _super.call(this, name, position, scene);
  35256. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35257. }
  35258. return StereoscopicGamepadCamera;
  35259. })(BABYLON.GamepadCamera);
  35260. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35261. })(BABYLON || (BABYLON = {}));
  35262. var BABYLON;
  35263. (function (BABYLON) {
  35264. var HDRRenderingPipeline = (function (_super) {
  35265. __extends(HDRRenderingPipeline, _super);
  35266. /**
  35267. * @constructor
  35268. * @param {string} name - The rendering pipeline name
  35269. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35270. * @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)
  35271. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35272. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35273. */
  35274. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35275. var _this = this;
  35276. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35277. _super.call(this, scene.getEngine(), name);
  35278. /**
  35279. * Public members
  35280. */
  35281. // Gaussian Blur
  35282. /**
  35283. * Gaussian blur coefficient
  35284. * @type {number}
  35285. */
  35286. this.gaussCoeff = 0.3;
  35287. /**
  35288. * Gaussian blur mean
  35289. * @type {number}
  35290. */
  35291. this.gaussMean = 1.0;
  35292. /**
  35293. * Gaussian blur standard deviation
  35294. * @type {number}
  35295. */
  35296. this.gaussStandDev = 0.8;
  35297. /**
  35298. * Gaussian blur multiplier. Multiplies the blur effect
  35299. * @type {number}
  35300. */
  35301. this.gaussMultiplier = 4.0;
  35302. // HDR
  35303. /**
  35304. * Exposure, controls the overall intensity of the pipeline
  35305. * @type {number}
  35306. */
  35307. this.exposure = 1.0;
  35308. /**
  35309. * Minimum luminance that the post-process can output. Luminance is >= 0
  35310. * @type {number}
  35311. */
  35312. this.minimumLuminance = 1.0;
  35313. /**
  35314. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35315. * @type {number}
  35316. */
  35317. this.maximumLuminance = 1e20;
  35318. /**
  35319. * Increase rate for luminance: eye adaptation speed to dark
  35320. * @type {number}
  35321. */
  35322. this.luminanceIncreaserate = 0.5;
  35323. /**
  35324. * Decrease rate for luminance: eye adaptation speed to bright
  35325. * @type {number}
  35326. */
  35327. this.luminanceDecreaseRate = 0.5;
  35328. // Bright pass
  35329. /**
  35330. * Minimum luminance needed to compute HDR
  35331. * @type {number}
  35332. */
  35333. this.brightThreshold = 0.8;
  35334. this._needUpdate = true;
  35335. this._scene = scene;
  35336. // Bright pass
  35337. this._createBrightPassPostProcess(scene, ratio);
  35338. // Down sample X4
  35339. this._createDownSampleX4PostProcess(scene, ratio);
  35340. // Create gaussian blur post-processes
  35341. this._createGaussianBlurPostProcess(scene, ratio);
  35342. // Texture adder
  35343. this._createTextureAdderPostProcess(scene, ratio);
  35344. // Luminance generator
  35345. this._createLuminanceGeneratorPostProcess(scene);
  35346. // HDR
  35347. this._createHDRPostProcess(scene, ratio);
  35348. // Pass postprocess
  35349. if (originalPostProcess === null) {
  35350. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35351. }
  35352. else {
  35353. this._originalPostProcess = originalPostProcess;
  35354. }
  35355. // Configure pipeline
  35356. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35357. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35358. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35359. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35360. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35361. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35362. var addDownSamplerPostProcess = function (id) {
  35363. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35364. };
  35365. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35366. addDownSamplerPostProcess(i);
  35367. }
  35368. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35369. // Finish
  35370. scene.postProcessRenderPipelineManager.addPipeline(this);
  35371. if (cameras !== null) {
  35372. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35373. }
  35374. this.update();
  35375. }
  35376. /**
  35377. * Tells the pipeline to update its post-processes
  35378. */
  35379. HDRRenderingPipeline.prototype.update = function () {
  35380. this._needUpdate = true;
  35381. };
  35382. /**
  35383. * Returns the current calculated luminance
  35384. */
  35385. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35386. return this._hdrCurrentLuminance;
  35387. };
  35388. /**
  35389. * Returns the currently drawn luminance
  35390. */
  35391. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35392. return this._hdrOutputLuminance;
  35393. };
  35394. /**
  35395. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35396. */
  35397. HDRRenderingPipeline.prototype.dispose = function () {
  35398. this._originalPostProcess = undefined;
  35399. this._brightPassPostProcess = undefined;
  35400. this._downSampleX4PostProcess = undefined;
  35401. this._guassianBlurHPostProcess = undefined;
  35402. this._guassianBlurVPostProcess = undefined;
  35403. this._textureAdderPostProcess = undefined;
  35404. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35405. this._downSamplePostProcesses[i] = undefined;
  35406. }
  35407. this._hdrPostProcess = undefined;
  35408. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35409. };
  35410. /**
  35411. * Creates the HDR post-process and computes the luminance adaptation
  35412. */
  35413. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35414. var _this = this;
  35415. var hdrLastLuminance = 0.0;
  35416. this._hdrOutputLuminance = -1.0;
  35417. this._hdrCurrentLuminance = 1.0;
  35418. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35419. this._hdrPostProcess.onApply = function (effect) {
  35420. if (_this._hdrOutputLuminance < 0.0) {
  35421. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35422. }
  35423. else {
  35424. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35425. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35426. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35427. }
  35428. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35429. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35430. }
  35431. else {
  35432. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35433. }
  35434. }
  35435. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35436. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35437. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35438. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35439. effect.setFloat("exposure", _this.exposure);
  35440. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35441. _this._needUpdate = false;
  35442. };
  35443. };
  35444. /**
  35445. * Texture Adder post-process
  35446. */
  35447. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35448. var _this = this;
  35449. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35450. this._textureAdderPostProcess.onApply = function (effect) {
  35451. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35452. };
  35453. };
  35454. /**
  35455. * Down sample X4 post-process
  35456. */
  35457. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35458. var _this = this;
  35459. var downSampleX4Offsets = new Array(32);
  35460. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35461. this._downSampleX4PostProcess.onApply = function (effect) {
  35462. if (_this._needUpdate) {
  35463. var id = 0;
  35464. for (var i = -2; i < 2; i++) {
  35465. for (var j = -2; j < 2; j++) {
  35466. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35467. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35468. id += 2;
  35469. }
  35470. }
  35471. }
  35472. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35473. };
  35474. };
  35475. /**
  35476. * Bright pass post-process
  35477. */
  35478. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35479. var _this = this;
  35480. var brightOffsets = new Array(8);
  35481. var brightPassCallback = function (effect) {
  35482. if (_this._needUpdate) {
  35483. var sU = (1.0 / _this._brightPassPostProcess.width);
  35484. var sV = (1.0 / _this._brightPassPostProcess.height);
  35485. brightOffsets[0] = -0.5 * sU;
  35486. brightOffsets[1] = 0.5 * sV;
  35487. brightOffsets[2] = 0.5 * sU;
  35488. brightOffsets[3] = 0.5 * sV;
  35489. brightOffsets[4] = -0.5 * sU;
  35490. brightOffsets[5] = -0.5 * sV;
  35491. brightOffsets[6] = 0.5 * sU;
  35492. brightOffsets[7] = -0.5 * sV;
  35493. }
  35494. effect.setArray2("dsOffsets", brightOffsets);
  35495. effect.setFloat("brightThreshold", _this.brightThreshold);
  35496. };
  35497. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35498. this._brightPassPostProcess.onApply = brightPassCallback;
  35499. };
  35500. /**
  35501. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35502. */
  35503. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35504. var _this = this;
  35505. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35506. var luminanceOffsets = new Array(8);
  35507. var downSampleOffsets = new Array(18);
  35508. var halfDestPixelSize;
  35509. this._downSamplePostProcesses = new Array(lumSteps);
  35510. // Utils for luminance
  35511. var luminanceUpdateSourceOffsets = function (width, height) {
  35512. var sU = (1.0 / width);
  35513. var sV = (1.0 / height);
  35514. luminanceOffsets[0] = -0.5 * sU;
  35515. luminanceOffsets[1] = 0.5 * sV;
  35516. luminanceOffsets[2] = 0.5 * sU;
  35517. luminanceOffsets[3] = 0.5 * sV;
  35518. luminanceOffsets[4] = -0.5 * sU;
  35519. luminanceOffsets[5] = -0.5 * sV;
  35520. luminanceOffsets[6] = 0.5 * sU;
  35521. luminanceOffsets[7] = -0.5 * sV;
  35522. };
  35523. var luminanceUpdateDestOffsets = function (width, height) {
  35524. var id = 0;
  35525. for (var x = -1; x < 2; x++) {
  35526. for (var y = -1; y < 2; y++) {
  35527. downSampleOffsets[id] = (x) / width;
  35528. downSampleOffsets[id + 1] = (y) / height;
  35529. id += 2;
  35530. }
  35531. }
  35532. };
  35533. // Luminance callback
  35534. var luminanceCallback = function (effect) {
  35535. if (_this._needUpdate) {
  35536. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35537. }
  35538. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35539. effect.setArray2("lumOffsets", luminanceOffsets);
  35540. };
  35541. // Down sample callbacks
  35542. var downSampleCallback = function (indice) {
  35543. var i = indice;
  35544. return function (effect) {
  35545. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35546. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35547. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35548. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35549. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35550. effect.setArray2("dsOffsets", downSampleOffsets);
  35551. };
  35552. };
  35553. var downSampleAfterRenderCallback = function (effect) {
  35554. // Unpack result
  35555. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35556. 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);
  35557. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35558. };
  35559. // Create luminance post-process
  35560. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35561. 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);
  35562. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35563. // Create down sample post-processes
  35564. for (var i = lumSteps - 2; i >= 0; i--) {
  35565. var length = Math.pow(3, i);
  35566. ratio = { width: length, height: length };
  35567. var defines = "#define DOWN_SAMPLE\n";
  35568. if (i === 0) {
  35569. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35570. }
  35571. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35572. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35573. if (i === 0) {
  35574. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35575. }
  35576. }
  35577. };
  35578. /**
  35579. * Gaussian blur post-processes. Horizontal and Vertical
  35580. */
  35581. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35582. var _this = this;
  35583. var blurOffsetsW = new Array(9);
  35584. var blurOffsetsH = new Array(9);
  35585. var blurWeights = new Array(9);
  35586. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  35587. // Utils for gaussian blur
  35588. var calculateBlurOffsets = function (height) {
  35589. var lastOutputDimensions = {
  35590. width: scene.getEngine().getRenderWidth(),
  35591. height: scene.getEngine().getRenderHeight()
  35592. };
  35593. for (var i = 0; i < 9; i++) {
  35594. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35595. if (height) {
  35596. blurOffsetsH[i] = value;
  35597. }
  35598. else {
  35599. blurOffsetsW[i] = value;
  35600. }
  35601. }
  35602. };
  35603. var calculateWeights = function () {
  35604. var x = 0.0;
  35605. for (var i = 0; i < 9; i++) {
  35606. x = (i - 4.0) / 4.0;
  35607. 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));
  35608. }
  35609. };
  35610. // Callback
  35611. var gaussianBlurCallback = function (height) {
  35612. return function (effect) {
  35613. if (_this._needUpdate) {
  35614. calculateWeights();
  35615. calculateBlurOffsets(height);
  35616. }
  35617. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35618. effect.setArray("blurWeights", blurWeights);
  35619. effect.setFloat("multiplier", _this.gaussMultiplier);
  35620. };
  35621. };
  35622. // Create horizontal gaussian blur post-processes
  35623. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35624. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35625. // Create vertical gaussian blur post-process
  35626. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35627. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35628. };
  35629. // Luminance generator
  35630. HDRRenderingPipeline.LUM_STEPS = 6;
  35631. return HDRRenderingPipeline;
  35632. })(BABYLON.PostProcessRenderPipeline);
  35633. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35634. })(BABYLON || (BABYLON = {}));
  35635. var BABYLON;
  35636. (function (BABYLON) {
  35637. var FaceAdjacencies = (function () {
  35638. function FaceAdjacencies() {
  35639. this.edges = new Array();
  35640. this.edgesConnectedCount = 0;
  35641. }
  35642. return FaceAdjacencies;
  35643. })();
  35644. var EdgesRenderer = (function () {
  35645. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35646. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35647. if (epsilon === void 0) { epsilon = 0.95; }
  35648. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35649. this._linesPositions = new Array();
  35650. this._linesNormals = new Array();
  35651. this._linesIndices = new Array();
  35652. this._buffers = new Array();
  35653. this._checkVerticesInsteadOfIndices = false;
  35654. this._source = source;
  35655. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35656. this._epsilon = epsilon;
  35657. this._prepareRessources();
  35658. this._generateEdgesLines();
  35659. }
  35660. EdgesRenderer.prototype._prepareRessources = function () {
  35661. if (this._lineShader) {
  35662. return;
  35663. }
  35664. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35665. attributes: ["position", "normal"],
  35666. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35667. });
  35668. this._lineShader.disableDepthWrite = true;
  35669. this._lineShader.backFaceCulling = false;
  35670. };
  35671. EdgesRenderer.prototype.dispose = function () {
  35672. this._vb0.dispose();
  35673. this._vb1.dispose();
  35674. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35675. this._lineShader.dispose();
  35676. };
  35677. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35678. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35679. return 0;
  35680. }
  35681. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35682. return 1;
  35683. }
  35684. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35685. return 2;
  35686. }
  35687. return -1;
  35688. };
  35689. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35690. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35691. return 0;
  35692. }
  35693. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35694. return 1;
  35695. }
  35696. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35697. return 2;
  35698. }
  35699. return -1;
  35700. };
  35701. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35702. var needToCreateLine;
  35703. if (edge === undefined) {
  35704. needToCreateLine = true;
  35705. }
  35706. else {
  35707. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35708. needToCreateLine = dotProduct < this._epsilon;
  35709. }
  35710. if (needToCreateLine) {
  35711. var offset = this._linesPositions.length / 3;
  35712. var normal = p0.subtract(p1);
  35713. normal.normalize();
  35714. // Positions
  35715. this._linesPositions.push(p0.x);
  35716. this._linesPositions.push(p0.y);
  35717. this._linesPositions.push(p0.z);
  35718. this._linesPositions.push(p0.x);
  35719. this._linesPositions.push(p0.y);
  35720. this._linesPositions.push(p0.z);
  35721. this._linesPositions.push(p1.x);
  35722. this._linesPositions.push(p1.y);
  35723. this._linesPositions.push(p1.z);
  35724. this._linesPositions.push(p1.x);
  35725. this._linesPositions.push(p1.y);
  35726. this._linesPositions.push(p1.z);
  35727. // Normals
  35728. this._linesNormals.push(p1.x);
  35729. this._linesNormals.push(p1.y);
  35730. this._linesNormals.push(p1.z);
  35731. this._linesNormals.push(-1);
  35732. this._linesNormals.push(p1.x);
  35733. this._linesNormals.push(p1.y);
  35734. this._linesNormals.push(p1.z);
  35735. this._linesNormals.push(1);
  35736. this._linesNormals.push(p0.x);
  35737. this._linesNormals.push(p0.y);
  35738. this._linesNormals.push(p0.z);
  35739. this._linesNormals.push(-1);
  35740. this._linesNormals.push(p0.x);
  35741. this._linesNormals.push(p0.y);
  35742. this._linesNormals.push(p0.z);
  35743. this._linesNormals.push(1);
  35744. // Indices
  35745. this._linesIndices.push(offset);
  35746. this._linesIndices.push(offset + 1);
  35747. this._linesIndices.push(offset + 2);
  35748. this._linesIndices.push(offset);
  35749. this._linesIndices.push(offset + 2);
  35750. this._linesIndices.push(offset + 3);
  35751. }
  35752. };
  35753. EdgesRenderer.prototype._generateEdgesLines = function () {
  35754. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35755. var indices = this._source.getIndices();
  35756. // First let's find adjacencies
  35757. var adjacencies = new Array();
  35758. var faceNormals = new Array();
  35759. var index;
  35760. var faceAdjacencies;
  35761. // Prepare faces
  35762. for (index = 0; index < indices.length; index += 3) {
  35763. faceAdjacencies = new FaceAdjacencies();
  35764. var p0Index = indices[index];
  35765. var p1Index = indices[index + 1];
  35766. var p2Index = indices[index + 2];
  35767. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35768. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35769. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35770. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35771. faceNormal.normalize();
  35772. faceNormals.push(faceNormal);
  35773. adjacencies.push(faceAdjacencies);
  35774. }
  35775. // Scan
  35776. for (index = 0; index < adjacencies.length; index++) {
  35777. faceAdjacencies = adjacencies[index];
  35778. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35779. var otherFaceAdjacencies = adjacencies[otherIndex];
  35780. if (faceAdjacencies.edgesConnectedCount === 3) {
  35781. break;
  35782. }
  35783. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35784. continue;
  35785. }
  35786. var otherP0 = indices[otherIndex * 3];
  35787. var otherP1 = indices[otherIndex * 3 + 1];
  35788. var otherP2 = indices[otherIndex * 3 + 2];
  35789. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35790. var otherEdgeIndex;
  35791. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35792. continue;
  35793. }
  35794. switch (edgeIndex) {
  35795. case 0:
  35796. if (this._checkVerticesInsteadOfIndices) {
  35797. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35798. }
  35799. else {
  35800. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35801. }
  35802. break;
  35803. case 1:
  35804. if (this._checkVerticesInsteadOfIndices) {
  35805. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35806. }
  35807. else {
  35808. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35809. }
  35810. break;
  35811. case 2:
  35812. if (this._checkVerticesInsteadOfIndices) {
  35813. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35814. }
  35815. else {
  35816. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35817. }
  35818. break;
  35819. }
  35820. if (otherEdgeIndex === -1) {
  35821. continue;
  35822. }
  35823. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35824. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35825. faceAdjacencies.edgesConnectedCount++;
  35826. otherFaceAdjacencies.edgesConnectedCount++;
  35827. if (faceAdjacencies.edgesConnectedCount === 3) {
  35828. break;
  35829. }
  35830. }
  35831. }
  35832. }
  35833. // Create lines
  35834. for (index = 0; index < adjacencies.length; index++) {
  35835. // 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
  35836. var current = adjacencies[index];
  35837. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35838. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35839. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35840. }
  35841. // Merge into a single mesh
  35842. var engine = this._source.getScene().getEngine();
  35843. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35844. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35845. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35846. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35847. this._ib = engine.createIndexBuffer(this._linesIndices);
  35848. this._indicesCount = this._linesIndices.length;
  35849. };
  35850. EdgesRenderer.prototype.render = function () {
  35851. if (!this._lineShader.isReady()) {
  35852. return;
  35853. }
  35854. var scene = this._source.getScene();
  35855. var engine = scene.getEngine();
  35856. this._lineShader._preBind();
  35857. // VBOs
  35858. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35859. scene.resetCachedMaterial();
  35860. this._lineShader.setColor4("color", this._source.edgesColor);
  35861. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35862. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35863. this._lineShader.bind(this._source.getWorldMatrix());
  35864. // Draw order
  35865. engine.draw(true, 0, this._indicesCount);
  35866. this._lineShader.unbind();
  35867. engine.setDepthWrite(true);
  35868. };
  35869. return EdgesRenderer;
  35870. })();
  35871. BABYLON.EdgesRenderer = EdgesRenderer;
  35872. })(BABYLON || (BABYLON = {}));
  35873. var BABYLON;
  35874. (function (BABYLON) {
  35875. (function (TonemappingOperator) {
  35876. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35877. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35878. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35879. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35880. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35881. var TonemappingOperator = BABYLON.TonemappingOperator;
  35882. ;
  35883. var TonemapPostProcess = (function (_super) {
  35884. __extends(TonemapPostProcess, _super);
  35885. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35886. var _this = this;
  35887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35888. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35889. this._operator = operator;
  35890. this._exposureAdjustment = exposureAdjustment;
  35891. var params = ["_ExposureAdjustment"];
  35892. var defines = "#define ";
  35893. if (operator === TonemappingOperator.Hable)
  35894. defines += "HABLE_TONEMAPPING";
  35895. else if (operator === TonemappingOperator.Reinhard)
  35896. defines += "REINHARD_TONEMAPPING";
  35897. else if (operator === TonemappingOperator.HejiDawson)
  35898. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35899. else if (operator === TonemappingOperator.Photographic)
  35900. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35901. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35902. this.onApply = function (effect) {
  35903. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35904. };
  35905. }
  35906. return TonemapPostProcess;
  35907. })(BABYLON.PostProcess);
  35908. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35909. })(BABYLON || (BABYLON = {}));
  35910. var BABYLON;
  35911. (function (BABYLON) {
  35912. var ReflectionProbe = (function () {
  35913. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35914. var _this = this;
  35915. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35916. this.name = name;
  35917. this._viewMatrix = BABYLON.Matrix.Identity();
  35918. this._target = BABYLON.Vector3.Zero();
  35919. this._add = BABYLON.Vector3.Zero();
  35920. this.position = BABYLON.Vector3.Zero();
  35921. this._scene = scene;
  35922. this._scene.reflectionProbes.push(this);
  35923. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35924. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35925. switch (faceIndex) {
  35926. case 0:
  35927. _this._add.copyFromFloats(1, 0, 0);
  35928. break;
  35929. case 1:
  35930. _this._add.copyFromFloats(-1, 0, 0);
  35931. break;
  35932. case 2:
  35933. _this._add.copyFromFloats(0, -1, 0);
  35934. break;
  35935. case 3:
  35936. _this._add.copyFromFloats(0, 1, 0);
  35937. break;
  35938. case 4:
  35939. _this._add.copyFromFloats(0, 0, 1);
  35940. break;
  35941. case 5:
  35942. _this._add.copyFromFloats(0, 0, -1);
  35943. break;
  35944. }
  35945. if (_this._attachedMesh) {
  35946. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35947. }
  35948. _this.position.addToRef(_this._add, _this._target);
  35949. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35950. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35951. };
  35952. this._renderTargetTexture.onAfterUnbind = function () {
  35953. scene.updateTransformMatrix(true);
  35954. };
  35955. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35956. }
  35957. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35958. get: function () {
  35959. return this._renderTargetTexture.refreshRate;
  35960. },
  35961. set: function (value) {
  35962. this._renderTargetTexture.refreshRate = value;
  35963. },
  35964. enumerable: true,
  35965. configurable: true
  35966. });
  35967. ReflectionProbe.prototype.getScene = function () {
  35968. return this._scene;
  35969. };
  35970. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35971. get: function () {
  35972. return this._renderTargetTexture;
  35973. },
  35974. enumerable: true,
  35975. configurable: true
  35976. });
  35977. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35978. get: function () {
  35979. return this._renderTargetTexture.renderList;
  35980. },
  35981. enumerable: true,
  35982. configurable: true
  35983. });
  35984. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35985. this._attachedMesh = mesh;
  35986. };
  35987. ReflectionProbe.prototype.dispose = function () {
  35988. var index = this._scene.reflectionProbes.indexOf(this);
  35989. if (index !== -1) {
  35990. // Remove from the scene if found
  35991. this._scene.reflectionProbes.splice(index, 1);
  35992. }
  35993. };
  35994. return ReflectionProbe;
  35995. })();
  35996. BABYLON.ReflectionProbe = ReflectionProbe;
  35997. })(BABYLON || (BABYLON = {}));
  35998. var BABYLON;
  35999. (function (BABYLON) {
  36000. var SolidParticle = (function () {
  36001. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  36002. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  36003. this.position = BABYLON.Vector3.Zero(); // position
  36004. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36005. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36006. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36007. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36008. this.alive = true; // alive
  36009. this.idx = particleIndex;
  36010. this._pos = positionIndex;
  36011. this._model = model;
  36012. this.shapeId = shapeId;
  36013. this.idxInShape = idxInShape;
  36014. }
  36015. return SolidParticle;
  36016. })();
  36017. BABYLON.SolidParticle = SolidParticle;
  36018. var ModelShape = (function () {
  36019. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36020. this.shapeID = id;
  36021. this._shape = shape;
  36022. this._shapeUV = shapeUV;
  36023. this._positionFunction = posFunction;
  36024. this._vertexFunction = vtxFunction;
  36025. }
  36026. return ModelShape;
  36027. })();
  36028. BABYLON.ModelShape = ModelShape;
  36029. })(BABYLON || (BABYLON = {}));
  36030. var BABYLON;
  36031. (function (BABYLON) {
  36032. var SolidParticleSystem = (function () {
  36033. function SolidParticleSystem(name, scene, options) {
  36034. // public members
  36035. this.particles = new Array();
  36036. this.nbParticles = 0;
  36037. this.billboard = false;
  36038. this.counter = 0;
  36039. this.vars = {};
  36040. this._positions = new Array();
  36041. this._indices = new Array();
  36042. this._normals = new Array();
  36043. this._colors = new Array();
  36044. this._uvs = new Array();
  36045. this._index = 0; // indices index
  36046. this._updatable = true;
  36047. this._pickable = false;
  36048. this._alwaysVisible = false;
  36049. this._shapeCounter = 0;
  36050. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36051. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36052. this._computeParticleColor = true;
  36053. this._computeParticleTexture = true;
  36054. this._computeParticleRotation = true;
  36055. this._computeParticleVertex = false;
  36056. this._cam_axisZ = BABYLON.Vector3.Zero();
  36057. this._cam_axisY = BABYLON.Vector3.Zero();
  36058. this._cam_axisX = BABYLON.Vector3.Zero();
  36059. this._axisX = BABYLON.Axis.X;
  36060. this._axisY = BABYLON.Axis.Y;
  36061. this._axisZ = BABYLON.Axis.Z;
  36062. this._fakeCamPos = BABYLON.Vector3.Zero();
  36063. this._rotMatrix = new BABYLON.Matrix();
  36064. this._invertMatrix = new BABYLON.Matrix();
  36065. this._rotated = BABYLON.Vector3.Zero();
  36066. this._quaternion = new BABYLON.Quaternion();
  36067. this._vertex = BABYLON.Vector3.Zero();
  36068. this._normal = BABYLON.Vector3.Zero();
  36069. this._yaw = 0.0;
  36070. this._pitch = 0.0;
  36071. this._roll = 0.0;
  36072. this._halfroll = 0.0;
  36073. this._halfpitch = 0.0;
  36074. this._halfyaw = 0.0;
  36075. this._sinRoll = 0.0;
  36076. this._cosRoll = 0.0;
  36077. this._sinPitch = 0.0;
  36078. this._cosPitch = 0.0;
  36079. this._sinYaw = 0.0;
  36080. this._cosYaw = 0.0;
  36081. this._w = 0.0;
  36082. this.name = name;
  36083. this._scene = scene;
  36084. this._camera = scene.activeCamera;
  36085. this._pickable = options ? options.isPickable : false;
  36086. if (options && options.updatable) {
  36087. this._updatable = options.updatable;
  36088. }
  36089. else {
  36090. this._updatable = true;
  36091. }
  36092. if (this._pickable) {
  36093. this.pickedParticles = [];
  36094. }
  36095. }
  36096. // build the SPS mesh : returns the mesh
  36097. SolidParticleSystem.prototype.buildMesh = function () {
  36098. if (this.nbParticles === 0) {
  36099. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36100. this.addShape(triangle, 1);
  36101. triangle.dispose();
  36102. }
  36103. this._positions32 = new Float32Array(this._positions);
  36104. this._uvs32 = new Float32Array(this._uvs);
  36105. this._colors32 = new Float32Array(this._colors);
  36106. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36107. this._normals32 = new Float32Array(this._normals);
  36108. this._fixedNormal32 = new Float32Array(this._normals);
  36109. var vertexData = new BABYLON.VertexData();
  36110. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36111. vertexData.indices = this._indices;
  36112. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36113. if (this._uvs32) {
  36114. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36115. ;
  36116. }
  36117. if (this._colors32) {
  36118. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36119. }
  36120. var mesh = new BABYLON.Mesh(name, this._scene);
  36121. vertexData.applyToMesh(mesh, this._updatable);
  36122. this.mesh = mesh;
  36123. this.mesh.isPickable = this._pickable;
  36124. // free memory
  36125. this._positions = null;
  36126. this._normals = null;
  36127. this._uvs = null;
  36128. this._colors = null;
  36129. if (!this._updatable) {
  36130. this.particles.length = 0;
  36131. }
  36132. return mesh;
  36133. };
  36134. //reset copy
  36135. SolidParticleSystem.prototype._resetCopy = function () {
  36136. this._copy.position.x = 0;
  36137. this._copy.position.y = 0;
  36138. this._copy.position.z = 0;
  36139. this._copy.rotation.x = 0;
  36140. this._copy.rotation.y = 0;
  36141. this._copy.rotation.z = 0;
  36142. this._copy.quaternion = null;
  36143. this._copy.scale.x = 1;
  36144. this._copy.scale.y = 1;
  36145. this._copy.scale.z = 1;
  36146. this._copy.uvs.x = 0;
  36147. this._copy.uvs.y = 0;
  36148. this._copy.uvs.z = 1;
  36149. this._copy.uvs.w = 1;
  36150. this._copy.color = null;
  36151. };
  36152. // _meshBuilder : inserts the shape model in the global SPS mesh
  36153. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36154. var i;
  36155. var u = 0;
  36156. var c = 0;
  36157. this._resetCopy();
  36158. if (options && options.positionFunction) {
  36159. options.positionFunction(this._copy, idx, idxInShape);
  36160. }
  36161. if (this._copy.quaternion) {
  36162. this._quaternion.x = this._copy.quaternion.x;
  36163. this._quaternion.y = this._copy.quaternion.y;
  36164. this._quaternion.z = this._copy.quaternion.z;
  36165. this._quaternion.w = this._copy.quaternion.w;
  36166. }
  36167. else {
  36168. this._yaw = this._copy.rotation.y;
  36169. this._pitch = this._copy.rotation.x;
  36170. this._roll = this._copy.rotation.z;
  36171. this._quaternionRotationYPR();
  36172. }
  36173. this._quaternionToRotationMatrix();
  36174. for (i = 0; i < shape.length; i++) {
  36175. this._vertex.x = shape[i].x;
  36176. this._vertex.y = shape[i].y;
  36177. this._vertex.z = shape[i].z;
  36178. if (options && options.vertexFunction) {
  36179. options.vertexFunction(this._copy, this._vertex, i);
  36180. }
  36181. this._vertex.x *= this._copy.scale.x;
  36182. this._vertex.y *= this._copy.scale.y;
  36183. this._vertex.z *= this._copy.scale.z;
  36184. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36185. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36186. if (meshUV) {
  36187. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  36188. u += 2;
  36189. }
  36190. if (this._copy.color) {
  36191. this._color = this._copy.color;
  36192. }
  36193. else if (meshCol && meshCol[c]) {
  36194. this._color.r = meshCol[c];
  36195. this._color.g = meshCol[c + 1];
  36196. this._color.b = meshCol[c + 2];
  36197. this._color.a = meshCol[c + 3];
  36198. }
  36199. else {
  36200. this._color.r = 1;
  36201. this._color.g = 1;
  36202. this._color.b = 1;
  36203. this._color.a = 1;
  36204. }
  36205. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36206. c += 4;
  36207. }
  36208. for (i = 0; i < meshInd.length; i++) {
  36209. indices.push(p + meshInd[i]);
  36210. }
  36211. if (this._pickable) {
  36212. var nbfaces = meshInd.length / 3;
  36213. for (i = 0; i < nbfaces; i++) {
  36214. this.pickedParticles.push({ idx: idx, faceId: i });
  36215. }
  36216. }
  36217. };
  36218. // returns a shape array from positions array
  36219. SolidParticleSystem.prototype._posToShape = function (positions) {
  36220. var shape = [];
  36221. for (var i = 0; i < positions.length; i += 3) {
  36222. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36223. }
  36224. return shape;
  36225. };
  36226. // returns a shapeUV array from a Vector4 uvs
  36227. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36228. var shapeUV = [];
  36229. if (uvs) {
  36230. for (var i = 0; i < uvs.length; i++)
  36231. shapeUV.push(uvs[i]);
  36232. }
  36233. return shapeUV;
  36234. };
  36235. // adds a new particle object in the particles array
  36236. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36237. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36238. };
  36239. // add solid particles from a shape model in the particles array
  36240. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36241. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36242. var meshInd = mesh.getIndices();
  36243. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36244. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36245. var shape = this._posToShape(meshPos);
  36246. var shapeUV = this._uvsToShapeUV(meshUV);
  36247. var posfunc = options ? options.positionFunction : null;
  36248. var vtxfunc = options ? options.vertexFunction : null;
  36249. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36250. // particles
  36251. var idx = this.nbParticles;
  36252. for (var i = 0; i < nb; i++) {
  36253. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36254. if (this._updatable) {
  36255. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36256. }
  36257. this._index += shape.length;
  36258. idx++;
  36259. }
  36260. this.nbParticles += nb;
  36261. this._shapeCounter++;
  36262. return this._shapeCounter;
  36263. };
  36264. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36265. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36266. this._resetCopy();
  36267. if (particle._model._positionFunction) {
  36268. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36269. }
  36270. if (this._copy.quaternion) {
  36271. this._quaternion.x = this._copy.quaternion.x;
  36272. this._quaternion.y = this._copy.quaternion.y;
  36273. this._quaternion.z = this._copy.quaternion.z;
  36274. this._quaternion.w = this._copy.quaternion.w;
  36275. }
  36276. else {
  36277. this._yaw = this._copy.rotation.y;
  36278. this._pitch = this._copy.rotation.x;
  36279. this._roll = this._copy.rotation.z;
  36280. this._quaternionRotationYPR();
  36281. }
  36282. this._quaternionToRotationMatrix();
  36283. this._shape = particle._model._shape;
  36284. for (var pt = 0; pt < this._shape.length; pt++) {
  36285. this._vertex.x = this._shape[pt].x;
  36286. this._vertex.y = this._shape[pt].y;
  36287. this._vertex.z = this._shape[pt].z;
  36288. if (particle._model._vertexFunction) {
  36289. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36290. }
  36291. this._vertex.x *= this._copy.scale.x;
  36292. this._vertex.y *= this._copy.scale.y;
  36293. this._vertex.z *= this._copy.scale.z;
  36294. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36295. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36296. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36297. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36298. }
  36299. particle.position.x = 0;
  36300. particle.position.y = 0;
  36301. particle.position.z = 0;
  36302. particle.rotation.x = 0;
  36303. particle.rotation.y = 0;
  36304. particle.rotation.z = 0;
  36305. particle.quaternion = null;
  36306. particle.scale.x = 1;
  36307. particle.scale.y = 1;
  36308. particle.scale.z = 1;
  36309. };
  36310. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36311. SolidParticleSystem.prototype.rebuildMesh = function () {
  36312. for (var p = 0; p < this.particles.length; p++) {
  36313. this._rebuildParticle(this.particles[p]);
  36314. }
  36315. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36316. };
  36317. // sets all the particles : updates the VBO
  36318. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36319. if (start === void 0) { start = 0; }
  36320. if (end === void 0) { end = this.nbParticles - 1; }
  36321. if (update === void 0) { update = true; }
  36322. if (!this._updatable) {
  36323. return;
  36324. }
  36325. // custom beforeUpdate
  36326. this.beforeUpdateParticles(start, end, update);
  36327. this._cam_axisX.x = 1;
  36328. this._cam_axisX.y = 0;
  36329. this._cam_axisX.z = 0;
  36330. this._cam_axisY.x = 0;
  36331. this._cam_axisY.y = 1;
  36332. this._cam_axisY.z = 0;
  36333. this._cam_axisZ.x = 0;
  36334. this._cam_axisZ.y = 0;
  36335. this._cam_axisZ.z = 1;
  36336. // if the particles will always face the camera
  36337. if (this.billboard) {
  36338. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36339. this._yaw = this.mesh.rotation.y;
  36340. this._pitch = this.mesh.rotation.x;
  36341. this._roll = this.mesh.rotation.z;
  36342. this._quaternionRotationYPR();
  36343. this._quaternionToRotationMatrix();
  36344. this._rotMatrix.invertToRef(this._invertMatrix);
  36345. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36346. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36347. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36348. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36349. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36350. this._cam_axisY.normalize();
  36351. this._cam_axisX.normalize();
  36352. this._cam_axisZ.normalize();
  36353. }
  36354. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36355. var idx = 0;
  36356. var index = 0;
  36357. var colidx = 0;
  36358. var colorIndex = 0;
  36359. var uvidx = 0;
  36360. var uvIndex = 0;
  36361. // particle loop
  36362. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36363. for (var p = start; p <= end; p++) {
  36364. this._particle = this.particles[p];
  36365. this._shape = this._particle._model._shape;
  36366. this._shapeUV = this._particle._model._shapeUV;
  36367. // call to custom user function to update the particle properties
  36368. this.updateParticle(this._particle);
  36369. // particle rotation matrix
  36370. if (this.billboard) {
  36371. this._particle.rotation.x = 0.0;
  36372. this._particle.rotation.y = 0.0;
  36373. }
  36374. if (this._computeParticleRotation) {
  36375. if (this._particle.quaternion) {
  36376. this._quaternion.x = this._particle.quaternion.x;
  36377. this._quaternion.y = this._particle.quaternion.y;
  36378. this._quaternion.z = this._particle.quaternion.z;
  36379. this._quaternion.w = this._particle.quaternion.w;
  36380. }
  36381. else {
  36382. this._yaw = this._particle.rotation.y;
  36383. this._pitch = this._particle.rotation.x;
  36384. this._roll = this._particle.rotation.z;
  36385. this._quaternionRotationYPR();
  36386. }
  36387. this._quaternionToRotationMatrix();
  36388. }
  36389. for (var pt = 0; pt < this._shape.length; pt++) {
  36390. idx = index + pt * 3;
  36391. colidx = colorIndex + pt * 4;
  36392. uvidx = uvIndex + pt * 2;
  36393. this._vertex.x = this._shape[pt].x;
  36394. this._vertex.y = this._shape[pt].y;
  36395. this._vertex.z = this._shape[pt].z;
  36396. if (this._computeParticleVertex) {
  36397. this.updateParticleVertex(this._particle, this._vertex, pt);
  36398. }
  36399. // positions
  36400. this._vertex.x *= this._particle.scale.x;
  36401. this._vertex.y *= this._particle.scale.y;
  36402. this._vertex.z *= this._particle.scale.z;
  36403. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  36404. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  36405. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  36406. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  36407. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36408. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  36409. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  36410. // normals : if the particles can't be morphed then just rotate the normals
  36411. if (!this._computeParticleVertex && !this.billboard) {
  36412. this._normal.x = this._fixedNormal32[idx];
  36413. this._normal.y = this._fixedNormal32[idx + 1];
  36414. this._normal.z = this._fixedNormal32[idx + 2];
  36415. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  36416. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  36417. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  36418. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  36419. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36420. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  36421. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  36422. }
  36423. if (this._computeParticleColor) {
  36424. this._colors32[colidx] = this._particle.color.r;
  36425. this._colors32[colidx + 1] = this._particle.color.g;
  36426. this._colors32[colidx + 2] = this._particle.color.b;
  36427. this._colors32[colidx + 3] = this._particle.color.a;
  36428. }
  36429. if (this._computeParticleTexture) {
  36430. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36431. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36432. }
  36433. }
  36434. index = idx + 3;
  36435. colorIndex = colidx + 4;
  36436. uvIndex = uvidx + 2;
  36437. }
  36438. if (update) {
  36439. if (this._computeParticleColor) {
  36440. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36441. }
  36442. if (this._computeParticleTexture) {
  36443. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36444. }
  36445. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36446. if (!this.mesh.areNormalsFrozen) {
  36447. if (this._computeParticleVertex || this.billboard) {
  36448. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36449. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36450. for (var i = 0; i < this._normals32.length; i++) {
  36451. this._fixedNormal32[i] = this._normals32[i];
  36452. }
  36453. }
  36454. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36455. }
  36456. }
  36457. this.afterUpdateParticles(start, end, update);
  36458. };
  36459. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36460. this._halfroll = this._roll * 0.5;
  36461. this._halfpitch = this._pitch * 0.5;
  36462. this._halfyaw = this._yaw * 0.5;
  36463. this._sinRoll = Math.sin(this._halfroll);
  36464. this._cosRoll = Math.cos(this._halfroll);
  36465. this._sinPitch = Math.sin(this._halfpitch);
  36466. this._cosPitch = Math.cos(this._halfpitch);
  36467. this._sinYaw = Math.sin(this._halfyaw);
  36468. this._cosYaw = Math.cos(this._halfyaw);
  36469. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36470. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36471. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36472. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36473. };
  36474. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36475. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36476. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36477. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36478. this._rotMatrix.m[3] = 0;
  36479. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36480. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36481. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36482. this._rotMatrix.m[7] = 0;
  36483. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36484. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36485. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36486. this._rotMatrix.m[11] = 0;
  36487. this._rotMatrix.m[12] = 0;
  36488. this._rotMatrix.m[13] = 0;
  36489. this._rotMatrix.m[14] = 0;
  36490. this._rotMatrix.m[15] = 1.0;
  36491. };
  36492. // dispose the SPS
  36493. SolidParticleSystem.prototype.dispose = function () {
  36494. this.mesh.dispose();
  36495. this.vars = null;
  36496. // drop references to internal big arrays for the GC
  36497. this._positions = null;
  36498. this._indices = null;
  36499. this._normals = null;
  36500. this._uvs = null;
  36501. this._colors = null;
  36502. this._positions32 = null;
  36503. this._normals32 = null;
  36504. this._fixedNormal32 = null;
  36505. this._uvs32 = null;
  36506. this._colors32 = null;
  36507. this.pickedParticles = null;
  36508. };
  36509. // Visibilty helpers
  36510. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36511. this.mesh.refreshBoundingInfo();
  36512. };
  36513. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36514. // getter and setter
  36515. get: function () {
  36516. return this._alwaysVisible;
  36517. },
  36518. set: function (val) {
  36519. this._alwaysVisible = val;
  36520. this.mesh.alwaysSelectAsActiveMesh = val;
  36521. },
  36522. enumerable: true,
  36523. configurable: true
  36524. });
  36525. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36526. // getters
  36527. get: function () {
  36528. return this._computeParticleRotation;
  36529. },
  36530. // Optimizer setters
  36531. set: function (val) {
  36532. this._computeParticleRotation = val;
  36533. },
  36534. enumerable: true,
  36535. configurable: true
  36536. });
  36537. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36538. get: function () {
  36539. return this._computeParticleColor;
  36540. },
  36541. set: function (val) {
  36542. this._computeParticleColor = val;
  36543. },
  36544. enumerable: true,
  36545. configurable: true
  36546. });
  36547. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36548. get: function () {
  36549. return this._computeParticleTexture;
  36550. },
  36551. set: function (val) {
  36552. this._computeParticleTexture = val;
  36553. },
  36554. enumerable: true,
  36555. configurable: true
  36556. });
  36557. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36558. get: function () {
  36559. return this._computeParticleVertex;
  36560. },
  36561. set: function (val) {
  36562. this._computeParticleVertex = val;
  36563. },
  36564. enumerable: true,
  36565. configurable: true
  36566. });
  36567. // =======================================================================
  36568. // Particle behavior logic
  36569. // these following methods may be overwritten by the user to fit his needs
  36570. // init : sets all particles first values and calls updateParticle to set them in space
  36571. // can be overwritten by the user
  36572. SolidParticleSystem.prototype.initParticles = function () {
  36573. };
  36574. // recycles a particle : can by overwritten by the user
  36575. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36576. return particle;
  36577. };
  36578. // updates a particle : can be overwritten by the user
  36579. // will be called on each particle by setParticles() :
  36580. // ex : just set a particle position or velocity and recycle conditions
  36581. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36582. return particle;
  36583. };
  36584. // updates a vertex of a particle : can be overwritten by the user
  36585. // will be called on each vertex particle by setParticles() :
  36586. // particle : the current particle
  36587. // vertex : the current index of the current particle
  36588. // pt : the index of the current vertex in the particle shape
  36589. // ex : just set a vertex particle position
  36590. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36591. return vertex;
  36592. };
  36593. // will be called before any other treatment by setParticles()
  36594. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36595. };
  36596. // will be called after all setParticles() treatments
  36597. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36598. };
  36599. return SolidParticleSystem;
  36600. })();
  36601. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36602. })(BABYLON || (BABYLON = {}));
  36603. 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}","bricktexturePixelShader":"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":"precision 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}","cloudtexturePixelShader":"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":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\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\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\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\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\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\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\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\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\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 vec2 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 EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 view;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 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 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\tfloat diskScale = (1.0 - (1.0 + depth * 3.0)) / mapSize;\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\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 unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\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#endif\r\n\r\n// Bump\r\n#ifdef BUMP\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#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\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#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#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#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\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#ifdef SHADOWPCF0\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#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#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\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#ifdef SHADOWPCF1\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#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#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\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#ifdef SHADOWPCF2\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#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#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\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#ifdef SHADOWPCF3\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#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\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\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#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\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// 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#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\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\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 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\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\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\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\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 vec2 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 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#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \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#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\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#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#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#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\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\r\n\t// Log. depth\r\n#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\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#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\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\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#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\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}","firetexturePixelShader":"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}","grasstexturePixelShader":"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\nuniform float multiplier;\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] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * 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\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\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\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\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\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\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\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\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 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 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\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\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\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\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#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#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\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, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\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#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\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, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\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#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\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, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\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 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#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\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, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\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\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#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\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// 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#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\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 = world;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\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\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#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\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 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#ifdef 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#else\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#endif\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}","marbletexturePixelShader":"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#if NUM_BONE_INFLUENCERS > 0\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\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\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\tvec3 offsetPosition = position + normal * offset;\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#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\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}\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}","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}","roadtexturePixelShader":"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#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\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\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#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\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\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\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\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(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, vec2(0.001, 0.001), vec2(0.999, 0.999))).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\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\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}","woodtexturePixelShader":"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}"};
  36604. 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=1/2.2,n=2.2,r=function(){function r(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.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},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.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},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.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},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.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},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}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,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i}();t.Color4=o;var s=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,n){return new i(this.x*t,this.y*n)},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,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},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,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,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,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=s;var e=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}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 a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*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,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,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,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},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,n,r){return new i(this.x*t,this.y*n,this.z*r)},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,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=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];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y,f=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e,h,a,u=i.Normalize(n),m=i.Normalize(o),y=f.X,c=f.Y,p=0,l=0,x=0,z=0,w=0,v=0,g=0,d=-1,T=0,R=0;t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?v=1:t.Tools.WithinEpsilon(m.x,0,t.Engine.Epsilon)?z=1:(g=m.z/m.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),h=new i(z,w,v),h.normalize(),a=i.Cross(m,h),a.normalize(),e=i.Cross(u,h),e.normalize(),i.Dot(m,e)<0&&(d=1),R=i.Dot(u,h),R=Math.min(1,Math.max(-1,R)),x=Math.acos(R)*d,i.Dot(h,y)<0&&(x=Math.PI+x,h=h.scaleInPlace(-1),a=a.scaleInPlace(-1),T++);var _,M;z=0,w=0,v=0,d=-1,t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?z=1:(g=h.z/h.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),_=new i(z,w,v),_.normalize(),M=i.Cross(_,h),M.normalize(),e=i.Cross(m,_),e.normalize(),i.Dot(h,e)<0&&(d=1),R=i.Dot(m,_),R=Math.min(1,Math.max(-1,R)),l=Math.acos(R)*d,i.Dot(M,c)<0&&(l=Math.PI+l,M=M.scaleInPlace(-1),_=_.scaleInPlace(-1),T++),d=-1,e=i.Cross(y,h),e.normalize(),i.Dot(e,c)<0&&(d=1),R=i.Dot(h,y),R=Math.min(1,Math.max(-1,R)),p=-Math.acos(R)*d,0>R&&2>T&&(p=Math.PI+p),s.x=l,s.y=p,s.z=x},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}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,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,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,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},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,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},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,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}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,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,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 n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=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(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),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=e.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,n=this.y,r=this.z,o=this.w,s=i*n,e=i*r,h=o*n,a=o*r,u=o*i,m=n*r,y=i*i,c=n*n,p=y+c;return 0!==p&&1!==p?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*p),t.z=Math.atan2(e-h,u+m)):0===p?(t.x=0,t.y=0,t.z=Math.atan2(s-a,.5-c-r*r)):(t.x=Math.atan2(s-a,.5-c-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+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 n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},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,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=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],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=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]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+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 n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];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],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,g=u*x-c*p,d=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,P=e*x-a*f,C=e*l-h*f,I=s*x-a*p,E=s*l-h*p,L=s*f-e*p,q=h*c-a*y,D=e*c-a*m,S=e*y-h*m,Z=s*c-a*u,N=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*g+o*d)*b,t.m[9]=-(i*w-n*g+o*T)*b,t.m[13]=(i*v-n*d+r*T)*b,t.m[2]=(n*A-r*P+o*C)*b,t.m[6]=-(i*A-r*I+o*E)*b,t.m[10]=(i*P-n*I+o*L)*b,t.m[14]=-(i*C-n*E+r*L)*b,t.m[3]=-(n*q-r*D+o*S)*b,t.m[7]=(i*q-r*Z+o*N)*b,t.m[11]=-(i*D-n*Z+o*W)*b,t.m[15]=(i*S-n*N+r*W)*b,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 n=new i;return this.multiplyToRef(t,n),n},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 n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],P=t.m[10],C=t.m[11],I=t.m[12],E=t.m[13],L=t.m[14],q=t.m[15];return i[n]=r*v+o*R+s*b+e*I,i[n+1]=r*g+o*_+s*A+e*E,i[n+2]=r*d+o*M+s*P+e*L,i[n+3]=r*T+o*F+s*C+e*q,i[n+4]=h*v+a*R+u*b+m*I,i[n+5]=h*g+a*_+u*A+m*E,i[n+6]=h*d+a*M+u*P+m*L,i[n+7]=h*T+a*F+u*C+m*q,i[n+8]=y*v+c*R+p*b+f*I,i[n+9]=y*g+c*_+p*A+f*E,i[n+10]=y*d+c*M+p*P+f*L,i[n+11]=y*T+c*F+p*C+f*q,i[n+12]=l*v+x*R+z*b+w*I,i[n+13]=l*g+x*_+z*A+w*E,i[n+14]=l*d+x*M+z*P+w*L,i[n+15]=l*T+x*F+z*C+w*q,this},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(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=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(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=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 n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},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 n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,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 n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,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 n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,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,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,\nn.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.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,s,h,a,1,o)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,y=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},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 n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new a,i._xAxis=e.Zero(),i._yAxis=e.Zero(),i._zAxis=e.Zero(),i}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}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 n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},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,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,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 n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.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,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},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=c;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=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(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)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(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)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(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)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,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,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 e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=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,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=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 e(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=v;var g=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),y=m.angle.radians()/e;m.orientation===x.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,p=0;e>p;p++){var f=Math.cos(c)*m.radius+m.centerPoint.x,l=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(f,l),c+=y}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],n=this._points[0];t+=n.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.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var y=u.normalize(),c=n-r;return new s(h.x+y.x*c,h.y+y.y*c)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=g;var d=function(){function i(t,i,n){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 r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!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 n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].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 n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=d;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_}(BABYLON||(BABYLON={}));";
  36605. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36606. module.exports = BABYLON;
  36607. };